diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/src/org/gridlab/gridsphere/provider/portlet/jsr/PortletServlet.java b/src/org/gridlab/gridsphere/provider/portlet/jsr/PortletServlet.java index c0682cd4a..84736b3b5 100644 --- a/src/org/gridlab/gridsphere/provider/portlet/jsr/PortletServlet.java +++ b/src/org/gridlab/gridsphere/provider/portlet/jsr/PortletServlet.java @@ -1,680 +1,680 @@ /* * @author <a href="mailto:[email protected]">Jason Novotny</a> * @version $Id$ */ package org.gridlab.gridsphere.provider.portlet.jsr; import org.gridlab.gridsphere.portlet.*; import org.gridlab.gridsphere.portlet.jsrimpl.*; import org.gridlab.gridsphere.portlet.GuestUser; import org.gridlab.gridsphere.portlet.PortletLog; import org.gridlab.gridsphere.portlet.User; import org.gridlab.gridsphere.portlet.impl.SportletLog; import org.gridlab.gridsphere.portlet.impl.SportletProperties; import org.gridlab.gridsphere.portlet.impl.ClientImpl; import org.gridlab.gridsphere.portlet.jsrimpl.*; import org.gridlab.gridsphere.portletcontainer.PortletRegistry; import org.gridlab.gridsphere.portletcontainer.ApplicationPortletConfig; import org.gridlab.gridsphere.portletcontainer.jsrimpl.JSRApplicationPortletImpl; import org.gridlab.gridsphere.portletcontainer.jsrimpl.JSRPortletWebApplicationImpl; import org.gridlab.gridsphere.portletcontainer.jsrimpl.descriptor.PortletDefinition; import org.gridlab.gridsphere.services.core.registry.impl.PortletManager; import javax.portlet.*; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import javax.portlet.Portlet; import javax.portlet.PortletConfig; import javax.portlet.PortletContext; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import javax.portlet.UnavailableException; import javax.servlet.*; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter; import java.io.File; import java.util.*; public class PortletServlet extends HttpServlet implements Servlet, ServletConfig, ServletContextListener, HttpSessionAttributeListener, HttpSessionListener, HttpSessionActivationListener { protected transient static PortletLog log = SportletLog.getInstance(PortletServlet.class); protected transient static PortletRegistry registry = null; protected JSRPortletWebApplicationImpl portletWebApp = null; protected String webAppName = null; PortletManager manager = PortletManager.getInstance(); protected PortletContext portletContext = null; //protected PortalContext portalContext = null; protected Map portlets = null; protected Map portletConfigHash = null; /* require an acl service to get role info */ //private AccessControlManagerService aclService = null; private PortletPreferencesManager prefsManager = null; public void init(ServletConfig config) throws ServletException { super.init(config); String propsFile = config.getServletContext().getRealPath("/WEB-INF/classes/log4j.properties"); File f = new File(propsFile); if (f.exists()) { System.err.println("configuring to use " + propsFile); SportletLog.setConfigureURL(propsFile); } // load descriptor files log.debug("in init of PortletServlet"); //aclService = AccessControlManagerServiceImpl.getInstance(); //registry = PortletRegistry.getInstance(); ServletContext ctx = config.getServletContext(); portlets = new Hashtable(); portletConfigHash = new Hashtable(); portletWebApp = new JSRPortletWebApplicationImpl(ctx, "PortletServlet", Thread.currentThread().getContextClassLoader()); //registry.addApplicationPortlet(appPortlet); Collection appPortlets = portletWebApp.getAllApplicationPortlets(); Iterator it = appPortlets.iterator(); while (it.hasNext()) { JSRApplicationPortletImpl appPortlet = (JSRApplicationPortletImpl) it.next(); String portletClass = appPortlet.getPortletClassName(); try { // instantiate portlet classes Portlet portletInstance = (Portlet) Class.forName(portletClass).newInstance(); portlets.put(portletClass, portletInstance); log.debug("Creating new portlet instance: " + portletClass); // put portlet web app in registry } catch (Exception e) { log.error("Unable to create jsr portlet instance: " + portletClass, e); throw new ServletException("Unable to create jsr portlet instance: " + portletClass, e); } } /* PortletManager manager = PortletManager.getInstance(); manager.initPortletWebApplication(webapp); */ // create portlet context portletContext = new PortletContextImpl(ctx); prefsManager = PortletPreferencesManager.getInstance(); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { registry = PortletRegistry.getInstance(); // If no portlet ID exists, this may be a command to init or shutdown a portlet instance // currently either all portlets are initailized or shutdown, not one individually... String method = (String) request.getAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD); if (method.equals(SportletProperties.INIT)) { Set set = portlets.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { String portletClass = (String) it.next(); Portlet portlet = (Portlet) portlets.get(portletClass); log.debug("in PortletServlet: service(): Initializing portlet " + portletClass); PortletDefinition portletDef = portletWebApp.getPortletDefinition(portletClass); PortletConfig portletConfig = new PortletConfigImpl(getServletConfig(), portletDef, Thread.currentThread().getContextClassLoader()); try { portlet.init(portletConfig); portletConfigHash.put(portletClass, portletConfig); } catch (Exception e) { log.error("in PortletServlet: service(): Unable to INIT portlet " + portletClass, e); // PLT.5.5.2.1 Portlet that fails to initialize must not be placed in active service it.remove(); } } manager.addWebApp(portletWebApp); return; } else if (method.equals(SportletProperties.INIT_CONCRETE)) { // do nothing for concrete portlets return; } else if (method.equals(SportletProperties.DESTROY)) { Iterator it = portlets.keySet().iterator(); while (it.hasNext()) { String portletClass = (String) it.next(); Portlet portlet = (Portlet) portlets.get(portletClass); log.debug("in PortletServlet: service(): Destroying portlet " + portletClass); try { portlet.destroy(); } catch (RuntimeException e) { log.error("Caught exception during portlet destroy", e); } } manager.removePortletWebApplication(portletWebApp); return; } else if (method.equals(SportletProperties.DESTROY_CONCRETE)) { // do nothing for concrete portlets return; } // There must be a portlet ID to know which portlet to service String portletClassName = (String) request.getAttribute(SportletProperties.PORTLETID); String compId = (String) request.getAttribute(SportletProperties.COMPONENT_ID); if (portletClassName == null) { // it may be in the request parameter portletClassName = request.getParameter(SportletProperties.PORTLETID); if (portletClassName == null) { log.debug("in PortletServlet: service(): No PortletID found in request!"); return; } request.setAttribute(SportletProperties.PORTLETID, portletClassName); } log.debug("have a portlet id " + portletClassName + " component id= " + compId); Portlet portlet = (Portlet) portlets.get(portletClassName); JSRApplicationPortletImpl appPortlet = (JSRApplicationPortletImpl) registry.getApplicationPortlet(portletClassName); //Supports[] supports = appPortlet.getSupports(); ApplicationPortletConfig appPortletConfig = appPortlet.getApplicationPortletConfig(); Client client = (Client)request.getSession().getAttribute(SportletProperties.CLIENT); if (client == null) { client = new ClientImpl(request); request.getSession().setAttribute(SportletProperties.CLIENT, client); } List appModes = appPortletConfig.getSupportedModes(client.getMimeType()); // convert modes from GridSphere type to JSR Iterator it = appModes.iterator(); List myModes = new ArrayList(); PortletMode m = PortletMode.VIEW; while (it.hasNext()) { org.gridlab.gridsphere.portlet.Portlet.Mode mode = (org.gridlab.gridsphere.portlet.Portlet.Mode)it.next(); if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW) { m = PortletMode.VIEW; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.EDIT) { m = PortletMode.EDIT; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.HELP) { m = PortletMode.HELP; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.CONFIGURE) { m = new PortletMode("config"); } else { m = new PortletMode(mode.toString()); } myModes.add(m.toString()); } org.gridlab.gridsphere.portlet.Portlet.Mode mode = (org.gridlab.gridsphere.portlet.Portlet.Mode) request.getAttribute(SportletProperties.PORTLET_MODE); if (mode == null) mode = org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW; if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW) { m = PortletMode.VIEW; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.EDIT) { m = PortletMode.EDIT; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.HELP) { m = PortletMode.HELP; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.CONFIGURE) { m = new PortletMode("config"); } else { m = new PortletMode(mode.toString()); } request.setAttribute(SportletProperties.ALLOWED_MODES, myModes); request.setAttribute(SportletProperties.PORTLET_MODE_JSR, m); // perform user conversion from gridsphere to JSR model User user = (User) request.getAttribute(SportletProperties.PORTLET_USER); Map userInfo; if (user instanceof GuestUser) { userInfo = null; } else { userInfo = new HashMap(); userInfo.put("user.name", user.getUserName()); //userInfo.put("user.name.nickName", user.getUserName()); userInfo.put("user.id", user.getID()); userInfo.put("user.email", user.getEmailAddress()); userInfo.put("user.organization", user.getOrganization()); userInfo.put("user.lastlogintime", new Long(user.getLastLoginTime()).toString()); userInfo.put("user.name.full", user.getFullName()); userInfo.put("user.timezone", user.getAttribute(User.TIMEZONE)); userInfo.put("user.locale", user.getAttribute(User.LOCALE)); userInfo.put("user.theme", user.getAttribute(User.THEME)); //userInfo.put("user.name.given", user.getGivenName()); //userInfo.put("user.name.family", user.getFamilyName()); request.setAttribute(PortletRequest.USER_INFO, userInfo); } /* UserAttribute[] userAttrs = portletWebApp.getUserAttributes(); for (int i = 0; i < userAttrs.length; i++) { UserAttribute userAttr = userAttrs[i]; String name = userAttr.getName().getContent(); userInfo.put(name, ""); } request.setAttribute(PortletRequest.USER_INFO, userInfo); */ // portlet preferences PortalContext portalContext = appPortlet.getPortalContext(); request.setAttribute(SportletProperties.PORTAL_CONTEXT, portalContext); request.setAttribute(SportletProperties.PORTLET_CONFIG, portletConfigHash.get(portletClassName)); if (portlet == null) { log.error("in PortletServlet: service(): No portlet matching " + portletClassName + " found!"); return; } if (method.equals(SportletProperties.SERVICE)) { String action = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD); if (action != null) { log.debug("in PortletServlet: action is not NULL"); if (action.equals(SportletProperties.DO_TITLE)) { RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext); RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext); renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest); renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse); log.debug("in PortletServlet: do title " + portletClassName); try { doTitle(portlet, renderRequest, renderResponse); } catch (PortletException e) { log.error("Error during doTitle:", e); } } else if (action.equals(SportletProperties.WINDOW_EVENT)) { // do nothing } else if (action.equals(SportletProperties.MESSAGE_RECEIVED)) { // do nothing } else if (action.equals(SportletProperties.ACTION_PERFORMED)) { PortletPreferences prefs = prefsManager.getPortletPreferences(appPortlet, user, Thread.currentThread().getContextClassLoader(), false); request.setAttribute(SportletProperties.PORTLET_PREFERENCES, prefs); ActionRequestImpl actionRequest = new ActionRequestImpl(request, portalContext, portletContext); ActionResponse actionResponse = new ActionResponseImpl(request, response, portalContext); //setGroupAndRole(actionRequest, actionResponse); log.debug("in PortletServlet: action handling portlet " + portletClassName); try { portlet.processAction(actionRequest, actionResponse); } catch (Exception e) { log.error("Error during processAction:", e); request.setAttribute(SportletProperties.PORTLETERROR + portletClassName, new org.gridlab.gridsphere.portlet.PortletException(e)); } Map params = ((ActionResponseImpl) actionResponse).getRenderParameters(); String cid = (String) request.getAttribute(SportletProperties.COMPONENT_ID); actionRequest.setAttribute("renderParams" + "_" + portletClassName + "_" + cid, params); log.debug("placing render params in attribute: " + "renderParams" + "_" + portletClassName + "_" + cid); //actionRequest.clearParameters(); - //redirect(request, response, actionRequest, actionResponse, portalContext); + redirect(request, response, actionRequest, actionResponse, portalContext); } } else { PortletPreferences prefs = prefsManager.getPortletPreferences(appPortlet, user, Thread.currentThread().getContextClassLoader(), true); request.setAttribute(SportletProperties.PORTLET_PREFERENCES, prefs); RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext); RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext); renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest); renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse); //setGroupAndRole(renderRequest, renderResponse); log.debug("in PortletServlet: rendering portlet " + portletClassName); if (renderRequest.getAttribute(SportletProperties.RESPONSE_COMMITTED) == null) { try { portlet.render(renderRequest, renderResponse); } catch (UnavailableException e) { log.error("in PortletServlet(): doRender() caught unavailable exception: "); try { portlet.destroy(); } catch (Exception d) { log.error("in PortletServlet(): destroy caught unavailable exception: ", d); } } catch (Exception e) { System.err.println("set error = " + SportletProperties.PORTLETERROR + portletClassName); org.gridlab.gridsphere.portlet.PortletException ex = new org.gridlab.gridsphere.portlet.PortletException(e); ex.printStackTrace(); if (request.getAttribute(SportletProperties.PORTLETERROR + portletClassName) == null) { request.setAttribute(SportletProperties.PORTLETERROR + portletClassName, e); } log.error("in PortletServlet(): doRender() caught exception"); throw new ServletException(e); } } } request.removeAttribute(SportletProperties.PORTLET_ACTION_METHOD); } else { log.error("in PortletServlet: service(): No " + SportletProperties.PORTLET_LIFECYCLE_METHOD + " found in request!"); } request.removeAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD); } /* protected void setGroupAndRole(PortletRequest request, PortletResponse response) { String ctxPath = this.getServletContext().getRealPath(""); int i = ctxPath.lastIndexOf(File.separator); String groupName = ctxPath.substring(i+1); PortletGroup group = aclService.getGroupByName(groupName); if (group == null) group = PortletGroupFactory.createPortletGroup(groupName); PortletRole role = aclService.getRoleInGroup(request.getUser(), group); log.debug("Setting Group: " + group.toString() + " Role: " + role.toString()); request.setAttribute(SportletProperties.PORTLET_GROUP, group); request.setAttribute(SportletProperties.PORTLET_ROLE, role); } */ protected void doTitle(Portlet portlet, RenderRequest request, RenderResponse response) throws PortletException { try { Portlet por = (Portlet)portlet; if (por instanceof GenericPortlet) { GenericPortlet genPortlet = ((GenericPortlet) portlet); if (genPortlet.getPortletConfig() == null) throw new PortletException("Unable to get PortletConfig from Porltlet"); ResourceBundle resBundle = genPortlet.getPortletConfig().getResourceBundle(request.getLocale()); String title = resBundle.getString("javax.portlet.title"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(title); } } catch (IOException e) { log.error("printing title failed", e); } } protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doGet(req, res); } protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doPut(req, res); } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doPost(req, res); } protected void doTrace(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doTrace(req, res); } protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { super.doDelete(req, res); } public void destroy() { portletWebApp.destroy(); super.destroy(); //portletManager.destroyPortletWebApplication(portletWebApp); } protected void redirect(HttpServletRequest servletRequest, HttpServletResponse servletResponse, ActionRequest actionRequest, ActionResponse actionResponse, PortalContext portalContext) throws IOException { String location = null; if (actionResponse instanceof ActionResponseImpl) { ActionResponseImpl aResponse = (ActionResponseImpl) actionResponse; location = aResponse.getRedirectLocation(); if (location != null) { //if (location == null) { //if (location.indexOf("://") < 0 ) { /* PortletURLImpl redirectUrl = new PortletURLImpl(servletRequest, servletResponse, portalContext, false); //TODO: don't send changes in case of exception -> PORTLET:SPEC:17 // get the changings of this portlet entity that might be set during action handling // change portlet mode //redirectUrl.setContextPath(actionRequest.getContextPath()); try { if (aResponse.getChangedPortletMode() != null) { redirectUrl.setPortletMode(aResponse.getChangedPortletMode()); } else { redirectUrl.setPortletMode(actionRequest.getPortletMode()); } } catch (PortletModeException e) { e.printStackTrace(); } // change window state try { if (aResponse.getChangedWindowState() != null) { redirectUrl.setWindowState(aResponse.getChangedWindowState()); } else { redirectUrl.setWindowState(actionRequest.getWindowState()); } } catch (WindowStateException e) { e.printStackTrace(); } // get render parameters Map renderParameter = aResponse.getRenderParameters(); redirectUrl.setComponentID((String) servletRequest.getParameter(SportletProperties.COMPONENT_ID)); redirectUrl.setParameters(renderParameter); System.err.println("redirecting url " + redirectUrl.toString()); location = servletResponse.encodeRedirectURL(redirectUrl.toString()); //} */ javax.servlet.http.HttpServletResponse redirectResponse = servletResponse; while (redirectResponse instanceof javax.servlet.http.HttpServletResponseWrapper) { redirectResponse = (javax.servlet.http.HttpServletResponse) ((javax.servlet.http.HttpServletResponseWrapper) redirectResponse).getResponse(); } log.debug("redirecting to location= " + location); redirectResponse.sendRedirect(location); } } } /** * 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); //loginService.sessionDestroyed(event.getSession()); log.debug("sessionDestroyed('" + event.getSession().getId() + "')"); HttpSession s = event.getSession(); //HttpSession session = event.getSession(); //User user = (User) session.getAttribute(SportletProperties.PORTLET_USER); //System.err.println("user : " + user.getUserID() + " expired!"); //PortletLayoutEngine engine = PortletLayoutEngine.getDefault(); //engine.removeUser(user); //engine.logoutPortlets(event); } /** * 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); //loginService.sessionDestroyed(event.getSession()); log.debug("sessionWillPassivate('" + event.getSession().getId() + "')"); //HttpSession session = event.getSession(); //User user = (User) session.getAttribute(SportletProperties.USER); //System.err.println("user : " + user.getUserID() + " expired!"); //PortletLayoutEngine engine = PortletLayoutEngine.getDefault(); //engine.removeUser(user); //engine.logoutPortlets(event); } }
true
true
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { registry = PortletRegistry.getInstance(); // If no portlet ID exists, this may be a command to init or shutdown a portlet instance // currently either all portlets are initailized or shutdown, not one individually... String method = (String) request.getAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD); if (method.equals(SportletProperties.INIT)) { Set set = portlets.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { String portletClass = (String) it.next(); Portlet portlet = (Portlet) portlets.get(portletClass); log.debug("in PortletServlet: service(): Initializing portlet " + portletClass); PortletDefinition portletDef = portletWebApp.getPortletDefinition(portletClass); PortletConfig portletConfig = new PortletConfigImpl(getServletConfig(), portletDef, Thread.currentThread().getContextClassLoader()); try { portlet.init(portletConfig); portletConfigHash.put(portletClass, portletConfig); } catch (Exception e) { log.error("in PortletServlet: service(): Unable to INIT portlet " + portletClass, e); // PLT.5.5.2.1 Portlet that fails to initialize must not be placed in active service it.remove(); } } manager.addWebApp(portletWebApp); return; } else if (method.equals(SportletProperties.INIT_CONCRETE)) { // do nothing for concrete portlets return; } else if (method.equals(SportletProperties.DESTROY)) { Iterator it = portlets.keySet().iterator(); while (it.hasNext()) { String portletClass = (String) it.next(); Portlet portlet = (Portlet) portlets.get(portletClass); log.debug("in PortletServlet: service(): Destroying portlet " + portletClass); try { portlet.destroy(); } catch (RuntimeException e) { log.error("Caught exception during portlet destroy", e); } } manager.removePortletWebApplication(portletWebApp); return; } else if (method.equals(SportletProperties.DESTROY_CONCRETE)) { // do nothing for concrete portlets return; } // There must be a portlet ID to know which portlet to service String portletClassName = (String) request.getAttribute(SportletProperties.PORTLETID); String compId = (String) request.getAttribute(SportletProperties.COMPONENT_ID); if (portletClassName == null) { // it may be in the request parameter portletClassName = request.getParameter(SportletProperties.PORTLETID); if (portletClassName == null) { log.debug("in PortletServlet: service(): No PortletID found in request!"); return; } request.setAttribute(SportletProperties.PORTLETID, portletClassName); } log.debug("have a portlet id " + portletClassName + " component id= " + compId); Portlet portlet = (Portlet) portlets.get(portletClassName); JSRApplicationPortletImpl appPortlet = (JSRApplicationPortletImpl) registry.getApplicationPortlet(portletClassName); //Supports[] supports = appPortlet.getSupports(); ApplicationPortletConfig appPortletConfig = appPortlet.getApplicationPortletConfig(); Client client = (Client)request.getSession().getAttribute(SportletProperties.CLIENT); if (client == null) { client = new ClientImpl(request); request.getSession().setAttribute(SportletProperties.CLIENT, client); } List appModes = appPortletConfig.getSupportedModes(client.getMimeType()); // convert modes from GridSphere type to JSR Iterator it = appModes.iterator(); List myModes = new ArrayList(); PortletMode m = PortletMode.VIEW; while (it.hasNext()) { org.gridlab.gridsphere.portlet.Portlet.Mode mode = (org.gridlab.gridsphere.portlet.Portlet.Mode)it.next(); if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW) { m = PortletMode.VIEW; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.EDIT) { m = PortletMode.EDIT; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.HELP) { m = PortletMode.HELP; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.CONFIGURE) { m = new PortletMode("config"); } else { m = new PortletMode(mode.toString()); } myModes.add(m.toString()); } org.gridlab.gridsphere.portlet.Portlet.Mode mode = (org.gridlab.gridsphere.portlet.Portlet.Mode) request.getAttribute(SportletProperties.PORTLET_MODE); if (mode == null) mode = org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW; if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW) { m = PortletMode.VIEW; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.EDIT) { m = PortletMode.EDIT; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.HELP) { m = PortletMode.HELP; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.CONFIGURE) { m = new PortletMode("config"); } else { m = new PortletMode(mode.toString()); } request.setAttribute(SportletProperties.ALLOWED_MODES, myModes); request.setAttribute(SportletProperties.PORTLET_MODE_JSR, m); // perform user conversion from gridsphere to JSR model User user = (User) request.getAttribute(SportletProperties.PORTLET_USER); Map userInfo; if (user instanceof GuestUser) { userInfo = null; } else { userInfo = new HashMap(); userInfo.put("user.name", user.getUserName()); //userInfo.put("user.name.nickName", user.getUserName()); userInfo.put("user.id", user.getID()); userInfo.put("user.email", user.getEmailAddress()); userInfo.put("user.organization", user.getOrganization()); userInfo.put("user.lastlogintime", new Long(user.getLastLoginTime()).toString()); userInfo.put("user.name.full", user.getFullName()); userInfo.put("user.timezone", user.getAttribute(User.TIMEZONE)); userInfo.put("user.locale", user.getAttribute(User.LOCALE)); userInfo.put("user.theme", user.getAttribute(User.THEME)); //userInfo.put("user.name.given", user.getGivenName()); //userInfo.put("user.name.family", user.getFamilyName()); request.setAttribute(PortletRequest.USER_INFO, userInfo); } /* UserAttribute[] userAttrs = portletWebApp.getUserAttributes(); for (int i = 0; i < userAttrs.length; i++) { UserAttribute userAttr = userAttrs[i]; String name = userAttr.getName().getContent(); userInfo.put(name, ""); } request.setAttribute(PortletRequest.USER_INFO, userInfo); */ // portlet preferences PortalContext portalContext = appPortlet.getPortalContext(); request.setAttribute(SportletProperties.PORTAL_CONTEXT, portalContext); request.setAttribute(SportletProperties.PORTLET_CONFIG, portletConfigHash.get(portletClassName)); if (portlet == null) { log.error("in PortletServlet: service(): No portlet matching " + portletClassName + " found!"); return; } if (method.equals(SportletProperties.SERVICE)) { String action = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD); if (action != null) { log.debug("in PortletServlet: action is not NULL"); if (action.equals(SportletProperties.DO_TITLE)) { RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext); RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext); renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest); renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse); log.debug("in PortletServlet: do title " + portletClassName); try { doTitle(portlet, renderRequest, renderResponse); } catch (PortletException e) { log.error("Error during doTitle:", e); } } else if (action.equals(SportletProperties.WINDOW_EVENT)) { // do nothing } else if (action.equals(SportletProperties.MESSAGE_RECEIVED)) { // do nothing } else if (action.equals(SportletProperties.ACTION_PERFORMED)) { PortletPreferences prefs = prefsManager.getPortletPreferences(appPortlet, user, Thread.currentThread().getContextClassLoader(), false); request.setAttribute(SportletProperties.PORTLET_PREFERENCES, prefs); ActionRequestImpl actionRequest = new ActionRequestImpl(request, portalContext, portletContext); ActionResponse actionResponse = new ActionResponseImpl(request, response, portalContext); //setGroupAndRole(actionRequest, actionResponse); log.debug("in PortletServlet: action handling portlet " + portletClassName); try { portlet.processAction(actionRequest, actionResponse); } catch (Exception e) { log.error("Error during processAction:", e); request.setAttribute(SportletProperties.PORTLETERROR + portletClassName, new org.gridlab.gridsphere.portlet.PortletException(e)); } Map params = ((ActionResponseImpl) actionResponse).getRenderParameters(); String cid = (String) request.getAttribute(SportletProperties.COMPONENT_ID); actionRequest.setAttribute("renderParams" + "_" + portletClassName + "_" + cid, params); log.debug("placing render params in attribute: " + "renderParams" + "_" + portletClassName + "_" + cid); //actionRequest.clearParameters(); //redirect(request, response, actionRequest, actionResponse, portalContext); } } else { PortletPreferences prefs = prefsManager.getPortletPreferences(appPortlet, user, Thread.currentThread().getContextClassLoader(), true); request.setAttribute(SportletProperties.PORTLET_PREFERENCES, prefs); RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext); RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext); renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest); renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse); //setGroupAndRole(renderRequest, renderResponse); log.debug("in PortletServlet: rendering portlet " + portletClassName); if (renderRequest.getAttribute(SportletProperties.RESPONSE_COMMITTED) == null) { try { portlet.render(renderRequest, renderResponse); } catch (UnavailableException e) { log.error("in PortletServlet(): doRender() caught unavailable exception: "); try { portlet.destroy(); } catch (Exception d) { log.error("in PortletServlet(): destroy caught unavailable exception: ", d); } } catch (Exception e) { System.err.println("set error = " + SportletProperties.PORTLETERROR + portletClassName); org.gridlab.gridsphere.portlet.PortletException ex = new org.gridlab.gridsphere.portlet.PortletException(e); ex.printStackTrace(); if (request.getAttribute(SportletProperties.PORTLETERROR + portletClassName) == null) { request.setAttribute(SportletProperties.PORTLETERROR + portletClassName, e); } log.error("in PortletServlet(): doRender() caught exception"); throw new ServletException(e); } } } request.removeAttribute(SportletProperties.PORTLET_ACTION_METHOD); } else { log.error("in PortletServlet: service(): No " + SportletProperties.PORTLET_LIFECYCLE_METHOD + " found in request!"); } request.removeAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD); }
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { registry = PortletRegistry.getInstance(); // If no portlet ID exists, this may be a command to init or shutdown a portlet instance // currently either all portlets are initailized or shutdown, not one individually... String method = (String) request.getAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD); if (method.equals(SportletProperties.INIT)) { Set set = portlets.keySet(); Iterator it = set.iterator(); while (it.hasNext()) { String portletClass = (String) it.next(); Portlet portlet = (Portlet) portlets.get(portletClass); log.debug("in PortletServlet: service(): Initializing portlet " + portletClass); PortletDefinition portletDef = portletWebApp.getPortletDefinition(portletClass); PortletConfig portletConfig = new PortletConfigImpl(getServletConfig(), portletDef, Thread.currentThread().getContextClassLoader()); try { portlet.init(portletConfig); portletConfigHash.put(portletClass, portletConfig); } catch (Exception e) { log.error("in PortletServlet: service(): Unable to INIT portlet " + portletClass, e); // PLT.5.5.2.1 Portlet that fails to initialize must not be placed in active service it.remove(); } } manager.addWebApp(portletWebApp); return; } else if (method.equals(SportletProperties.INIT_CONCRETE)) { // do nothing for concrete portlets return; } else if (method.equals(SportletProperties.DESTROY)) { Iterator it = portlets.keySet().iterator(); while (it.hasNext()) { String portletClass = (String) it.next(); Portlet portlet = (Portlet) portlets.get(portletClass); log.debug("in PortletServlet: service(): Destroying portlet " + portletClass); try { portlet.destroy(); } catch (RuntimeException e) { log.error("Caught exception during portlet destroy", e); } } manager.removePortletWebApplication(portletWebApp); return; } else if (method.equals(SportletProperties.DESTROY_CONCRETE)) { // do nothing for concrete portlets return; } // There must be a portlet ID to know which portlet to service String portletClassName = (String) request.getAttribute(SportletProperties.PORTLETID); String compId = (String) request.getAttribute(SportletProperties.COMPONENT_ID); if (portletClassName == null) { // it may be in the request parameter portletClassName = request.getParameter(SportletProperties.PORTLETID); if (portletClassName == null) { log.debug("in PortletServlet: service(): No PortletID found in request!"); return; } request.setAttribute(SportletProperties.PORTLETID, portletClassName); } log.debug("have a portlet id " + portletClassName + " component id= " + compId); Portlet portlet = (Portlet) portlets.get(portletClassName); JSRApplicationPortletImpl appPortlet = (JSRApplicationPortletImpl) registry.getApplicationPortlet(portletClassName); //Supports[] supports = appPortlet.getSupports(); ApplicationPortletConfig appPortletConfig = appPortlet.getApplicationPortletConfig(); Client client = (Client)request.getSession().getAttribute(SportletProperties.CLIENT); if (client == null) { client = new ClientImpl(request); request.getSession().setAttribute(SportletProperties.CLIENT, client); } List appModes = appPortletConfig.getSupportedModes(client.getMimeType()); // convert modes from GridSphere type to JSR Iterator it = appModes.iterator(); List myModes = new ArrayList(); PortletMode m = PortletMode.VIEW; while (it.hasNext()) { org.gridlab.gridsphere.portlet.Portlet.Mode mode = (org.gridlab.gridsphere.portlet.Portlet.Mode)it.next(); if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW) { m = PortletMode.VIEW; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.EDIT) { m = PortletMode.EDIT; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.HELP) { m = PortletMode.HELP; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.CONFIGURE) { m = new PortletMode("config"); } else { m = new PortletMode(mode.toString()); } myModes.add(m.toString()); } org.gridlab.gridsphere.portlet.Portlet.Mode mode = (org.gridlab.gridsphere.portlet.Portlet.Mode) request.getAttribute(SportletProperties.PORTLET_MODE); if (mode == null) mode = org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW; if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.VIEW) { m = PortletMode.VIEW; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.EDIT) { m = PortletMode.EDIT; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.HELP) { m = PortletMode.HELP; } else if (mode == org.gridlab.gridsphere.portlet.Portlet.Mode.CONFIGURE) { m = new PortletMode("config"); } else { m = new PortletMode(mode.toString()); } request.setAttribute(SportletProperties.ALLOWED_MODES, myModes); request.setAttribute(SportletProperties.PORTLET_MODE_JSR, m); // perform user conversion from gridsphere to JSR model User user = (User) request.getAttribute(SportletProperties.PORTLET_USER); Map userInfo; if (user instanceof GuestUser) { userInfo = null; } else { userInfo = new HashMap(); userInfo.put("user.name", user.getUserName()); //userInfo.put("user.name.nickName", user.getUserName()); userInfo.put("user.id", user.getID()); userInfo.put("user.email", user.getEmailAddress()); userInfo.put("user.organization", user.getOrganization()); userInfo.put("user.lastlogintime", new Long(user.getLastLoginTime()).toString()); userInfo.put("user.name.full", user.getFullName()); userInfo.put("user.timezone", user.getAttribute(User.TIMEZONE)); userInfo.put("user.locale", user.getAttribute(User.LOCALE)); userInfo.put("user.theme", user.getAttribute(User.THEME)); //userInfo.put("user.name.given", user.getGivenName()); //userInfo.put("user.name.family", user.getFamilyName()); request.setAttribute(PortletRequest.USER_INFO, userInfo); } /* UserAttribute[] userAttrs = portletWebApp.getUserAttributes(); for (int i = 0; i < userAttrs.length; i++) { UserAttribute userAttr = userAttrs[i]; String name = userAttr.getName().getContent(); userInfo.put(name, ""); } request.setAttribute(PortletRequest.USER_INFO, userInfo); */ // portlet preferences PortalContext portalContext = appPortlet.getPortalContext(); request.setAttribute(SportletProperties.PORTAL_CONTEXT, portalContext); request.setAttribute(SportletProperties.PORTLET_CONFIG, portletConfigHash.get(portletClassName)); if (portlet == null) { log.error("in PortletServlet: service(): No portlet matching " + portletClassName + " found!"); return; } if (method.equals(SportletProperties.SERVICE)) { String action = (String) request.getAttribute(SportletProperties.PORTLET_ACTION_METHOD); if (action != null) { log.debug("in PortletServlet: action is not NULL"); if (action.equals(SportletProperties.DO_TITLE)) { RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext); RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext); renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest); renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse); log.debug("in PortletServlet: do title " + portletClassName); try { doTitle(portlet, renderRequest, renderResponse); } catch (PortletException e) { log.error("Error during doTitle:", e); } } else if (action.equals(SportletProperties.WINDOW_EVENT)) { // do nothing } else if (action.equals(SportletProperties.MESSAGE_RECEIVED)) { // do nothing } else if (action.equals(SportletProperties.ACTION_PERFORMED)) { PortletPreferences prefs = prefsManager.getPortletPreferences(appPortlet, user, Thread.currentThread().getContextClassLoader(), false); request.setAttribute(SportletProperties.PORTLET_PREFERENCES, prefs); ActionRequestImpl actionRequest = new ActionRequestImpl(request, portalContext, portletContext); ActionResponse actionResponse = new ActionResponseImpl(request, response, portalContext); //setGroupAndRole(actionRequest, actionResponse); log.debug("in PortletServlet: action handling portlet " + portletClassName); try { portlet.processAction(actionRequest, actionResponse); } catch (Exception e) { log.error("Error during processAction:", e); request.setAttribute(SportletProperties.PORTLETERROR + portletClassName, new org.gridlab.gridsphere.portlet.PortletException(e)); } Map params = ((ActionResponseImpl) actionResponse).getRenderParameters(); String cid = (String) request.getAttribute(SportletProperties.COMPONENT_ID); actionRequest.setAttribute("renderParams" + "_" + portletClassName + "_" + cid, params); log.debug("placing render params in attribute: " + "renderParams" + "_" + portletClassName + "_" + cid); //actionRequest.clearParameters(); redirect(request, response, actionRequest, actionResponse, portalContext); } } else { PortletPreferences prefs = prefsManager.getPortletPreferences(appPortlet, user, Thread.currentThread().getContextClassLoader(), true); request.setAttribute(SportletProperties.PORTLET_PREFERENCES, prefs); RenderRequest renderRequest = new RenderRequestImpl(request, portalContext, portletContext); RenderResponse renderResponse = new RenderResponseImpl(request, response, portalContext); renderRequest.setAttribute(SportletProperties.RENDER_REQUEST, renderRequest); renderRequest.setAttribute(SportletProperties.RENDER_RESPONSE, renderResponse); //setGroupAndRole(renderRequest, renderResponse); log.debug("in PortletServlet: rendering portlet " + portletClassName); if (renderRequest.getAttribute(SportletProperties.RESPONSE_COMMITTED) == null) { try { portlet.render(renderRequest, renderResponse); } catch (UnavailableException e) { log.error("in PortletServlet(): doRender() caught unavailable exception: "); try { portlet.destroy(); } catch (Exception d) { log.error("in PortletServlet(): destroy caught unavailable exception: ", d); } } catch (Exception e) { System.err.println("set error = " + SportletProperties.PORTLETERROR + portletClassName); org.gridlab.gridsphere.portlet.PortletException ex = new org.gridlab.gridsphere.portlet.PortletException(e); ex.printStackTrace(); if (request.getAttribute(SportletProperties.PORTLETERROR + portletClassName) == null) { request.setAttribute(SportletProperties.PORTLETERROR + portletClassName, e); } log.error("in PortletServlet(): doRender() caught exception"); throw new ServletException(e); } } } request.removeAttribute(SportletProperties.PORTLET_ACTION_METHOD); } else { log.error("in PortletServlet: service(): No " + SportletProperties.PORTLET_LIFECYCLE_METHOD + " found in request!"); } request.removeAttribute(SportletProperties.PORTLET_LIFECYCLE_METHOD); }
diff --git a/platform-infrastructure/service-lifecycle/platform-webapp/src/main/java/org/societies/webapp/controller/ServiceControlController.java b/platform-infrastructure/service-lifecycle/platform-webapp/src/main/java/org/societies/webapp/controller/ServiceControlController.java index 293e19703..f2bdc78ee 100644 --- a/platform-infrastructure/service-lifecycle/platform-webapp/src/main/java/org/societies/webapp/controller/ServiceControlController.java +++ b/platform-infrastructure/service-lifecycle/platform-webapp/src/main/java/org/societies/webapp/controller/ServiceControlController.java @@ -1,416 +1,416 @@ package org.societies.webapp.controller; /** * Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET * (SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije * informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE * COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp., * INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM * ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC)) * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.societies.api.comm.xmpp.interfaces.ICommManager; import org.societies.api.internal.servicelifecycle.IServiceControl; import org.societies.api.internal.servicelifecycle.IServiceDiscovery; import org.societies.api.internal.servicelifecycle.ServiceControlException; import org.societies.api.schema.servicelifecycle.model.Service; import org.societies.api.schema.servicelifecycle.model.ServiceResourceIdentifier; import org.societies.api.schema.servicelifecycle.servicecontrol.ServiceControlResult; import org.societies.webapp.models.ServiceControlForm; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class ServiceControlController { static final Logger logger = LoggerFactory.getLogger(ServiceControlController.class); /** * OSGI service get auto injected */ @Autowired private IServiceControl scService; public IServiceControl getSCService() { return scService; } public void setSCService(IServiceControl scService) { this.scService = scService; } /** * OSGI service get auto injected */ @Autowired private ICommManager commManager; public ICommManager getCommManager() { return commManager; } public void setCommManager(ICommManager commManager) { this.commManager = commManager; } /** * OSGI service get auto injected */ @Autowired private IServiceDiscovery sdService; public IServiceDiscovery getSDService() { return sdService; } public void getSDService(IServiceDiscovery sdService) { this.sdService = sdService; } @RequestMapping(value = "/servicecontrol.html", method = RequestMethod.GET) public ModelAndView serviceControlGet() { Map<String, Object> model = new HashMap<String, Object>(); model.put("message", "Please input values and submit"); ServiceControlForm scForm = new ServiceControlForm(); Map<String, String> methods = new LinkedHashMap<String, String>(); Map<String, String> services = new LinkedHashMap<String, String>(); List<Service> serviceList = new ArrayList<Service>(); try { Future<List<Service>> asynchResult = this.getSDService().getLocalServices(); serviceList = asynchResult.get(); Iterator<Service> servIt = serviceList.iterator(); while(servIt.hasNext()){ Service next = servIt.next(); String serviceId = next.getServiceIdentifier().getServiceInstanceIdentifier()+ "_" +next.getServiceIdentifier().getIdentifier().toString(); if(logger.isDebugEnabled()) logger.debug("Service: " + serviceId); services.put(serviceId, next.getServiceName()); } } catch (Exception e) { e.printStackTrace(); } methods.put("StartService", "Start a Service"); methods.put("StopService", "Stop a Service"); methods.put("UninstallService", "Uninstall a Service"); methods.put("InstallService", "Install a Service"); //methods.put("InstallServiceRemote", "Install a Service on a Remote Node"); model.put("services", services); model.put("methods", methods); model.put("scForm", scForm); model.put("servicecontrolResult", "Service Control Result :"); return new ModelAndView("servicecontrol", model); } @SuppressWarnings("unchecked") @RequestMapping(value = "/servicecontrol.html", method = RequestMethod.POST) public ModelAndView serviceControlPost(@Valid ServiceControlForm scForm, BindingResult result, Map model) { String returnPage = "servicecontrolresult"; if (result.hasErrors()) { model.put("result", "service control form error"); return new ModelAndView("servicecontrol", model); } if (getSCService() == null) { model.put("errormsg", "Service Control Service reference not available"); return new ModelAndView("error", model); } String node = scForm.getNode(); String method = scForm.getMethod(); String url = scForm.getUrl(); //Service service = scForm.getService(); String serviceUri = scForm.getService(); String endpoint = scForm.getEndpoint(); if(logger.isDebugEnabled()){ logger.debug("node = " + node ); logger.debug("method=" + method ); logger.debug("url: " + url ); logger.debug("Service Id:" + serviceUri ); logger.debug("Endpoint: " + endpoint); } if(method.equalsIgnoreCase("NONE")){ model.put("result", "No method selected"); model.put("scResult", "NOTHING"); return new ModelAndView("servicecontrolresult", model); } ServiceResourceIdentifier serviceId = new ServiceResourceIdentifier(); if(!serviceUri.equals("NONE") && !serviceUri.equals("REMOTE")){ int index = serviceUri.indexOf('_'); String bundleExtract = serviceUri.substring(0, index); String identifierExtract = serviceUri.substring(index+1); if(logger.isDebugEnabled()) logger.debug("Creating ServiceResourceIdentifier with: " +bundleExtract + " - " + identifierExtract); serviceId.setServiceInstanceIdentifier(bundleExtract); try { serviceId.setIdentifier(new URI(identifierExtract)); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if(!method.equalsIgnoreCase("InstallService") && !endpoint.isEmpty() && (serviceUri.equals("REMOTE") || serviceUri.equals("NONE"))){ if(logger.isDebugEnabled()) logger.debug("It's a remote service, so we need to check it: " + endpoint); Future<List<Service>> asynchResult = null; List<Service> services = new ArrayList<Service>(); int index = endpoint.indexOf('/'); String remoteJid = endpoint.substring(0, index); if(logger.isDebugEnabled()) logger.debug("Remote JID is: " + remoteJid); try { asynchResult=this.getSDService().getServices(remoteJid); services = asynchResult.get(); } catch (Exception e) { logger.error("exception getting services from remote node: " + e.getMessage()); e.printStackTrace(); } for(Service remoteService: services){ if(logger.isDebugEnabled()) logger.debug("Remote service: " + remoteService.getServiceName()); if(remoteService.getServiceEndpoint().equals(endpoint)){ if(logger.isDebugEnabled()) logger.debug("Found the correct service: " + remoteService.getServiceEndpoint()); serviceId = remoteService.getServiceIdentifier(); break; } } } Future<ServiceControlResult> asynchResult = null; ServiceControlResult scresult; String res = ""; try { if (method.equalsIgnoreCase("InstallService")) { URL serviceUrl = new URL(url); /* if(logger.isDebugEnabled()) logger.debug("InstallService Method on:" + serviceUrl); asynchResult=this.getSCService().installService(serviceUrl); res="ServiceControl Result Installing in Local Node: "; */ if(logger.isDebugEnabled()) logger.debug("InstallService Remote Method on:" + serviceUrl +" on node " + node); asynchResult=this.getSCService().installService(serviceUrl, node); if(!node.isEmpty()) res="ServiceControl Result for Node : [" + node + "]"; else res="ServiceControl Result Installing in Local Node: "; scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); }else if (method.equalsIgnoreCase("InstallServiceRemote")) { URL serviceUrl = new URL(url); if(logger.isDebugEnabled()) logger.debug("InstallService Remote Method on:" + serviceUrl +" on node " + node); asynchResult=this.getSCService().installService(serviceUrl, node); res="ServiceControl Result for Node : [" + node + "]"; scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); }else if (method.equalsIgnoreCase("StartService")){ if(logger.isDebugEnabled()) logger.debug("StartService:" + serviceId); asynchResult=this.getSCService().startService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Started service: " + serviceId; returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("UnshareService")){ if(logger.isDebugEnabled()) logger.debug("UnshareService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToShare = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().unshareService(serviceToShare, node); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); model.put("myNode", getCommManager().getIdManager().getThisNetworkNode()); res = "Success";//scresult.getMessage().toString(); returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("StopService")){ if(logger.isDebugEnabled()) logger.debug("StopService:" + serviceId); asynchResult=this.getSCService().stopService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Stopped service: " + serviceId; returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("UninstallService")){ if(logger.isDebugEnabled()) logger.debug("UninstallService:" + serviceId); asynchResult=this.getSCService().uninstallService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Uninstall service: " + serviceId; returnPage = "servicediscoveryresult"; //>>>>>>>>>>>> SHARE SERVICE <<<<<<<<<<<<<<< } else if (method.equalsIgnoreCase("ShareService")){ if(logger.isDebugEnabled()) logger.debug("ShareService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToShare = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().shareService(serviceToShare, node); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); model.put("myNode", getCommManager().getIdManager().getThisNetworkNode()); res = "Success";//scresult.getMessage().toString(); returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("Install3PService")){ if(logger.isDebugEnabled()) logger.debug("Install3PService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToInstall = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().installService(serviceToInstall); //scresult = asynchResult.get(); - if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); + //if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); /* //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); */ //res = scresult.getMessage().toString(); res = "Waiting..."; returnPage = "servicecontrolresult"; } else { res="error unknown metod"; } if (returnPage.equals("servicediscoveryresult")) { Future<List<Service>> asynchServices = this.getSDService().getLocalServices(); List<Service> services = asynchServices.get(); model.put("services", services); } } catch (ServiceControlException e) { res = "Oops!!!! Service Control Exception <br/>" + e.getMessage(); } catch (Exception ex) { res = "Oops!!!! " +ex.getMessage() +" <br/>"; }; model.put("result", res); return new ModelAndView(returnPage, model); } }
true
true
public ModelAndView serviceControlPost(@Valid ServiceControlForm scForm, BindingResult result, Map model) { String returnPage = "servicecontrolresult"; if (result.hasErrors()) { model.put("result", "service control form error"); return new ModelAndView("servicecontrol", model); } if (getSCService() == null) { model.put("errormsg", "Service Control Service reference not available"); return new ModelAndView("error", model); } String node = scForm.getNode(); String method = scForm.getMethod(); String url = scForm.getUrl(); //Service service = scForm.getService(); String serviceUri = scForm.getService(); String endpoint = scForm.getEndpoint(); if(logger.isDebugEnabled()){ logger.debug("node = " + node ); logger.debug("method=" + method ); logger.debug("url: " + url ); logger.debug("Service Id:" + serviceUri ); logger.debug("Endpoint: " + endpoint); } if(method.equalsIgnoreCase("NONE")){ model.put("result", "No method selected"); model.put("scResult", "NOTHING"); return new ModelAndView("servicecontrolresult", model); } ServiceResourceIdentifier serviceId = new ServiceResourceIdentifier(); if(!serviceUri.equals("NONE") && !serviceUri.equals("REMOTE")){ int index = serviceUri.indexOf('_'); String bundleExtract = serviceUri.substring(0, index); String identifierExtract = serviceUri.substring(index+1); if(logger.isDebugEnabled()) logger.debug("Creating ServiceResourceIdentifier with: " +bundleExtract + " - " + identifierExtract); serviceId.setServiceInstanceIdentifier(bundleExtract); try { serviceId.setIdentifier(new URI(identifierExtract)); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if(!method.equalsIgnoreCase("InstallService") && !endpoint.isEmpty() && (serviceUri.equals("REMOTE") || serviceUri.equals("NONE"))){ if(logger.isDebugEnabled()) logger.debug("It's a remote service, so we need to check it: " + endpoint); Future<List<Service>> asynchResult = null; List<Service> services = new ArrayList<Service>(); int index = endpoint.indexOf('/'); String remoteJid = endpoint.substring(0, index); if(logger.isDebugEnabled()) logger.debug("Remote JID is: " + remoteJid); try { asynchResult=this.getSDService().getServices(remoteJid); services = asynchResult.get(); } catch (Exception e) { logger.error("exception getting services from remote node: " + e.getMessage()); e.printStackTrace(); } for(Service remoteService: services){ if(logger.isDebugEnabled()) logger.debug("Remote service: " + remoteService.getServiceName()); if(remoteService.getServiceEndpoint().equals(endpoint)){ if(logger.isDebugEnabled()) logger.debug("Found the correct service: " + remoteService.getServiceEndpoint()); serviceId = remoteService.getServiceIdentifier(); break; } } } Future<ServiceControlResult> asynchResult = null; ServiceControlResult scresult; String res = ""; try { if (method.equalsIgnoreCase("InstallService")) { URL serviceUrl = new URL(url); /* if(logger.isDebugEnabled()) logger.debug("InstallService Method on:" + serviceUrl); asynchResult=this.getSCService().installService(serviceUrl); res="ServiceControl Result Installing in Local Node: "; */ if(logger.isDebugEnabled()) logger.debug("InstallService Remote Method on:" + serviceUrl +" on node " + node); asynchResult=this.getSCService().installService(serviceUrl, node); if(!node.isEmpty()) res="ServiceControl Result for Node : [" + node + "]"; else res="ServiceControl Result Installing in Local Node: "; scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); }else if (method.equalsIgnoreCase("InstallServiceRemote")) { URL serviceUrl = new URL(url); if(logger.isDebugEnabled()) logger.debug("InstallService Remote Method on:" + serviceUrl +" on node " + node); asynchResult=this.getSCService().installService(serviceUrl, node); res="ServiceControl Result for Node : [" + node + "]"; scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); }else if (method.equalsIgnoreCase("StartService")){ if(logger.isDebugEnabled()) logger.debug("StartService:" + serviceId); asynchResult=this.getSCService().startService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Started service: " + serviceId; returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("UnshareService")){ if(logger.isDebugEnabled()) logger.debug("UnshareService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToShare = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().unshareService(serviceToShare, node); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); model.put("myNode", getCommManager().getIdManager().getThisNetworkNode()); res = "Success";//scresult.getMessage().toString(); returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("StopService")){ if(logger.isDebugEnabled()) logger.debug("StopService:" + serviceId); asynchResult=this.getSCService().stopService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Stopped service: " + serviceId; returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("UninstallService")){ if(logger.isDebugEnabled()) logger.debug("UninstallService:" + serviceId); asynchResult=this.getSCService().uninstallService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Uninstall service: " + serviceId; returnPage = "servicediscoveryresult"; //>>>>>>>>>>>> SHARE SERVICE <<<<<<<<<<<<<<< } else if (method.equalsIgnoreCase("ShareService")){ if(logger.isDebugEnabled()) logger.debug("ShareService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToShare = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().shareService(serviceToShare, node); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); model.put("myNode", getCommManager().getIdManager().getThisNetworkNode()); res = "Success";//scresult.getMessage().toString(); returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("Install3PService")){ if(logger.isDebugEnabled()) logger.debug("Install3PService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToInstall = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().installService(serviceToInstall); //scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); /* //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); */ //res = scresult.getMessage().toString(); res = "Waiting..."; returnPage = "servicecontrolresult"; } else { res="error unknown metod"; } if (returnPage.equals("servicediscoveryresult")) { Future<List<Service>> asynchServices = this.getSDService().getLocalServices(); List<Service> services = asynchServices.get(); model.put("services", services); } } catch (ServiceControlException e) { res = "Oops!!!! Service Control Exception <br/>" + e.getMessage(); } catch (Exception ex) { res = "Oops!!!! " +ex.getMessage() +" <br/>"; }; model.put("result", res); return new ModelAndView(returnPage, model); }
public ModelAndView serviceControlPost(@Valid ServiceControlForm scForm, BindingResult result, Map model) { String returnPage = "servicecontrolresult"; if (result.hasErrors()) { model.put("result", "service control form error"); return new ModelAndView("servicecontrol", model); } if (getSCService() == null) { model.put("errormsg", "Service Control Service reference not available"); return new ModelAndView("error", model); } String node = scForm.getNode(); String method = scForm.getMethod(); String url = scForm.getUrl(); //Service service = scForm.getService(); String serviceUri = scForm.getService(); String endpoint = scForm.getEndpoint(); if(logger.isDebugEnabled()){ logger.debug("node = " + node ); logger.debug("method=" + method ); logger.debug("url: " + url ); logger.debug("Service Id:" + serviceUri ); logger.debug("Endpoint: " + endpoint); } if(method.equalsIgnoreCase("NONE")){ model.put("result", "No method selected"); model.put("scResult", "NOTHING"); return new ModelAndView("servicecontrolresult", model); } ServiceResourceIdentifier serviceId = new ServiceResourceIdentifier(); if(!serviceUri.equals("NONE") && !serviceUri.equals("REMOTE")){ int index = serviceUri.indexOf('_'); String bundleExtract = serviceUri.substring(0, index); String identifierExtract = serviceUri.substring(index+1); if(logger.isDebugEnabled()) logger.debug("Creating ServiceResourceIdentifier with: " +bundleExtract + " - " + identifierExtract); serviceId.setServiceInstanceIdentifier(bundleExtract); try { serviceId.setIdentifier(new URI(identifierExtract)); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if(!method.equalsIgnoreCase("InstallService") && !endpoint.isEmpty() && (serviceUri.equals("REMOTE") || serviceUri.equals("NONE"))){ if(logger.isDebugEnabled()) logger.debug("It's a remote service, so we need to check it: " + endpoint); Future<List<Service>> asynchResult = null; List<Service> services = new ArrayList<Service>(); int index = endpoint.indexOf('/'); String remoteJid = endpoint.substring(0, index); if(logger.isDebugEnabled()) logger.debug("Remote JID is: " + remoteJid); try { asynchResult=this.getSDService().getServices(remoteJid); services = asynchResult.get(); } catch (Exception e) { logger.error("exception getting services from remote node: " + e.getMessage()); e.printStackTrace(); } for(Service remoteService: services){ if(logger.isDebugEnabled()) logger.debug("Remote service: " + remoteService.getServiceName()); if(remoteService.getServiceEndpoint().equals(endpoint)){ if(logger.isDebugEnabled()) logger.debug("Found the correct service: " + remoteService.getServiceEndpoint()); serviceId = remoteService.getServiceIdentifier(); break; } } } Future<ServiceControlResult> asynchResult = null; ServiceControlResult scresult; String res = ""; try { if (method.equalsIgnoreCase("InstallService")) { URL serviceUrl = new URL(url); /* if(logger.isDebugEnabled()) logger.debug("InstallService Method on:" + serviceUrl); asynchResult=this.getSCService().installService(serviceUrl); res="ServiceControl Result Installing in Local Node: "; */ if(logger.isDebugEnabled()) logger.debug("InstallService Remote Method on:" + serviceUrl +" on node " + node); asynchResult=this.getSCService().installService(serviceUrl, node); if(!node.isEmpty()) res="ServiceControl Result for Node : [" + node + "]"; else res="ServiceControl Result Installing in Local Node: "; scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); }else if (method.equalsIgnoreCase("InstallServiceRemote")) { URL serviceUrl = new URL(url); if(logger.isDebugEnabled()) logger.debug("InstallService Remote Method on:" + serviceUrl +" on node " + node); asynchResult=this.getSCService().installService(serviceUrl, node); res="ServiceControl Result for Node : [" + node + "]"; scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); }else if (method.equalsIgnoreCase("StartService")){ if(logger.isDebugEnabled()) logger.debug("StartService:" + serviceId); asynchResult=this.getSCService().startService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Started service: " + serviceId; returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("UnshareService")){ if(logger.isDebugEnabled()) logger.debug("UnshareService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToShare = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().unshareService(serviceToShare, node); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); model.put("myNode", getCommManager().getIdManager().getThisNetworkNode()); res = "Success";//scresult.getMessage().toString(); returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("StopService")){ if(logger.isDebugEnabled()) logger.debug("StopService:" + serviceId); asynchResult=this.getSCService().stopService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Stopped service: " + serviceId; returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("UninstallService")){ if(logger.isDebugEnabled()) logger.debug("UninstallService:" + serviceId); asynchResult=this.getSCService().uninstallService(serviceId); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); model.put("serviceResult", scresult.getMessage()); res="Uninstall service: " + serviceId; returnPage = "servicediscoveryresult"; //>>>>>>>>>>>> SHARE SERVICE <<<<<<<<<<<<<<< } else if (method.equalsIgnoreCase("ShareService")){ if(logger.isDebugEnabled()) logger.debug("ShareService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToShare = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().shareService(serviceToShare, node); scresult = asynchResult.get(); if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); model.put("myNode", getCommManager().getIdManager().getThisNetworkNode()); res = "Success";//scresult.getMessage().toString(); returnPage = "servicediscoveryresult"; } else if (method.equalsIgnoreCase("Install3PService")){ if(logger.isDebugEnabled()) logger.debug("Install3PService:" + serviceId); //GENERATE SERVICE OBJECT Future<Service> asyncService = this.getSDService().getService(serviceId); Service serviceToInstall = asyncService.get(); //SHARE SERVICE asynchResult = this.getSCService().installService(serviceToInstall); //scresult = asynchResult.get(); //if(logger.isDebugEnabled()) logger.debug("Result of operation was " + scresult.getMessage()); /* //GET REMOTE SERVICES Future<List<Service>> asynchServices = this.getSDService().getServices(node); List<Service> cisServices = asynchServices.get(); model.put("cisservices", cisServices); */ //res = scresult.getMessage().toString(); res = "Waiting..."; returnPage = "servicecontrolresult"; } else { res="error unknown metod"; } if (returnPage.equals("servicediscoveryresult")) { Future<List<Service>> asynchServices = this.getSDService().getLocalServices(); List<Service> services = asynchServices.get(); model.put("services", services); } } catch (ServiceControlException e) { res = "Oops!!!! Service Control Exception <br/>" + e.getMessage(); } catch (Exception ex) { res = "Oops!!!! " +ex.getMessage() +" <br/>"; }; model.put("result", res); return new ModelAndView(returnPage, model); }
diff --git a/whitespace_short_circuit/src/main/java/bobcat/applications/WhitespaceShortCircuit.java b/whitespace_short_circuit/src/main/java/bobcat/applications/WhitespaceShortCircuit.java index 37c229c..d4e1d84 100644 --- a/whitespace_short_circuit/src/main/java/bobcat/applications/WhitespaceShortCircuit.java +++ b/whitespace_short_circuit/src/main/java/bobcat/applications/WhitespaceShortCircuit.java @@ -1,669 +1,671 @@ package bobcat.applications; import bobcat.network.*; import bobcat.simulation.Draw; import edu.uci.ics.jung.algorithms.shortestpath.DijkstraShortestPath; import edu.uci.ics.jung.algorithms.shortestpath.PrimMinimumSpanningTree; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.Pair; import ilog.concert.*; import ilog.cplex.IloCplex; import org.apache.commons.collections15.Transformer; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import java.util.*; public class WhitespaceShortCircuit { static int MAX_CLIQUE_SIZE = 5; static Logger logger = Logger.getLogger("RoutingChannelSelection"); public static Boolean inPath(Graph network, List<Edge> path, Vertex v) { HashSet nodes = new HashSet(); for (Object obj : path) { Edge e = (Edge) obj; Pair<Vertex> ends = network.getEndpoints(e); nodes.add((Vertex) ends.getFirst()); nodes.add((Vertex) ends.getSecond()); } return nodes.contains(v); } public static void combinations(Vector<Integer> current, HashSet combos) { combos.add(current); for (Object o : current) { Vector<Integer> next = (Vector<Integer>) current.clone(); next.remove(o); if (!next.isEmpty()) { combinations((Vector<Integer>) next.clone(), combos); } } } public static PathChannelSet rcsPath(Graph network, Vertex src, Vertex dst, int consider) { ChannelSelection cs = new ChannelSelection((Network) network); // Initialize for (Object o : network.getVertices()) { Vertex v = (Vertex) o; v.rcsPaths = new TreeMap(); if (v == src) { PathChannelSet p0 = new PathChannelSet(); v.rcsPaths.put(0.0d, p0); } } for (int i = 0; i < network.getVertexCount(); i++) { // For each edge see if we can extend the existing path/channel sets // with the available path/channel sets for (Object o : network.getEdges()) { Edge e = (Edge) o; Pair<Vertex> ends = network.getEndpoints(e); Vertex u = (Vertex) ends.getFirst(); Vertex v = (Vertex) ends.getSecond(); HashSet<Vector<Integer>> chset = new HashSet<Vector<Integer>>(); Vector<Integer> cset = new Vector<Integer>(); for (int j = 0; j < e.channels.length; j++) { if (e.channels[j] > 0.0d) { cset.add(j); } } combinations(cset, chset); // First direction for (Object c : u.rcsPaths.keySet()) { PathChannelSet opcs = (PathChannelSet) u.rcsPaths.get(c); ArrayList<Edge> opath = opcs.getPath(); if (opath.size() == i && !inPath(network, opath, v)) { PathCS opathCS = opcs.pathCS; for (Object chs : chset) { Vector<Integer> channels = (Vector<Integer>) chs; PathChannelSet npcs = new PathChannelSet(opcs); npcs.path.add(e); TreeSet<LinkChannel> nextChannelTS = new TreeSet(); for (int k = 0; k < channels.size(); k++) { nextChannelTS.add(new LinkChannel(npcs.path.size() - 1, channels.elementAt(k))); } npcs.pathCS.selected.add(nextChannelTS); double thpt = cs.evalPathCS(npcs.path, npcs.pathCS); v.rcsPaths.put(thpt, npcs); // If we added one and we're over, take one out if (v.rcsPaths.keySet().size() > consider) { v.rcsPaths.remove(v.rcsPaths.firstKey()); } } } } // Second direction for (Object c : v.rcsPaths.keySet()) { PathChannelSet opcs = (PathChannelSet) v.rcsPaths.get(c); ArrayList<Edge> opath = opcs.getPath(); if (opath.size() == i && !inPath(network, opath, u)) { PathCS opathCS = opcs.pathCS; for (Object chs : chset) { Vector<Integer> channels = (Vector<Integer>) chs; PathChannelSet npcs = new PathChannelSet(opcs); npcs.path.add(e); TreeSet<LinkChannel> nextChannelTS = new TreeSet(); for (int k = 0; k < channels.size(); k++) { nextChannelTS.add(new LinkChannel(npcs.path.size() - 1, channels.elementAt(k))); } npcs.pathCS.selected.add(nextChannelTS); double thpt = cs.evalPathCS(npcs.path, npcs.pathCS); u.rcsPaths.put(thpt, npcs); // If we added one and we're over, take one out if (u.rcsPaths.keySet().size() > consider) { u.rcsPaths.remove(u.rcsPaths.firstKey()); } } } } } } if (dst.rcsPaths.size() == 0) { System.out.println("Didn't find RCS Path."); return (null); } return (PathChannelSet) dst.rcsPaths.get(dst.rcsPaths.lastKey()); } public static Boolean grows_clique(HashSet clique, Edge edge, Network network, int channel) { if (clique.size() > network.getEdgeCount()) { // System.out.println("Clique already max size."); return (false); } if (edge.channels[channel] <= 1.0) { // System.out.println("Edge has no throughput."); return (false); } for (Object o : clique) { Edge e = (Edge) o; if (e.id == edge.id) { // System.out.println("Clique already contains edge."); return (false); } if ((!network.interferes[e.id][edge.id][channel]) && (!network.interferes[edge.id][e.id][channel])) { // System.out.println("No interference for the edge/clique on this channel."); return (false); } } return (true); } public static HashMap enumerate_cliques(Network network) { HashMap clique_list = new HashMap(); // For each edge for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap channel_cliques = new HashMap(); // For each channel for (int k = 0; k < network.numChannels * 3; k++) { HashMap size_cliques = new HashMap(); HashSet cliques = new HashSet(); HashSet clique = new HashSet(); clique.clear(); // Clique of size 1, if it's using channel k if (Math.abs(e.channels[k]) > 1.0) { clique.add(e); cliques.add(new HashSet(clique)); // System.out.println("Adding clique of size 1 for channel: "+k+" ("+e.channels[k]+") "+clique); size_cliques.put(1, new HashSet(cliques)); cliques.clear(); // Check all sizes up to max for (int i = 2; i < MAX_CLIQUE_SIZE; i++) { // For each clique of the size i-1 for (Object p : (HashSet) size_cliques.get(i - 1)) { clique = (HashSet) p; // Check to see if adding an edge will grow them for (Object q : network.getEdges()) { Edge edge = (Edge) q; // If it grows the clique if (grows_clique(clique, edge, network, k)) { HashSet cliqueCopy = new HashSet(clique); // clique.clear(); cliqueCopy.add(edge); if (cliqueCopy.size() == i) { // Store a copy under this size list cliques.add(cliqueCopy); // System.out.println("New clique of size: " + i + " " + cliqueCopy); } } else { // System.out.println("Adding "+edge+" doesn't grow clique "+clique); } } } size_cliques.put(i, new HashSet(cliques)); cliques.clear(); } // store cliques channel_cliques.put(k, new HashMap(size_cliques)); size_cliques.clear(); } else { // System.out.println("No clique for edge with no throughput."); // System.out.println("Edge "+e.id+ " Channel "+k + ": "+e.channels[k]); } } // roll out of the loop, storing results clique_list.put(e.id, new HashMap(channel_cliques)); channel_cliques.clear(); } return (clique_list); } public static void main(String[] args) { NetworkGenerator networkGenerator; Network network; WhitespaceShortCircuitOptions options = new WhitespaceShortCircuitOptions(); CmdLineParser parser = new CmdLineParser(options); Draw drawing = null; ChannelSelection cs = null; double rcsThpt; double[][] rcsBisectionBandwidth; PrimMinimumSpanningTree psp = null; Graph primTree = null; parser.setUsageWidth(80); BasicConfigurator.configure(); logger.setLevel(Level.DEBUG); try { parser.parseArgument(args); } catch (CmdLineException e) { logger.error("Failed to parse command line arguments."); logger.error(e.getMessage()); parser.printUsage(System.err); System.exit(1); } int count = 0; do { networkGenerator = Network.getGenerator(options.relays, options.subscribers, options.width, options.height, options.seed + count, options.channels, options.channelProb); network = networkGenerator.create(); rcsBisectionBandwidth = new double[network.getVertices().size()][network.getVertices().size()]; Transformer<Edge, Double> wtTransformer = new Transformer<Edge, Double>() { public Double transform(Edge e) { if (e.capacity > 0.0) { return e.length; } else { return Double.MAX_VALUE; } } }; Transformer<Edge, Double> pTransformer = new Transformer<Edge, Double>() { public Double transform(Edge e) { return e.bottleNeckWeight(); } }; // Set all edge and vertex types to 0 for (Object o : network.getVertices()) { Vertex v = (Vertex) o; v.type = 0; } for (Object o : network.getEdges()) { Edge e = (Edge) o; e.type = 0; } psp = new PrimMinimumSpanningTree(networkGenerator.networkFactory, pTransformer); primTree = psp.transform(network); count++; } while (network.getVertexCount() != primTree.getVertexCount()); // Handle options that matter if (options.verbose) { System.out.println("Random Seed: " + options.seed); } if (options.verbose) { System.out.println("Prim Tree: "); System.out.print(primTree.toString()); System.out.println(""); } for (Object e : primTree.getEdges()) { // Color the MST ((Edge) e).type = 2; } Collection<Edge> primEdges = primTree.getEdges(); Vector toRemove = new Vector(); for (Object e : network.getEdges()) { if (!primEdges.contains(e)) { toRemove.addElement(e); } } for (Object e : toRemove) { network.removeEdge((Edge) e); } // Renumber nodes int nid = 0; for(Object o : network.getVertices()) { Vertex v = (Vertex)o; v.id = nid; nid += 1; } // Renumber edges int eid = 0; for (Object o : network.getEdges()) { Edge e = (Edge) o; e.setId(eid); eid += 1; } network.computeInterference(); // go over all the nxn nodes and find the throughput using rcs for (Object o : network.getVertices()) { Vertex source = (Vertex) o; for (Object p : network.getVertices()) { Vertex destination = (Vertex) p; if (source.id < destination.id) { DijkstraShortestPath<Vertex, Edge> dspath = new DijkstraShortestPath(primTree); List<Edge> spath = dspath.getPath(source, destination); if (options.verbose) { System.out.println(source + " -> " + destination + " : " + spath); } } } } // Print out the edge list if (options.verbose) { System.out.println(network.getEdgeCount() + " Edges"); for (Object e : network.getEdges()) { System.out.println("\t" + (Edge) e); } } // Print out the conflict graph // for(int i = 0; i < network.getEdgeCount() + 1; i++) { // for(int j = 0; j < network.getEdgeCount() + 1; j++) { // for (int k = 0; k < network.numChannels * 3 + 1; k++) { // System.out.println("("+i+","+j+","+k+") = "+network.interferes[i][j][k]); // } // } // } // Initialize a hash of cliques by channel, the value is a set so we don't get duplicates // indexed by edge, then channel, then a list of cliques HashMap clique_list = enumerate_cliques(network); if (options.verbose) { //Print out all cliques to make sure we're good for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { System.out.println("Cliques involving Edge: " + e.id + " using channel " + k + ":"); // Keys are size, values are a list of cliques of that size HashMap cliques_of_size_key = (HashMap) edge_cliques.get(k); if (cliques_of_size_key != null) { for (Object t : cliques_of_size_key.keySet()) { Integer size = (Integer) t; HashSet clique = (HashSet) cliques_of_size_key.get(size); System.out.print("\t[ Size: " + size + " #: " + clique.size() + "] "); System.out.println(clique); } } } } } // Build ILP try { IloCplex cplex = new IloCplex(); // Variable Definitions for ILP // c IloIntVar[] c = new IloIntVar[network.numChannels * 3]; for (int i = 0; i < network.numChannels * 3; i++) { c[i] = cplex.intVar(0, 1, "c(" + i + ")"); } Double[] demand = new Double[network.getEdgeCount()]; for (Object o: network.getEdges()) { Edge e = (Edge)o; - demand[e.id] = 10.0; + demand[e.id] = 2e7; } // x IloIntVar[][][] x = new IloIntVar[network.getEdgeCount()][network.numChannels * 3][MAX_CLIQUE_SIZE]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { // System.out.println(x.length+","+x[0].length+","+x[0][0].length+ " "+e.id+","+k+","+tc); x[e.id][k][tc] = cplex.intVar(0, 1, "x(" + e.id + ")(" + k + ")(" + tc + ")"); } } } // D Double[][][] D = new Double[network.getEdgeCount()][network.numChannels * 3][MAX_CLIQUE_SIZE]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int size = 1; size < MAX_CLIQUE_SIZE; size++) { if (e.channels[k] >= 0) { D[e.id][k][size] = e.channels[k] / size; } else { D[e.id][k][size] = 0.0d; } } } } // y IloIntVar[][] y = new IloIntVar[network.getEdgeCount()][network.numChannels * 3]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { y[e.id][k] = cplex.intVar(0, network.getEdgeCount(), "y(" + e.id + ")(" + k + ")"); } } // Objective function in Equation 3 - Minimize Overall Channel Costs IloLinearNumExpr cost = cplex.linearNumExpr(); // Initialize Channel Costs: Channel costs are all the same 1.0 for now double[] channel_costs = new double[network.numChannels * 3]; Random randomGenerator = new Random(); for (int k = 0; k < network.numChannels * 3; k++) { - channel_costs[k] = randomGenerator.nextFloat(); - channel_costs[k] = 1.0; + if (k % 3 == 0) { + channel_costs[k] = 1.0; + } + if (k % 3 == 1) { + channel_costs[k] = 1.0; + } + if (k % 3 == 2) { + channel_costs[k] = 1.0; + } } // Objective: Minimize channel costs // Channel usage array (Number of edges * number of channels per edge) - for (Object o : network.getEdges()) { - Edge e = (Edge) o; - for (int k = 0; k < e.channels.length; k++) { - if (e.channels[k] > 0.0) { - cost.addTerm(channel_costs[k], c[k]); - } - } + for (int k = 0; k < network.numChannels * 3; k++) { + cost.addTerm(channel_costs[k], c[k]); } IloObjective objective = cplex.minimize(cost); cplex.add(objective); System.out.println("Objective : "+cost); // Initialize x variable: Variable x contains clique size, clique, channel activation status for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { // Keys are size, values are a list of cliques of that size HashMap cliques_of_size_key = (HashMap) edge_cliques.get(k); if (cliques_of_size_key != null) { for (Object t : cliques_of_size_key.keySet()) { Integer size = (Integer) t; HashSet n_cliques = (HashSet) cliques_of_size_key.get(size); for (Object u : n_cliques) { HashSet clique = (HashSet) u; int idx = size - 1; x[e.id][k][idx] = cplex.intVar(0, 1, "x(" + e.id + ")(" + k + ")(" + idx + ")"); if (idx == clique.size() && e.channels[k] > 0.0) { cplex.addEq(1, x[e.id][k][idx]); } else { cplex.addEq(0, x[e.id][k][idx]); } } } } } } System.out.println("Constraint 5: Enfoce good channel choices."); // Constraint 5: for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { // Sum acros clique sizes IloNumExpr irj = cplex.numExpr(); for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { irj = cplex.sum(x[e.id][k][tc], irj); } - System.out.println(y[e.id][k] + " = " + irj); + // System.out.println(y[e.id][k] + " = " + irj); cplex.addEq(y[e.id][k], irj); - System.out.println(y[e.id][k] + " <= " + c[k]); + // System.out.println(y[e.id][k] + " <= " + c[k]); cplex.addLe(y[e.id][k], c[k]); } } if (options.verbose) { System.out.println("Constraint 6: Only pick one channel"); } // Constraint 6: for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { // Sum acros clique sizes IloNumExpr irj = cplex.numExpr(); for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { irj = cplex.sum(x[e.id][k][tc], irj); } - System.out.println(irj+" <= " + 1); + // System.out.println(irj+" <= " + 1); cplex.addLe(irj, 1); } } if (options.verbose) { System.out.println("Constraint 7: Enforcing good choices"); } // Constraint 7: // Make interim data structure to make this easier HashMap cl = new HashMap(); for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { HashMap cliques_of_size = (HashMap)edge_cliques.get(k); if (cliques_of_size != null) { for (int c1 = 1; c1 < MAX_CLIQUE_SIZE; c1++) { HashSet cliques = (HashSet)cliques_of_size.get(c1); HashSet cls = (HashSet)cl.get(k); if (cls == null) { cl.put(k, new HashSet(cliques)); } else { cls.addAll(cliques); cl.put(k, cls); } } } } } for (int k = 0; k < network.numChannels * 3; k++) { HashSet cliques = (HashSet)cl.get(k); if (cliques != null) { for (Object o : cliques) { HashSet clique = (HashSet)o; IloNumExpr cs2 = cplex.numExpr(); for (Object p : clique) { Edge e = (Edge)p; cs2 = cplex.sum(y[e.id][k], cs2); } IloNumExpr c8 = cplex.diff(clique.size(), cs2); for (Object p : clique) { Edge e = (Edge)p; for (int i = 0; i < clique.size(); i++) { - System.out.println(x[e.id][k][i] + " " + c8); + // System.out.println(x[e.id][k][i] + " " + c8); cplex.addLe(x[e.id][k][i], c8); } } } } } if (options.verbose) { System.out.println("Constraint 8: Total capacity"); } // Constraint 8: Total capacity constraint for (Object zz : network.getEdges()) { Edge e = (Edge) zz; IloNumExpr lhs = cplex.numExpr(); for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { lhs = cplex.sum(cplex.prod(D[e.id][k][tc], x[e.id][k][tc]), lhs); } } - System.out.println(lhs + " >= "+ demand[e.id]); + // System.out.println(lhs + " >= "+ demand[e.id]); cplex.addGe(lhs, demand[e.id]); } // Write the model out to validate cplex.exportModel("JRCS-TVWS.lp"); if (cplex.solve()) { double cplexTotal = cplex.getObjValue(); for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { System.out.println("x("+e.id+")("+k+")("+tc+") = " + cplex.getValue(x[e.id][k][tc])); } } } for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { System.out.println("y("+e.id+")("+k+") = " + cplex.getValue(y[e.id][k])); } } for (int i = 0; i < network.numChannels * 3; i++) { System.out.println("c("+i+") = "+cplex.getValue(c[i])); } System.out.println("Solution status = " + cplex.getStatus()); System.out.println("Solution value = " + cplexTotal); } else { System.out.println("Couldn't solve problem!"); } cplex.end(); } catch (IloException e) { System.err.println("Concert exception '" + e + "' caught."); } // Show graph if (options.display) { drawing = new Draw(network, 1024, 768, "Routing and Channel Selection Application"); drawing.draw(); } System.out.println("Seed, Width, Height, Nodes, Users, Channels"); System.out.println(options.seed + ", " + options.width + ", " + options.height + ", " + options.relays + ", " + options.subscribers + ", " + options.channels); // System.out.println("RCS Bisection Bandwidth:"); // for(int i = 0; i < rcsBisectionBandwidth.length; i++) { // System.out.print(i + " :"); // for(int j = 0; j < rcsBisectionBandwidth[i].length;j++) { // System.out.printf(" %7.2g", rcsBisectionBandwidth[i][j]); // } // System.out.print("\n"); // } } }
false
true
public static void main(String[] args) { NetworkGenerator networkGenerator; Network network; WhitespaceShortCircuitOptions options = new WhitespaceShortCircuitOptions(); CmdLineParser parser = new CmdLineParser(options); Draw drawing = null; ChannelSelection cs = null; double rcsThpt; double[][] rcsBisectionBandwidth; PrimMinimumSpanningTree psp = null; Graph primTree = null; parser.setUsageWidth(80); BasicConfigurator.configure(); logger.setLevel(Level.DEBUG); try { parser.parseArgument(args); } catch (CmdLineException e) { logger.error("Failed to parse command line arguments."); logger.error(e.getMessage()); parser.printUsage(System.err); System.exit(1); } int count = 0; do { networkGenerator = Network.getGenerator(options.relays, options.subscribers, options.width, options.height, options.seed + count, options.channels, options.channelProb); network = networkGenerator.create(); rcsBisectionBandwidth = new double[network.getVertices().size()][network.getVertices().size()]; Transformer<Edge, Double> wtTransformer = new Transformer<Edge, Double>() { public Double transform(Edge e) { if (e.capacity > 0.0) { return e.length; } else { return Double.MAX_VALUE; } } }; Transformer<Edge, Double> pTransformer = new Transformer<Edge, Double>() { public Double transform(Edge e) { return e.bottleNeckWeight(); } }; // Set all edge and vertex types to 0 for (Object o : network.getVertices()) { Vertex v = (Vertex) o; v.type = 0; } for (Object o : network.getEdges()) { Edge e = (Edge) o; e.type = 0; } psp = new PrimMinimumSpanningTree(networkGenerator.networkFactory, pTransformer); primTree = psp.transform(network); count++; } while (network.getVertexCount() != primTree.getVertexCount()); // Handle options that matter if (options.verbose) { System.out.println("Random Seed: " + options.seed); } if (options.verbose) { System.out.println("Prim Tree: "); System.out.print(primTree.toString()); System.out.println(""); } for (Object e : primTree.getEdges()) { // Color the MST ((Edge) e).type = 2; } Collection<Edge> primEdges = primTree.getEdges(); Vector toRemove = new Vector(); for (Object e : network.getEdges()) { if (!primEdges.contains(e)) { toRemove.addElement(e); } } for (Object e : toRemove) { network.removeEdge((Edge) e); } // Renumber nodes int nid = 0; for(Object o : network.getVertices()) { Vertex v = (Vertex)o; v.id = nid; nid += 1; } // Renumber edges int eid = 0; for (Object o : network.getEdges()) { Edge e = (Edge) o; e.setId(eid); eid += 1; } network.computeInterference(); // go over all the nxn nodes and find the throughput using rcs for (Object o : network.getVertices()) { Vertex source = (Vertex) o; for (Object p : network.getVertices()) { Vertex destination = (Vertex) p; if (source.id < destination.id) { DijkstraShortestPath<Vertex, Edge> dspath = new DijkstraShortestPath(primTree); List<Edge> spath = dspath.getPath(source, destination); if (options.verbose) { System.out.println(source + " -> " + destination + " : " + spath); } } } } // Print out the edge list if (options.verbose) { System.out.println(network.getEdgeCount() + " Edges"); for (Object e : network.getEdges()) { System.out.println("\t" + (Edge) e); } } // Print out the conflict graph // for(int i = 0; i < network.getEdgeCount() + 1; i++) { // for(int j = 0; j < network.getEdgeCount() + 1; j++) { // for (int k = 0; k < network.numChannels * 3 + 1; k++) { // System.out.println("("+i+","+j+","+k+") = "+network.interferes[i][j][k]); // } // } // } // Initialize a hash of cliques by channel, the value is a set so we don't get duplicates // indexed by edge, then channel, then a list of cliques HashMap clique_list = enumerate_cliques(network); if (options.verbose) { //Print out all cliques to make sure we're good for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { System.out.println("Cliques involving Edge: " + e.id + " using channel " + k + ":"); // Keys are size, values are a list of cliques of that size HashMap cliques_of_size_key = (HashMap) edge_cliques.get(k); if (cliques_of_size_key != null) { for (Object t : cliques_of_size_key.keySet()) { Integer size = (Integer) t; HashSet clique = (HashSet) cliques_of_size_key.get(size); System.out.print("\t[ Size: " + size + " #: " + clique.size() + "] "); System.out.println(clique); } } } } } // Build ILP try { IloCplex cplex = new IloCplex(); // Variable Definitions for ILP // c IloIntVar[] c = new IloIntVar[network.numChannels * 3]; for (int i = 0; i < network.numChannels * 3; i++) { c[i] = cplex.intVar(0, 1, "c(" + i + ")"); } Double[] demand = new Double[network.getEdgeCount()]; for (Object o: network.getEdges()) { Edge e = (Edge)o; demand[e.id] = 10.0; } // x IloIntVar[][][] x = new IloIntVar[network.getEdgeCount()][network.numChannels * 3][MAX_CLIQUE_SIZE]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { // System.out.println(x.length+","+x[0].length+","+x[0][0].length+ " "+e.id+","+k+","+tc); x[e.id][k][tc] = cplex.intVar(0, 1, "x(" + e.id + ")(" + k + ")(" + tc + ")"); } } } // D Double[][][] D = new Double[network.getEdgeCount()][network.numChannels * 3][MAX_CLIQUE_SIZE]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int size = 1; size < MAX_CLIQUE_SIZE; size++) { if (e.channels[k] >= 0) { D[e.id][k][size] = e.channels[k] / size; } else { D[e.id][k][size] = 0.0d; } } } } // y IloIntVar[][] y = new IloIntVar[network.getEdgeCount()][network.numChannels * 3]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { y[e.id][k] = cplex.intVar(0, network.getEdgeCount(), "y(" + e.id + ")(" + k + ")"); } } // Objective function in Equation 3 - Minimize Overall Channel Costs IloLinearNumExpr cost = cplex.linearNumExpr(); // Initialize Channel Costs: Channel costs are all the same 1.0 for now double[] channel_costs = new double[network.numChannels * 3]; Random randomGenerator = new Random(); for (int k = 0; k < network.numChannels * 3; k++) { channel_costs[k] = randomGenerator.nextFloat(); channel_costs[k] = 1.0; } // Objective: Minimize channel costs // Channel usage array (Number of edges * number of channels per edge) for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < e.channels.length; k++) { if (e.channels[k] > 0.0) { cost.addTerm(channel_costs[k], c[k]); } } } IloObjective objective = cplex.minimize(cost); cplex.add(objective); System.out.println("Objective : "+cost); // Initialize x variable: Variable x contains clique size, clique, channel activation status for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { // Keys are size, values are a list of cliques of that size HashMap cliques_of_size_key = (HashMap) edge_cliques.get(k); if (cliques_of_size_key != null) { for (Object t : cliques_of_size_key.keySet()) { Integer size = (Integer) t; HashSet n_cliques = (HashSet) cliques_of_size_key.get(size); for (Object u : n_cliques) { HashSet clique = (HashSet) u; int idx = size - 1; x[e.id][k][idx] = cplex.intVar(0, 1, "x(" + e.id + ")(" + k + ")(" + idx + ")"); if (idx == clique.size() && e.channels[k] > 0.0) { cplex.addEq(1, x[e.id][k][idx]); } else { cplex.addEq(0, x[e.id][k][idx]); } } } } } } System.out.println("Constraint 5: Enfoce good channel choices."); // Constraint 5: for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { // Sum acros clique sizes IloNumExpr irj = cplex.numExpr(); for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { irj = cplex.sum(x[e.id][k][tc], irj); } System.out.println(y[e.id][k] + " = " + irj); cplex.addEq(y[e.id][k], irj); System.out.println(y[e.id][k] + " <= " + c[k]); cplex.addLe(y[e.id][k], c[k]); } } if (options.verbose) { System.out.println("Constraint 6: Only pick one channel"); } // Constraint 6: for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { // Sum acros clique sizes IloNumExpr irj = cplex.numExpr(); for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { irj = cplex.sum(x[e.id][k][tc], irj); } System.out.println(irj+" <= " + 1); cplex.addLe(irj, 1); } } if (options.verbose) { System.out.println("Constraint 7: Enforcing good choices"); } // Constraint 7: // Make interim data structure to make this easier HashMap cl = new HashMap(); for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { HashMap cliques_of_size = (HashMap)edge_cliques.get(k); if (cliques_of_size != null) { for (int c1 = 1; c1 < MAX_CLIQUE_SIZE; c1++) { HashSet cliques = (HashSet)cliques_of_size.get(c1); HashSet cls = (HashSet)cl.get(k); if (cls == null) { cl.put(k, new HashSet(cliques)); } else { cls.addAll(cliques); cl.put(k, cls); } } } } } for (int k = 0; k < network.numChannels * 3; k++) { HashSet cliques = (HashSet)cl.get(k); if (cliques != null) { for (Object o : cliques) { HashSet clique = (HashSet)o; IloNumExpr cs2 = cplex.numExpr(); for (Object p : clique) { Edge e = (Edge)p; cs2 = cplex.sum(y[e.id][k], cs2); } IloNumExpr c8 = cplex.diff(clique.size(), cs2); for (Object p : clique) { Edge e = (Edge)p; for (int i = 0; i < clique.size(); i++) { System.out.println(x[e.id][k][i] + " " + c8); cplex.addLe(x[e.id][k][i], c8); } } } } } if (options.verbose) { System.out.println("Constraint 8: Total capacity"); } // Constraint 8: Total capacity constraint for (Object zz : network.getEdges()) { Edge e = (Edge) zz; IloNumExpr lhs = cplex.numExpr(); for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { lhs = cplex.sum(cplex.prod(D[e.id][k][tc], x[e.id][k][tc]), lhs); } } System.out.println(lhs + " >= "+ demand[e.id]); cplex.addGe(lhs, demand[e.id]); } // Write the model out to validate cplex.exportModel("JRCS-TVWS.lp"); if (cplex.solve()) { double cplexTotal = cplex.getObjValue(); for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { System.out.println("x("+e.id+")("+k+")("+tc+") = " + cplex.getValue(x[e.id][k][tc])); } } } for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { System.out.println("y("+e.id+")("+k+") = " + cplex.getValue(y[e.id][k])); } } for (int i = 0; i < network.numChannels * 3; i++) { System.out.println("c("+i+") = "+cplex.getValue(c[i])); } System.out.println("Solution status = " + cplex.getStatus()); System.out.println("Solution value = " + cplexTotal); } else { System.out.println("Couldn't solve problem!"); } cplex.end(); } catch (IloException e) { System.err.println("Concert exception '" + e + "' caught."); } // Show graph if (options.display) { drawing = new Draw(network, 1024, 768, "Routing and Channel Selection Application"); drawing.draw(); } System.out.println("Seed, Width, Height, Nodes, Users, Channels"); System.out.println(options.seed + ", " + options.width + ", " + options.height + ", " + options.relays + ", " + options.subscribers + ", " + options.channels); // System.out.println("RCS Bisection Bandwidth:"); // for(int i = 0; i < rcsBisectionBandwidth.length; i++) { // System.out.print(i + " :"); // for(int j = 0; j < rcsBisectionBandwidth[i].length;j++) { // System.out.printf(" %7.2g", rcsBisectionBandwidth[i][j]); // } // System.out.print("\n"); // } }
public static void main(String[] args) { NetworkGenerator networkGenerator; Network network; WhitespaceShortCircuitOptions options = new WhitespaceShortCircuitOptions(); CmdLineParser parser = new CmdLineParser(options); Draw drawing = null; ChannelSelection cs = null; double rcsThpt; double[][] rcsBisectionBandwidth; PrimMinimumSpanningTree psp = null; Graph primTree = null; parser.setUsageWidth(80); BasicConfigurator.configure(); logger.setLevel(Level.DEBUG); try { parser.parseArgument(args); } catch (CmdLineException e) { logger.error("Failed to parse command line arguments."); logger.error(e.getMessage()); parser.printUsage(System.err); System.exit(1); } int count = 0; do { networkGenerator = Network.getGenerator(options.relays, options.subscribers, options.width, options.height, options.seed + count, options.channels, options.channelProb); network = networkGenerator.create(); rcsBisectionBandwidth = new double[network.getVertices().size()][network.getVertices().size()]; Transformer<Edge, Double> wtTransformer = new Transformer<Edge, Double>() { public Double transform(Edge e) { if (e.capacity > 0.0) { return e.length; } else { return Double.MAX_VALUE; } } }; Transformer<Edge, Double> pTransformer = new Transformer<Edge, Double>() { public Double transform(Edge e) { return e.bottleNeckWeight(); } }; // Set all edge and vertex types to 0 for (Object o : network.getVertices()) { Vertex v = (Vertex) o; v.type = 0; } for (Object o : network.getEdges()) { Edge e = (Edge) o; e.type = 0; } psp = new PrimMinimumSpanningTree(networkGenerator.networkFactory, pTransformer); primTree = psp.transform(network); count++; } while (network.getVertexCount() != primTree.getVertexCount()); // Handle options that matter if (options.verbose) { System.out.println("Random Seed: " + options.seed); } if (options.verbose) { System.out.println("Prim Tree: "); System.out.print(primTree.toString()); System.out.println(""); } for (Object e : primTree.getEdges()) { // Color the MST ((Edge) e).type = 2; } Collection<Edge> primEdges = primTree.getEdges(); Vector toRemove = new Vector(); for (Object e : network.getEdges()) { if (!primEdges.contains(e)) { toRemove.addElement(e); } } for (Object e : toRemove) { network.removeEdge((Edge) e); } // Renumber nodes int nid = 0; for(Object o : network.getVertices()) { Vertex v = (Vertex)o; v.id = nid; nid += 1; } // Renumber edges int eid = 0; for (Object o : network.getEdges()) { Edge e = (Edge) o; e.setId(eid); eid += 1; } network.computeInterference(); // go over all the nxn nodes and find the throughput using rcs for (Object o : network.getVertices()) { Vertex source = (Vertex) o; for (Object p : network.getVertices()) { Vertex destination = (Vertex) p; if (source.id < destination.id) { DijkstraShortestPath<Vertex, Edge> dspath = new DijkstraShortestPath(primTree); List<Edge> spath = dspath.getPath(source, destination); if (options.verbose) { System.out.println(source + " -> " + destination + " : " + spath); } } } } // Print out the edge list if (options.verbose) { System.out.println(network.getEdgeCount() + " Edges"); for (Object e : network.getEdges()) { System.out.println("\t" + (Edge) e); } } // Print out the conflict graph // for(int i = 0; i < network.getEdgeCount() + 1; i++) { // for(int j = 0; j < network.getEdgeCount() + 1; j++) { // for (int k = 0; k < network.numChannels * 3 + 1; k++) { // System.out.println("("+i+","+j+","+k+") = "+network.interferes[i][j][k]); // } // } // } // Initialize a hash of cliques by channel, the value is a set so we don't get duplicates // indexed by edge, then channel, then a list of cliques HashMap clique_list = enumerate_cliques(network); if (options.verbose) { //Print out all cliques to make sure we're good for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { System.out.println("Cliques involving Edge: " + e.id + " using channel " + k + ":"); // Keys are size, values are a list of cliques of that size HashMap cliques_of_size_key = (HashMap) edge_cliques.get(k); if (cliques_of_size_key != null) { for (Object t : cliques_of_size_key.keySet()) { Integer size = (Integer) t; HashSet clique = (HashSet) cliques_of_size_key.get(size); System.out.print("\t[ Size: " + size + " #: " + clique.size() + "] "); System.out.println(clique); } } } } } // Build ILP try { IloCplex cplex = new IloCplex(); // Variable Definitions for ILP // c IloIntVar[] c = new IloIntVar[network.numChannels * 3]; for (int i = 0; i < network.numChannels * 3; i++) { c[i] = cplex.intVar(0, 1, "c(" + i + ")"); } Double[] demand = new Double[network.getEdgeCount()]; for (Object o: network.getEdges()) { Edge e = (Edge)o; demand[e.id] = 2e7; } // x IloIntVar[][][] x = new IloIntVar[network.getEdgeCount()][network.numChannels * 3][MAX_CLIQUE_SIZE]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { // System.out.println(x.length+","+x[0].length+","+x[0][0].length+ " "+e.id+","+k+","+tc); x[e.id][k][tc] = cplex.intVar(0, 1, "x(" + e.id + ")(" + k + ")(" + tc + ")"); } } } // D Double[][][] D = new Double[network.getEdgeCount()][network.numChannels * 3][MAX_CLIQUE_SIZE]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int size = 1; size < MAX_CLIQUE_SIZE; size++) { if (e.channels[k] >= 0) { D[e.id][k][size] = e.channels[k] / size; } else { D[e.id][k][size] = 0.0d; } } } } // y IloIntVar[][] y = new IloIntVar[network.getEdgeCount()][network.numChannels * 3]; for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { y[e.id][k] = cplex.intVar(0, network.getEdgeCount(), "y(" + e.id + ")(" + k + ")"); } } // Objective function in Equation 3 - Minimize Overall Channel Costs IloLinearNumExpr cost = cplex.linearNumExpr(); // Initialize Channel Costs: Channel costs are all the same 1.0 for now double[] channel_costs = new double[network.numChannels * 3]; Random randomGenerator = new Random(); for (int k = 0; k < network.numChannels * 3; k++) { if (k % 3 == 0) { channel_costs[k] = 1.0; } if (k % 3 == 1) { channel_costs[k] = 1.0; } if (k % 3 == 2) { channel_costs[k] = 1.0; } } // Objective: Minimize channel costs // Channel usage array (Number of edges * number of channels per edge) for (int k = 0; k < network.numChannels * 3; k++) { cost.addTerm(channel_costs[k], c[k]); } IloObjective objective = cplex.minimize(cost); cplex.add(objective); System.out.println("Objective : "+cost); // Initialize x variable: Variable x contains clique size, clique, channel activation status for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { // Keys are size, values are a list of cliques of that size HashMap cliques_of_size_key = (HashMap) edge_cliques.get(k); if (cliques_of_size_key != null) { for (Object t : cliques_of_size_key.keySet()) { Integer size = (Integer) t; HashSet n_cliques = (HashSet) cliques_of_size_key.get(size); for (Object u : n_cliques) { HashSet clique = (HashSet) u; int idx = size - 1; x[e.id][k][idx] = cplex.intVar(0, 1, "x(" + e.id + ")(" + k + ")(" + idx + ")"); if (idx == clique.size() && e.channels[k] > 0.0) { cplex.addEq(1, x[e.id][k][idx]); } else { cplex.addEq(0, x[e.id][k][idx]); } } } } } } System.out.println("Constraint 5: Enfoce good channel choices."); // Constraint 5: for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { // Sum acros clique sizes IloNumExpr irj = cplex.numExpr(); for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { irj = cplex.sum(x[e.id][k][tc], irj); } // System.out.println(y[e.id][k] + " = " + irj); cplex.addEq(y[e.id][k], irj); // System.out.println(y[e.id][k] + " <= " + c[k]); cplex.addLe(y[e.id][k], c[k]); } } if (options.verbose) { System.out.println("Constraint 6: Only pick one channel"); } // Constraint 6: for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { // Sum acros clique sizes IloNumExpr irj = cplex.numExpr(); for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { irj = cplex.sum(x[e.id][k][tc], irj); } // System.out.println(irj+" <= " + 1); cplex.addLe(irj, 1); } } if (options.verbose) { System.out.println("Constraint 7: Enforcing good choices"); } // Constraint 7: // Make interim data structure to make this easier HashMap cl = new HashMap(); for (Object o : network.getEdges()) { Edge e = (Edge) o; HashMap edge_cliques = (HashMap) clique_list.get(e.id); for (int k = 0; k < network.numChannels * 3; k++) { HashMap cliques_of_size = (HashMap)edge_cliques.get(k); if (cliques_of_size != null) { for (int c1 = 1; c1 < MAX_CLIQUE_SIZE; c1++) { HashSet cliques = (HashSet)cliques_of_size.get(c1); HashSet cls = (HashSet)cl.get(k); if (cls == null) { cl.put(k, new HashSet(cliques)); } else { cls.addAll(cliques); cl.put(k, cls); } } } } } for (int k = 0; k < network.numChannels * 3; k++) { HashSet cliques = (HashSet)cl.get(k); if (cliques != null) { for (Object o : cliques) { HashSet clique = (HashSet)o; IloNumExpr cs2 = cplex.numExpr(); for (Object p : clique) { Edge e = (Edge)p; cs2 = cplex.sum(y[e.id][k], cs2); } IloNumExpr c8 = cplex.diff(clique.size(), cs2); for (Object p : clique) { Edge e = (Edge)p; for (int i = 0; i < clique.size(); i++) { // System.out.println(x[e.id][k][i] + " " + c8); cplex.addLe(x[e.id][k][i], c8); } } } } } if (options.verbose) { System.out.println("Constraint 8: Total capacity"); } // Constraint 8: Total capacity constraint for (Object zz : network.getEdges()) { Edge e = (Edge) zz; IloNumExpr lhs = cplex.numExpr(); for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { lhs = cplex.sum(cplex.prod(D[e.id][k][tc], x[e.id][k][tc]), lhs); } } // System.out.println(lhs + " >= "+ demand[e.id]); cplex.addGe(lhs, demand[e.id]); } // Write the model out to validate cplex.exportModel("JRCS-TVWS.lp"); if (cplex.solve()) { double cplexTotal = cplex.getObjValue(); for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { for (int tc = 1; tc < MAX_CLIQUE_SIZE; tc++) { System.out.println("x("+e.id+")("+k+")("+tc+") = " + cplex.getValue(x[e.id][k][tc])); } } } for (Object o : network.getEdges()) { Edge e = (Edge) o; for (int k = 0; k < network.numChannels * 3; k++) { System.out.println("y("+e.id+")("+k+") = " + cplex.getValue(y[e.id][k])); } } for (int i = 0; i < network.numChannels * 3; i++) { System.out.println("c("+i+") = "+cplex.getValue(c[i])); } System.out.println("Solution status = " + cplex.getStatus()); System.out.println("Solution value = " + cplexTotal); } else { System.out.println("Couldn't solve problem!"); } cplex.end(); } catch (IloException e) { System.err.println("Concert exception '" + e + "' caught."); } // Show graph if (options.display) { drawing = new Draw(network, 1024, 768, "Routing and Channel Selection Application"); drawing.draw(); } System.out.println("Seed, Width, Height, Nodes, Users, Channels"); System.out.println(options.seed + ", " + options.width + ", " + options.height + ", " + options.relays + ", " + options.subscribers + ", " + options.channels); // System.out.println("RCS Bisection Bandwidth:"); // for(int i = 0; i < rcsBisectionBandwidth.length; i++) { // System.out.print(i + " :"); // for(int j = 0; j < rcsBisectionBandwidth[i].length;j++) { // System.out.printf(" %7.2g", rcsBisectionBandwidth[i][j]); // } // System.out.print("\n"); // } }
diff --git a/src/main/java/net/LoadingChunks/OakLog/Util/SQLWrapper.java b/src/main/java/net/LoadingChunks/OakLog/Util/SQLWrapper.java index 70d9dc3..1c8799e 100644 --- a/src/main/java/net/LoadingChunks/OakLog/Util/SQLWrapper.java +++ b/src/main/java/net/LoadingChunks/OakLog/Util/SQLWrapper.java @@ -1,111 +1,113 @@ package net.LoadingChunks.OakLog.Util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.json.simple.JSONObject; import net.LoadingChunks.OakLog.OakLog; import net.LoadingChunks.OakLog.LogHandler.LogEntry; public class SQLWrapper { static private OakLog plugin; static private Connection con; static private Statement stmt; static private boolean success; static private String user; static private String password; static private String host; static private String db; static public OakLog getPlugin() { return plugin; } static public void setConfig(OakLog plugin, String user, String password, String host, String db) { SQLWrapper.plugin = plugin; SQLWrapper.user = user; SQLWrapper.password = password; SQLWrapper.host = host; SQLWrapper.db = db; } static public void connect() { try { Class.forName("com.mysql.jdbc.Driver"); String uri = "jdbc:mysql://" + SQLWrapper.host + ":3306/" + SQLWrapper.db; plugin.getLogger().severe("Connect to DB: " + uri); SQLWrapper.con = DriverManager.getConnection(uri, SQLWrapper.user, SQLWrapper.password); } catch(SQLException e) { e.printStackTrace(); SQLWrapper.success = false; } catch (ClassNotFoundException e) { e.printStackTrace(); SQLWrapper.success = false; } } static public void commitLog(LogEntry entry) { if(con == null) { plugin.getLogger().severe("Could not connect to logger database!"); return; } try { PreparedStatement stat = con.prepareStatement("INSERT INTO logs (`server`,`type`,`level`,`message`,`plugin`,`timestamp`) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); stat.setString(1, plugin.getServerConfig().getString("server.name")); stat.setString(2, entry.type); stat.setString(3, entry.level.getName()); stat.setString(4, entry.message); if(entry.plugin != null) stat.setString(5, entry.plugin.getName()); else stat.setString(5, null); stat.setDouble(6, entry.milliEpoch / 1000); stat.execute(); ResultSet keys = stat.getGeneratedKeys(); + keys.first(); int logid = keys.getInt(1); for(Player p : entry.associations) { stat = con.prepareStatement("SELECT * FROM `log_users` WHERE `name` = ? LIMIT 1"); stat.setString(1, p.getName()); stat.execute(); ResultSet player = stat.getResultSet(); player.last(); int rescount = player.getRow(); int uid = 0; if(rescount > 0) { uid = player.getInt("user_id"); } else { stat = con.prepareStatement("INSERT INTO `log_users` (`name`) VALUES (?)", Statement.RETURN_GENERATED_KEYS); stat.setString(1, p.getName()); stat.execute(); ResultSet uset = stat.getGeneratedKeys(); + uset.first(); uid = uset.getInt(1); } stat = con.prepareStatement("INSERT IGNORE INTO `log_associations` (`log_id`,`user_id`) VALUES (?,?)"); stat.setInt(1, logid); stat.setInt(2, uid); stat.execute(); } } catch(SQLException e) { e.printStackTrace(); } } }
false
true
static public void commitLog(LogEntry entry) { if(con == null) { plugin.getLogger().severe("Could not connect to logger database!"); return; } try { PreparedStatement stat = con.prepareStatement("INSERT INTO logs (`server`,`type`,`level`,`message`,`plugin`,`timestamp`) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); stat.setString(1, plugin.getServerConfig().getString("server.name")); stat.setString(2, entry.type); stat.setString(3, entry.level.getName()); stat.setString(4, entry.message); if(entry.plugin != null) stat.setString(5, entry.plugin.getName()); else stat.setString(5, null); stat.setDouble(6, entry.milliEpoch / 1000); stat.execute(); ResultSet keys = stat.getGeneratedKeys(); int logid = keys.getInt(1); for(Player p : entry.associations) { stat = con.prepareStatement("SELECT * FROM `log_users` WHERE `name` = ? LIMIT 1"); stat.setString(1, p.getName()); stat.execute(); ResultSet player = stat.getResultSet(); player.last(); int rescount = player.getRow(); int uid = 0; if(rescount > 0) { uid = player.getInt("user_id"); } else { stat = con.prepareStatement("INSERT INTO `log_users` (`name`) VALUES (?)", Statement.RETURN_GENERATED_KEYS); stat.setString(1, p.getName()); stat.execute(); ResultSet uset = stat.getGeneratedKeys(); uid = uset.getInt(1); } stat = con.prepareStatement("INSERT IGNORE INTO `log_associations` (`log_id`,`user_id`) VALUES (?,?)"); stat.setInt(1, logid); stat.setInt(2, uid); stat.execute(); } } catch(SQLException e) { e.printStackTrace(); } }
static public void commitLog(LogEntry entry) { if(con == null) { plugin.getLogger().severe("Could not connect to logger database!"); return; } try { PreparedStatement stat = con.prepareStatement("INSERT INTO logs (`server`,`type`,`level`,`message`,`plugin`,`timestamp`) VALUES (?,?,?,?,?,?)", Statement.RETURN_GENERATED_KEYS); stat.setString(1, plugin.getServerConfig().getString("server.name")); stat.setString(2, entry.type); stat.setString(3, entry.level.getName()); stat.setString(4, entry.message); if(entry.plugin != null) stat.setString(5, entry.plugin.getName()); else stat.setString(5, null); stat.setDouble(6, entry.milliEpoch / 1000); stat.execute(); ResultSet keys = stat.getGeneratedKeys(); keys.first(); int logid = keys.getInt(1); for(Player p : entry.associations) { stat = con.prepareStatement("SELECT * FROM `log_users` WHERE `name` = ? LIMIT 1"); stat.setString(1, p.getName()); stat.execute(); ResultSet player = stat.getResultSet(); player.last(); int rescount = player.getRow(); int uid = 0; if(rescount > 0) { uid = player.getInt("user_id"); } else { stat = con.prepareStatement("INSERT INTO `log_users` (`name`) VALUES (?)", Statement.RETURN_GENERATED_KEYS); stat.setString(1, p.getName()); stat.execute(); ResultSet uset = stat.getGeneratedKeys(); uset.first(); uid = uset.getInt(1); } stat = con.prepareStatement("INSERT IGNORE INTO `log_associations` (`log_id`,`user_id`) VALUES (?,?)"); stat.setInt(1, logid); stat.setInt(2, uid); stat.execute(); } } catch(SQLException e) { e.printStackTrace(); } }
diff --git a/src/net/sf/jsignpdf/SignerLogic.java b/src/net/sf/jsignpdf/SignerLogic.java index cbc8eaa..41fb73f 100644 --- a/src/net/sf/jsignpdf/SignerLogic.java +++ b/src/net/sf/jsignpdf/SignerLogic.java @@ -1,306 +1,315 @@ package net.sf.jsignpdf; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.Proxy; import java.security.MessageDigest; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.List; import net.sf.jsignpdf.crl.CRLInfo; import net.sf.jsignpdf.types.HashAlgorithm; import net.sf.jsignpdf.utils.FontUtils; import net.sf.jsignpdf.utils.KeyStoreUtils; import net.sf.jsignpdf.utils.ResourceProvider; import net.sf.jsignpdf.utils.StringUtils; import com.lowagie.text.Font; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.AcroFields; import com.lowagie.text.pdf.OcspClientBouncyCastle; import com.lowagie.text.pdf.PdfDate; import com.lowagie.text.pdf.PdfDictionary; import com.lowagie.text.pdf.PdfName; import com.lowagie.text.pdf.PdfPKCS7; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfSignature; import com.lowagie.text.pdf.PdfSignatureAppearance; import com.lowagie.text.pdf.PdfStamper; import com.lowagie.text.pdf.PdfString; import com.lowagie.text.pdf.PdfWriter; import com.lowagie.text.pdf.TSAClientBouncyCastle; /** * Main logic of signer application. It uses iText to create signature in PDF. * * @author Josef Cacek */ public class SignerLogic implements Runnable { protected final static ResourceProvider res = ResourceProvider.getInstance(); private BasicSignerOptions options; /** * Constructor with all necessary parameters. * * @param anOptions * options of signer */ public SignerLogic(final BasicSignerOptions anOptions) { options = anOptions; } /* * (non-Javadoc) * * @see java.lang.Runnable#run() */ @SuppressWarnings("unchecked") public void run() { if (options == null) { throw new NullPointerException("Options has to be filled."); } final String outFile = options.getOutFileX(); if (!validateInOutFiles(options.getInFile(), outFile)) { options.log("console.skippingSigning"); return; } Exception tmpResult = null; + FileOutputStream fout = null; try { final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options); final PrivateKey key = pkInfo.getKey(); final Certificate[] chain = pkInfo.getChain(); options.log("console.createPdfReader", options.getInFile()); PdfReader reader; try { // try to read without password reader = new PdfReader(options.getInFile()); } catch (Exception e) { try { reader = new PdfReader(options.getInFile(), new byte[0]); } catch (Exception e2) { reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStr().getBytes()); } } options.log("console.createOutPdf", outFile); - final FileOutputStream fout = new FileOutputStream(outFile); + fout = new FileOutputStream(outFile); final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX(); options.log("console.createSignature"); char tmpPdfVersion = '\0'; // default version - the same as input if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) { tmpPdfVersion = hashAlgorithm.getPdfVersion(); options.log("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) }); } final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX()); if (!options.isAppendX()) { // we are not in append mode, let's remove existing signatures // (otherwise we're getting to troubles) final AcroFields acroFields = stp.getAcroFields(); final List<String> sigNames = acroFields.getSignatureNames(); for (String sigName : sigNames) { acroFields.removeField(sigName); } } if (options.isEncryptedX()) { options.log("console.setEncryption"); final int tmpRight = options.getRightPrinting().getRight() | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0) | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0) | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0) | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0) | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0) | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0); stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStr(), tmpRight); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); if (!StringUtils.isEmpty(options.getReason())) { options.log("console.setReason", options.getReason()); sap.setReason(options.getReason()); } if (!StringUtils.isEmpty(options.getLocation())) { options.log("console.setLocation", options.getLocation()); sap.setLocation(options.getLocation()); } if (!StringUtils.isEmpty(options.getContact())) { options.log("console.setContact", options.getContact()); sap.setContact(options.getContact()); } options.log("console.setCertificationLevel"); sap.setCertificationLevel(options.getCertLevelX().getLevel()); if (options.isVisible()) { // visible signature is enabled options.log("console.configureVisible"); options.log("console.setAcro6Layers"); sap.setAcro6Layers(true); final String tmpImgPath = options.getImgPath(); if (tmpImgPath != null) { options.log("console.createImage", tmpImgPath); final Image img = Image.getInstance(tmpImgPath); options.log("console.setSignatureGraphic"); sap.setSignatureGraphic(img); } final String tmpBgImgPath = options.getBgImgPath(); if (tmpBgImgPath != null) { options.log("console.createImage", tmpBgImgPath); final Image img = Image.getInstance(tmpBgImgPath); options.log("console.setImage"); sap.setImage(img); } options.log("console.setImageScale"); sap.setImageScale(options.getBgImgScale()); options.log("console.setL2Text"); if (options.getL2Text() != null) { sap.setLayer2Text(options.getL2Text()); } else { final StringBuilder buf = new StringBuilder(); buf.append(res.get("default.l2text.signedBy")).append(" "); buf.append(PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN")).append('\n'); final SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append(res.get("default.l2text.date")).append(" ").append( sd.format(sap.getSignDate().getTime())); if (StringUtils.hasLength(options.getReason())) buf.append('\n').append(res.get("default.l2text.reason")).append(" ").append( options.getReason()); if (StringUtils.hasLength(options.getLocation())) buf.append('\n').append(res.get("default.l2text.location")).append(" ").append( options.getLocation()); sap.setLayer2Text(buf.toString()); ; } if (FontUtils.getL2BaseFont() != null) { sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize())); } options.log("console.setL4Text"); sap.setLayer4Text(options.getL4Text()); options.log("console.setRender"); sap.setRender(options.getRenderMode().getRender()); options.log("console.setVisibleSignature"); sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options .getPositionURX(), options.getPositionURY()), options.getPage(), null); } options.log("console.processing"); final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); final Proxy tmpProxy = options.createProxy(); final CRLInfo crlInfo = new CRLInfo(options, chain); // CRLs are stored twice in PDF c.f. // PdfPKCS7.getAuthenticatedAttributeBytes final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount()); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName()); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (options.isOcspEnabledX() && chain.length >= 2) { options.log("console.getOCSPURL"); String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (url != null && url.length() > 0) { options.log("console.readingOCSP"); final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url); ocspClient.setProxy(tmpProxy); ocsp = ocspClient.getEncoded(); } } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClientBouncyCastle tsc = null; if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) { options.log("console.creatingTsaClient"); tsc = new TSAClientBouncyCastle(options.getTsaUrl(), StringUtils.emptyNull(options.getTsaUser()), StringUtils.emptyNull(options.getTsaPasswd())); tsc.setProxy(tmpProxy); } byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) { System.err.println("SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length); throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); options.log("console.closeStream"); sap.close(dic2); fout.close(); } catch (Exception e) { options.log("console.exception"); e.printStackTrace(options.getPrintWriter()); tmpResult = e; } catch (OutOfMemoryError e) { e.printStackTrace(options.getPrintWriter()); options.log("console.memoryError"); + } finally { + if (fout != null) { + try { + fout.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } options.log("console.finished." + (tmpResult == null ? "ok" : "error")); options.fireSignerFinishedEvent(tmpResult); } /** * Validates if input and output files are valid for signing. * * @param inFile * input file * @param outFile * output file * @return true if valid, false otherwise */ private boolean validateInOutFiles(final String inFile, final String outFile) { options.log("console.validatingFiles"); if (StringUtils.isEmpty(inFile) || StringUtils.isEmpty(outFile)) { options.log("console.fileNotFilled.error"); return false; } final File tmpInFile = new File(inFile); final File tmpOutFile = new File(outFile); if (!(tmpInFile.exists() && tmpInFile.isFile() && tmpInFile.canRead())) { options.log("console.inFileNotFound.error"); return false; } if (tmpInFile.getAbsolutePath().equals(tmpOutFile.getAbsolutePath())) { options.log("console.filesAreEqual.error"); return false; } return true; } }
false
true
public void run() { if (options == null) { throw new NullPointerException("Options has to be filled."); } final String outFile = options.getOutFileX(); if (!validateInOutFiles(options.getInFile(), outFile)) { options.log("console.skippingSigning"); return; } Exception tmpResult = null; try { final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options); final PrivateKey key = pkInfo.getKey(); final Certificate[] chain = pkInfo.getChain(); options.log("console.createPdfReader", options.getInFile()); PdfReader reader; try { // try to read without password reader = new PdfReader(options.getInFile()); } catch (Exception e) { try { reader = new PdfReader(options.getInFile(), new byte[0]); } catch (Exception e2) { reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStr().getBytes()); } } options.log("console.createOutPdf", outFile); final FileOutputStream fout = new FileOutputStream(outFile); final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX(); options.log("console.createSignature"); char tmpPdfVersion = '\0'; // default version - the same as input if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) { tmpPdfVersion = hashAlgorithm.getPdfVersion(); options.log("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) }); } final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX()); if (!options.isAppendX()) { // we are not in append mode, let's remove existing signatures // (otherwise we're getting to troubles) final AcroFields acroFields = stp.getAcroFields(); final List<String> sigNames = acroFields.getSignatureNames(); for (String sigName : sigNames) { acroFields.removeField(sigName); } } if (options.isEncryptedX()) { options.log("console.setEncryption"); final int tmpRight = options.getRightPrinting().getRight() | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0) | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0) | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0) | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0) | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0) | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0); stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStr(), tmpRight); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); if (!StringUtils.isEmpty(options.getReason())) { options.log("console.setReason", options.getReason()); sap.setReason(options.getReason()); } if (!StringUtils.isEmpty(options.getLocation())) { options.log("console.setLocation", options.getLocation()); sap.setLocation(options.getLocation()); } if (!StringUtils.isEmpty(options.getContact())) { options.log("console.setContact", options.getContact()); sap.setContact(options.getContact()); } options.log("console.setCertificationLevel"); sap.setCertificationLevel(options.getCertLevelX().getLevel()); if (options.isVisible()) { // visible signature is enabled options.log("console.configureVisible"); options.log("console.setAcro6Layers"); sap.setAcro6Layers(true); final String tmpImgPath = options.getImgPath(); if (tmpImgPath != null) { options.log("console.createImage", tmpImgPath); final Image img = Image.getInstance(tmpImgPath); options.log("console.setSignatureGraphic"); sap.setSignatureGraphic(img); } final String tmpBgImgPath = options.getBgImgPath(); if (tmpBgImgPath != null) { options.log("console.createImage", tmpBgImgPath); final Image img = Image.getInstance(tmpBgImgPath); options.log("console.setImage"); sap.setImage(img); } options.log("console.setImageScale"); sap.setImageScale(options.getBgImgScale()); options.log("console.setL2Text"); if (options.getL2Text() != null) { sap.setLayer2Text(options.getL2Text()); } else { final StringBuilder buf = new StringBuilder(); buf.append(res.get("default.l2text.signedBy")).append(" "); buf.append(PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN")).append('\n'); final SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append(res.get("default.l2text.date")).append(" ").append( sd.format(sap.getSignDate().getTime())); if (StringUtils.hasLength(options.getReason())) buf.append('\n').append(res.get("default.l2text.reason")).append(" ").append( options.getReason()); if (StringUtils.hasLength(options.getLocation())) buf.append('\n').append(res.get("default.l2text.location")).append(" ").append( options.getLocation()); sap.setLayer2Text(buf.toString()); ; } if (FontUtils.getL2BaseFont() != null) { sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize())); } options.log("console.setL4Text"); sap.setLayer4Text(options.getL4Text()); options.log("console.setRender"); sap.setRender(options.getRenderMode().getRender()); options.log("console.setVisibleSignature"); sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options .getPositionURX(), options.getPositionURY()), options.getPage(), null); } options.log("console.processing"); final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); final Proxy tmpProxy = options.createProxy(); final CRLInfo crlInfo = new CRLInfo(options, chain); // CRLs are stored twice in PDF c.f. // PdfPKCS7.getAuthenticatedAttributeBytes final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount()); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName()); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (options.isOcspEnabledX() && chain.length >= 2) { options.log("console.getOCSPURL"); String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (url != null && url.length() > 0) { options.log("console.readingOCSP"); final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url); ocspClient.setProxy(tmpProxy); ocsp = ocspClient.getEncoded(); } } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClientBouncyCastle tsc = null; if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) { options.log("console.creatingTsaClient"); tsc = new TSAClientBouncyCastle(options.getTsaUrl(), StringUtils.emptyNull(options.getTsaUser()), StringUtils.emptyNull(options.getTsaPasswd())); tsc.setProxy(tmpProxy); } byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) { System.err.println("SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length); throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); options.log("console.closeStream"); sap.close(dic2); fout.close(); } catch (Exception e) { options.log("console.exception"); e.printStackTrace(options.getPrintWriter()); tmpResult = e; } catch (OutOfMemoryError e) { e.printStackTrace(options.getPrintWriter()); options.log("console.memoryError"); } options.log("console.finished." + (tmpResult == null ? "ok" : "error")); options.fireSignerFinishedEvent(tmpResult); }
public void run() { if (options == null) { throw new NullPointerException("Options has to be filled."); } final String outFile = options.getOutFileX(); if (!validateInOutFiles(options.getInFile(), outFile)) { options.log("console.skippingSigning"); return; } Exception tmpResult = null; FileOutputStream fout = null; try { final PrivateKeyInfo pkInfo = KeyStoreUtils.getPkInfo(options); final PrivateKey key = pkInfo.getKey(); final Certificate[] chain = pkInfo.getChain(); options.log("console.createPdfReader", options.getInFile()); PdfReader reader; try { // try to read without password reader = new PdfReader(options.getInFile()); } catch (Exception e) { try { reader = new PdfReader(options.getInFile(), new byte[0]); } catch (Exception e2) { reader = new PdfReader(options.getInFile(), options.getPdfOwnerPwdStr().getBytes()); } } options.log("console.createOutPdf", outFile); fout = new FileOutputStream(outFile); final HashAlgorithm hashAlgorithm = options.getHashAlgorithmX(); options.log("console.createSignature"); char tmpPdfVersion = '\0'; // default version - the same as input if (reader.getPdfVersion() < hashAlgorithm.getPdfVersion()) { tmpPdfVersion = hashAlgorithm.getPdfVersion(); options.log("console.updateVersion", new String[] { String.valueOf(reader.getPdfVersion()), String.valueOf(tmpPdfVersion) }); } final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, options.isAppendX()); if (!options.isAppendX()) { // we are not in append mode, let's remove existing signatures // (otherwise we're getting to troubles) final AcroFields acroFields = stp.getAcroFields(); final List<String> sigNames = acroFields.getSignatureNames(); for (String sigName : sigNames) { acroFields.removeField(sigName); } } if (options.isEncryptedX()) { options.log("console.setEncryption"); final int tmpRight = options.getRightPrinting().getRight() | (options.isRightCopy() ? PdfWriter.ALLOW_COPY : 0) | (options.isRightAssembly() ? PdfWriter.ALLOW_ASSEMBLY : 0) | (options.isRightFillIn() ? PdfWriter.ALLOW_FILL_IN : 0) | (options.isRightScreanReaders() ? PdfWriter.ALLOW_SCREENREADERS : 0) | (options.isRightModifyAnnotations() ? PdfWriter.ALLOW_MODIFY_ANNOTATIONS : 0) | (options.isRightModifyContents() ? PdfWriter.ALLOW_MODIFY_CONTENTS : 0); stp.setEncryption(true, options.getPdfUserPwdStr(), options.getPdfOwnerPwdStr(), tmpRight); } final PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); if (!StringUtils.isEmpty(options.getReason())) { options.log("console.setReason", options.getReason()); sap.setReason(options.getReason()); } if (!StringUtils.isEmpty(options.getLocation())) { options.log("console.setLocation", options.getLocation()); sap.setLocation(options.getLocation()); } if (!StringUtils.isEmpty(options.getContact())) { options.log("console.setContact", options.getContact()); sap.setContact(options.getContact()); } options.log("console.setCertificationLevel"); sap.setCertificationLevel(options.getCertLevelX().getLevel()); if (options.isVisible()) { // visible signature is enabled options.log("console.configureVisible"); options.log("console.setAcro6Layers"); sap.setAcro6Layers(true); final String tmpImgPath = options.getImgPath(); if (tmpImgPath != null) { options.log("console.createImage", tmpImgPath); final Image img = Image.getInstance(tmpImgPath); options.log("console.setSignatureGraphic"); sap.setSignatureGraphic(img); } final String tmpBgImgPath = options.getBgImgPath(); if (tmpBgImgPath != null) { options.log("console.createImage", tmpBgImgPath); final Image img = Image.getInstance(tmpBgImgPath); options.log("console.setImage"); sap.setImage(img); } options.log("console.setImageScale"); sap.setImageScale(options.getBgImgScale()); options.log("console.setL2Text"); if (options.getL2Text() != null) { sap.setLayer2Text(options.getL2Text()); } else { final StringBuilder buf = new StringBuilder(); buf.append(res.get("default.l2text.signedBy")).append(" "); buf.append(PdfPKCS7.getSubjectFields((X509Certificate) chain[0]).getField("CN")).append('\n'); final SimpleDateFormat sd = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); buf.append(res.get("default.l2text.date")).append(" ").append( sd.format(sap.getSignDate().getTime())); if (StringUtils.hasLength(options.getReason())) buf.append('\n').append(res.get("default.l2text.reason")).append(" ").append( options.getReason()); if (StringUtils.hasLength(options.getLocation())) buf.append('\n').append(res.get("default.l2text.location")).append(" ").append( options.getLocation()); sap.setLayer2Text(buf.toString()); ; } if (FontUtils.getL2BaseFont() != null) { sap.setLayer2Font(new Font(FontUtils.getL2BaseFont(), options.getL2TextFontSize())); } options.log("console.setL4Text"); sap.setLayer4Text(options.getL4Text()); options.log("console.setRender"); sap.setRender(options.getRenderMode().getRender()); options.log("console.setVisibleSignature"); sap.setVisibleSignature(new Rectangle(options.getPositionLLX(), options.getPositionLLY(), options .getPositionURX(), options.getPositionURY()), options.getPage(), null); } options.log("console.processing"); final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached")); dic.setReason(sap.getReason()); dic.setLocation(sap.getLocation()); dic.setContact(sap.getContact()); dic.setDate(new PdfDate(sap.getSignDate())); sap.setCryptoDictionary(dic); final Proxy tmpProxy = options.createProxy(); final CRLInfo crlInfo = new CRLInfo(options, chain); // CRLs are stored twice in PDF c.f. // PdfPKCS7.getAuthenticatedAttributeBytes final int contentEstimated = (int) (Constants.DEFVAL_SIG_SIZE + 2L * crlInfo.getByteCount()); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2)); sap.preClose(exc); PdfPKCS7 sgn = new PdfPKCS7(key, chain, crlInfo.getCrls(), hashAlgorithm.getAlgorithmName(), null, false); InputStream data = sap.getRangeStream(); final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgorithmName()); byte buf[] = new byte[8192]; int n; while ((n = data.read(buf)) > 0) { messageDigest.update(buf, 0, n); } byte hash[] = messageDigest.digest(); Calendar cal = Calendar.getInstance(); byte[] ocsp = null; if (options.isOcspEnabledX() && chain.length >= 2) { options.log("console.getOCSPURL"); String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]); if (url != null && url.length() > 0) { options.log("console.readingOCSP"); final OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle((X509Certificate) chain[0], (X509Certificate) chain[1], url); ocspClient.setProxy(tmpProxy); ocsp = ocspClient.getEncoded(); } } byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp); sgn.update(sh, 0, sh.length); TSAClientBouncyCastle tsc = null; if (options.isTimestampX() && !StringUtils.isEmpty(options.getTsaUrl())) { options.log("console.creatingTsaClient"); tsc = new TSAClientBouncyCastle(options.getTsaUrl(), StringUtils.emptyNull(options.getTsaUser()), StringUtils.emptyNull(options.getTsaPasswd())); tsc.setProxy(tmpProxy); } byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp); if (contentEstimated + 2 < encodedSig.length) { System.err.println("SigSize - contentEstimated=" + contentEstimated + ", sigLen=" + encodedSig.length); throw new Exception("Not enough space"); } byte[] paddedSig = new byte[contentEstimated]; System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true)); options.log("console.closeStream"); sap.close(dic2); fout.close(); } catch (Exception e) { options.log("console.exception"); e.printStackTrace(options.getPrintWriter()); tmpResult = e; } catch (OutOfMemoryError e) { e.printStackTrace(options.getPrintWriter()); options.log("console.memoryError"); } finally { if (fout != null) { try { fout.close(); } catch (Exception e) { e.printStackTrace(); } } } options.log("console.finished." + (tmpResult == null ? "ok" : "error")); options.fireSignerFinishedEvent(tmpResult); }
diff --git a/src/com/android/email/mail/transport/MailTransport.java b/src/com/android/email/mail/transport/MailTransport.java index 5c7f2646c..785d647e6 100644 --- a/src/com/android/email/mail/transport/MailTransport.java +++ b/src/com/android/email/mail/transport/MailTransport.java @@ -1,326 +1,331 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.email.mail.transport; import com.android.email2.ui.MailActivityEmail; import com.android.emailcommon.Logging; import com.android.emailcommon.mail.CertificateValidationException; import com.android.emailcommon.mail.MessagingException; import com.android.emailcommon.mail.Transport; import com.android.emailcommon.provider.HostAuth; import com.android.emailcommon.utility.SSLUtils; import android.content.Context; import android.util.Log; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocket; /** * This class implements the common aspects of "transport", one layer below the * specific wire protocols such as POP3, IMAP, or SMTP. */ public class MailTransport implements Transport { // TODO protected eventually /*protected*/ public static final int SOCKET_CONNECT_TIMEOUT = 10000; /*protected*/ public static final int SOCKET_READ_TIMEOUT = 60000; private static final HostnameVerifier HOSTNAME_VERIFIER = HttpsURLConnection.getDefaultHostnameVerifier(); private final String mDebugLabel; private final Context mContext; private final HostAuth mHostAuth; private Socket mSocket; private InputStream mIn; private OutputStream mOut; public MailTransport(Context context, String debugLabel, HostAuth hostAuth) { super(); mContext = context; mDebugLabel = debugLabel; mHostAuth = hostAuth; } /** * Returns a new transport, using the current transport as a model. The new transport is * configured identically (as if {@link #setSecurity(int, boolean)}, {@link #setPort(int)} * and {@link #setHost(String)} were invoked), but not opened or connected in any way. */ @Override public Transport clone() { return new MailTransport(mContext, mDebugLabel, mHostAuth); } @Override public String getHost() { return mHostAuth.mAddress; } @Override public int getPort() { return mHostAuth.mPort; } @Override public boolean canTrySslSecurity() { return (mHostAuth.mFlags & HostAuth.FLAG_SSL) != 0; } @Override public boolean canTryTlsSecurity() { return (mHostAuth.mFlags & HostAuth.FLAG_TLS) != 0; } @Override public boolean canTrustAllCertificates() { return (mHostAuth.mFlags & HostAuth.FLAG_TRUST_ALL) != 0; } /** * Attempts to open a connection using the Uri supplied for connection parameters. Will attempt * an SSL connection if indicated. */ @Override public void open() throws MessagingException, CertificateValidationException { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, "*** " + mDebugLabel + " open " + getHost() + ":" + String.valueOf(getPort())); } try { SocketAddress socketAddress = new InetSocketAddress(getHost(), getPort()); if (canTrySslSecurity()) { mSocket = SSLUtils.getSSLSocketFactory( mContext, mHostAuth, canTrustAllCertificates()).createSocket(); } else { mSocket = new Socket(); } mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); // After the socket connects to an SSL server, confirm that the hostname is as expected if (canTrySslSecurity() && !canTrustAllCertificates()) { verifyHostname(mSocket, getHost()); } mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); } catch (SSLException e) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, e.toString()); } throw new CertificateValidationException(e.getMessage(), e); } catch (IOException ioe) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, ioe.toString()); } throw new MessagingException(MessagingException.IOERROR, ioe.toString()); + } catch (IllegalArgumentException iae) { + if (MailActivityEmail.DEBUG) { + Log.d(Logging.LOG_TAG, iae.toString()); + } + throw new MessagingException(MessagingException.UNSPECIFIED_EXCEPTION, iae.toString()); } } /** * Attempts to reopen a TLS connection using the Uri supplied for connection parameters. * * NOTE: No explicit hostname verification is required here, because it's handled automatically * by the call to createSocket(). * * TODO should we explicitly close the old socket? This seems funky to abandon it. */ @Override public void reopenTls() throws MessagingException { try { mSocket = SSLUtils.getSSLSocketFactory(mContext, mHostAuth, canTrustAllCertificates()) .createSocket(mSocket, getHost(), getPort(), true); mSocket.setSoTimeout(SOCKET_READ_TIMEOUT); mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); } catch (SSLException e) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, e.toString()); } throw new CertificateValidationException(e.getMessage(), e); } catch (IOException ioe) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, ioe.toString()); } throw new MessagingException(MessagingException.IOERROR, ioe.toString()); } } /** * Lightweight version of SSLCertificateSocketFactory.verifyHostname, which provides this * service but is not in the public API. * * Verify the hostname of the certificate used by the other end of a * connected socket. You MUST call this if you did not supply a hostname * to SSLCertificateSocketFactory.createSocket(). It is harmless to call this method * redundantly if the hostname has already been verified. * * <p>Wildcard certificates are allowed to verify any matching hostname, * so "foo.bar.example.com" is verified if the peer has a certificate * for "*.example.com". * * @param socket An SSL socket which has been connected to a server * @param hostname The expected hostname of the remote server * @throws IOException if something goes wrong handshaking with the server * @throws SSLPeerUnverifiedException if the server cannot prove its identity */ private void verifyHostname(Socket socket, String hostname) throws IOException { // The code at the start of OpenSSLSocketImpl.startHandshake() // ensures that the call is idempotent, so we can safely call it. SSLSocket ssl = (SSLSocket) socket; ssl.startHandshake(); SSLSession session = ssl.getSession(); if (session == null) { throw new SSLException("Cannot verify SSL socket without session"); } // TODO: Instead of reporting the name of the server we think we're connecting to, // we should be reporting the bad name in the certificate. Unfortunately this is buried // in the verifier code and is not available in the verifier API, and extracting the // CN & alts is beyond the scope of this patch. if (!HOSTNAME_VERIFIER.verify(hostname, session)) { throw new SSLPeerUnverifiedException( "Certificate hostname not useable for server: " + hostname); } } /** * Set the socket timeout. * @param timeoutMilliseconds the read timeout value if greater than {@code 0}, or * {@code 0} for an infinite timeout. */ @Override public void setSoTimeout(int timeoutMilliseconds) throws SocketException { mSocket.setSoTimeout(timeoutMilliseconds); } @Override public boolean isOpen() { return (mIn != null && mOut != null && mSocket != null && mSocket.isConnected() && !mSocket.isClosed()); } /** * Close the connection. MUST NOT return any exceptions - must be "best effort" and safe. */ @Override public void close() { try { mIn.close(); } catch (Exception e) { // May fail if the connection is already closed. } try { mOut.close(); } catch (Exception e) { // May fail if the connection is already closed. } try { mSocket.close(); } catch (Exception e) { // May fail if the connection is already closed. } mIn = null; mOut = null; mSocket = null; } @Override public InputStream getInputStream() { return mIn; } @Override public OutputStream getOutputStream() { return mOut; } /** * Writes a single line to the server using \r\n termination. */ @Override public void writeLine(String s, String sensitiveReplacement) throws IOException { if (MailActivityEmail.DEBUG) { if (sensitiveReplacement != null && !Logging.DEBUG_SENSITIVE) { Log.d(Logging.LOG_TAG, ">>> " + sensitiveReplacement); } else { Log.d(Logging.LOG_TAG, ">>> " + s); } } OutputStream out = getOutputStream(); out.write(s.getBytes()); out.write('\r'); out.write('\n'); out.flush(); } /** * Reads a single line from the server, using either \r\n or \n as the delimiter. The * delimiter char(s) are not included in the result. */ @Override public String readLine() throws IOException { StringBuffer sb = new StringBuffer(); InputStream in = getInputStream(); int d; while ((d = in.read()) != -1) { if (((char)d) == '\r') { continue; } else if (((char)d) == '\n') { break; } else { sb.append((char)d); } } if (d == -1 && MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, "End of stream reached while trying to read line."); } String ret = sb.toString(); if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, "<<< " + ret); } return ret; } @Override public InetAddress getLocalAddress() { if (isOpen()) { return mSocket.getLocalAddress(); } else { return null; } } }
true
true
public void open() throws MessagingException, CertificateValidationException { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, "*** " + mDebugLabel + " open " + getHost() + ":" + String.valueOf(getPort())); } try { SocketAddress socketAddress = new InetSocketAddress(getHost(), getPort()); if (canTrySslSecurity()) { mSocket = SSLUtils.getSSLSocketFactory( mContext, mHostAuth, canTrustAllCertificates()).createSocket(); } else { mSocket = new Socket(); } mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); // After the socket connects to an SSL server, confirm that the hostname is as expected if (canTrySslSecurity() && !canTrustAllCertificates()) { verifyHostname(mSocket, getHost()); } mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); } catch (SSLException e) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, e.toString()); } throw new CertificateValidationException(e.getMessage(), e); } catch (IOException ioe) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, ioe.toString()); } throw new MessagingException(MessagingException.IOERROR, ioe.toString()); } }
public void open() throws MessagingException, CertificateValidationException { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, "*** " + mDebugLabel + " open " + getHost() + ":" + String.valueOf(getPort())); } try { SocketAddress socketAddress = new InetSocketAddress(getHost(), getPort()); if (canTrySslSecurity()) { mSocket = SSLUtils.getSSLSocketFactory( mContext, mHostAuth, canTrustAllCertificates()).createSocket(); } else { mSocket = new Socket(); } mSocket.connect(socketAddress, SOCKET_CONNECT_TIMEOUT); // After the socket connects to an SSL server, confirm that the hostname is as expected if (canTrySslSecurity() && !canTrustAllCertificates()) { verifyHostname(mSocket, getHost()); } mIn = new BufferedInputStream(mSocket.getInputStream(), 1024); mOut = new BufferedOutputStream(mSocket.getOutputStream(), 512); } catch (SSLException e) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, e.toString()); } throw new CertificateValidationException(e.getMessage(), e); } catch (IOException ioe) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, ioe.toString()); } throw new MessagingException(MessagingException.IOERROR, ioe.toString()); } catch (IllegalArgumentException iae) { if (MailActivityEmail.DEBUG) { Log.d(Logging.LOG_TAG, iae.toString()); } throw new MessagingException(MessagingException.UNSPECIFIED_EXCEPTION, iae.toString()); } }
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/ui/FunctionListModel.java b/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/ui/FunctionListModel.java index 9e1b72ed4..bd7e7e329 100644 --- a/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/ui/FunctionListModel.java +++ b/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/sqlConsole/ui/FunctionListModel.java @@ -1,126 +1,126 @@ /* * OrbisGIS is a GIS application dedicated to scientific spatial simulation. * This cross-platform GIS is developed at French IRSTV institute and is able to * manipulate and create vector and raster spatial information. OrbisGIS is * distributed under GPL 3 license. It is produced by the "Atelier SIG" team of * the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488. * * * Team leader Erwan BOCHER, scientific researcher * * * Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC * * Copyright (C) 2010 Erwan BOCHER, Alexis GUEGANNO, Antoine GOURLAY, Adelin PIAU, Gwendall PETIT * * Copyright (C) 2010 Erwan BOCHER, Alexis GUEGANNO, Antoine GOURLAY, Gwendall PETIT * * This file is part of OrbisGIS. * * OrbisGIS is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * OrbisGIS. If not, see <http://www.gnu.org/licenses/>. * * For more information, please consult: <http://www.orbisgis.org/> * * or contact directly: * info _at_ orbisgis.org */ package org.orbisgis.core.ui.plugins.views.sqlConsole.ui; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.swing.AbstractListModel; import javax.swing.ListModel; import org.gdms.sql.customQuery.QueryManager; import org.gdms.sql.function.FunctionManager; /** * A custom list model to load and manage GDMS functions. * @author ebocher */ public class FunctionListModel extends AbstractListModel implements ListModel { private ArrayList<FunctionElement> functionsList; public FunctionListModel() { getSQLFunctions(); } @Override public int getSize() { return functionsList.size(); } @Override public Object getElementAt(int i) { return functionsList.get(i); } private void getSQLFunctions() { functionsList = new ArrayList<FunctionElement>(); String[] functions = FunctionManager.getFunctionNames(); for (String functionName : functions) { functionsList.add(new FunctionElement(functionName.toUpperCase(), FunctionElement.BASIC_FUNCTION)); } String[] customQueries = QueryManager.getQueryNames(); for (String customName : customQueries) { functionsList.add(new FunctionElement(customName.toUpperCase(), FunctionElement.CUSTOM_FUNCTION)); } Collections.sort(functionsList, new NameComparator()); } /** * A method to update the list according to a text filter * @param text */ public void filter(String text) { if (text.length() == 0) { getSQLFunctions(); } else { ArrayList<FunctionElement> functionsFiltered = new ArrayList<FunctionElement>(); for (FunctionElement functionElement : functionsList) { - if (functionElement.getFunctionName().toLowerCase().contains(text)) { + if (functionElement.getFunctionName().toLowerCase().contains(text.toLowerCase())) { functionsFiltered.add(functionElement); } } functionsList = functionsFiltered; } fireIntervalRemoved(this, 0, getSize()); fireIntervalAdded(this, 0, getSize()); } /** * A comparator to order functionElement according to its name. */ private static class NameComparator implements Comparator { public NameComparator() { } @Override public int compare(Object t, Object t1) { FunctionElement functionElement1 = (FunctionElement) t; FunctionElement functionElement2 = (FunctionElement) t1; return functionElement1.getFunctionName().toLowerCase().compareTo(functionElement2.getFunctionName().toLowerCase()); } } }
true
true
public void filter(String text) { if (text.length() == 0) { getSQLFunctions(); } else { ArrayList<FunctionElement> functionsFiltered = new ArrayList<FunctionElement>(); for (FunctionElement functionElement : functionsList) { if (functionElement.getFunctionName().toLowerCase().contains(text)) { functionsFiltered.add(functionElement); } } functionsList = functionsFiltered; } fireIntervalRemoved(this, 0, getSize()); fireIntervalAdded(this, 0, getSize()); }
public void filter(String text) { if (text.length() == 0) { getSQLFunctions(); } else { ArrayList<FunctionElement> functionsFiltered = new ArrayList<FunctionElement>(); for (FunctionElement functionElement : functionsList) { if (functionElement.getFunctionName().toLowerCase().contains(text.toLowerCase())) { functionsFiltered.add(functionElement); } } functionsList = functionsFiltered; } fireIntervalRemoved(this, 0, getSize()); fireIntervalAdded(this, 0, getSize()); }
diff --git a/src/gov/nih/nci/ncicb/cadsr/loader/persister/DEPersister.java b/src/gov/nih/nci/ncicb/cadsr/loader/persister/DEPersister.java index 9940af99..2a31d454 100755 --- a/src/gov/nih/nci/ncicb/cadsr/loader/persister/DEPersister.java +++ b/src/gov/nih/nci/ncicb/cadsr/loader/persister/DEPersister.java @@ -1,250 +1,250 @@ /* * Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.persister; import gov.nih.nci.ncicb.cadsr.dao.*; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.ElementsLists; import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressEvent; import gov.nih.nci.ncicb.cadsr.loader.event.ProgressListener; import gov.nih.nci.ncicb.cadsr.loader.util.*; import org.apache.log4j.Logger; import java.util.*; /** * * @author <a href="mailto:[email protected]">Christophe Ludet</a> */ public class DEPersister implements Persister { private static Logger logger = Logger.getLogger(DEPersister.class.getName()); public static String DE_PREFERRED_NAME_DELIMITER = "v"; public static String DE_PREFERRED_NAME_CONCAT_CHAR = ":"; public static String DE_PREFERRED_DEF_CONCAT_CHAR = "_"; private UMLDefaults defaults = UMLDefaults.getInstance(); private ElementsLists elements = ElementsLists.getInstance(); private ProgressListener progressListener = null; private PersisterUtil persisterUtil; private DataElementDAO dataElementDAO; public DEPersister() { initDAOs(); } public void persist() { DataElement de = DomainObjectFactory.newDataElement(); List<DataElement> des = elements.getElements(de); logger.debug("des..."); int count = 0; sendProgressEvent(count++, des.size(), "DEs"); if (des != null) { for (ListIterator<DataElement> it = des.listIterator(); it.hasNext();) { try { de = it.next(); sendProgressEvent(count++, des.size(), "DE : " + de.getLongName()); DataElement newDe = DomainObjectFactory.newDataElement(); de.setDataElementConcept( persisterUtil.lookupDec(de.getDataElementConcept().getId())); newDe.setDataElementConcept(de.getDataElementConcept()); ValueDomain vd = LookupUtil.lookupValueDomain(de.getValueDomain()); if(vd == null) { logger.error("Value Domain " + de.getValueDomain().getLongName() + " does not exist."); logger.error("CDE " + de.getLongName() + " DID NOT GET LOADED"); continue; } de.setValueDomain(vd); // } newDe.setValueDomain(de.getValueDomain()); if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { newDe = existingMapping(de); /* if DE alreay exists, check context * If context is different, add Used_by alt_name */ de.setId(newDe.getId()); if (!newDe.getContext().getId().equals(defaults.getContext().getId())) { AlternateName _an = DomainObjectFactory.newAlternateName(); _an.setName(defaults.getContext().getName()); _an.setType(AlternateName.TYPE_USED_BY); persisterUtil.addAlternateName(de, _an); } logger.info(PropertyAccessor.getProperty("mapped.to.existing.de")); } else { List l = dataElementDAO.find(newDe); de.setLongName(this.deriveLongName(de)); if (l.size() == 0) { de.setContext(defaults.getContext()); de.setPreferredName(this.derivePreferredName(de)); de.setVersion(new Float(1.0f)); de.setWorkflowStatus(defaults.getWorkflowStatus()); de.setPreferredDefinition( de.getDataElementConcept().getPreferredDefinition() + DE_PREFERRED_DEF_CONCAT_CHAR + de.getValueDomain().getPreferredDefinition() ); de.setAudit(defaults.getAudit()); de.setLifecycle(defaults.getLifecycle()); logger.debug("Creating DE: " + de.getLongName()); List<AlternateName> altNames = new ArrayList<AlternateName>(de.getAlternateNames()); List<Definition> altDefs = new ArrayList<Definition>(de.getDefinitions()); de.removeAlternateNames(); de.removeDefinitions(); newDe = dataElementDAO.create(de); // restore altNames for(AlternateName an : altNames) { de.addAlternateName(an); } // restore altDefs for(Definition def : altDefs) { de.addDefinition(def); } logger.info(PropertyAccessor.getProperty("created.de")); } else { newDe = (DataElement) l.get(0); logger.info(PropertyAccessor.getProperty("existed.de")); /* if DE alreay exists, check context * If context is different, add Used_by alt_name */ de.setId(newDe.getId()); if (!newDe.getContext().getId().equals(defaults.getContext().getId())) { persisterUtil.addAlternateName( de, defaults.getContext().getName(), AlternateName.TYPE_USED_BY, null); } } } LogUtil.logAc(newDe, logger); logger.info( PropertyAccessor.getProperty( "vd.preferredName", newDe.getValueDomain().getPreferredName())); de.setId(newDe.getId()); persisterUtil.addPackageClassification(de); for(AlternateName altName : de.getAlternateNames()) { persisterUtil.addAlternateName(de, altName); } for(Definition def : de.getDefinitions()) { persisterUtil.addAlternateDefinition(de, def); } /** * update the reference docs */ if (de.getReferenceDocuments() != null) { - persisterUtil.updateRefDocs(de, de.getReferenceDocuments()); + persisterUtil.updateRefDocs(de); } it.set(newDe); } catch (PersisterException e) { logger.error("Could not persist DE: " + de.getLongName()); logger.error(e.getMessage()); } // end of try-catch } } } //Will need to declare this method as abstract method in UMLPersistor protected String derivePreferredName (AdminComponent ac ) { DataElement de = (DataElement)ac; String preferredName = ConventionUtil.publicIdVersion(de.getDataElementConcept()) +DE_PREFERRED_NAME_CONCAT_CHAR +ConventionUtil.publicIdVersion(de.getValueDomain()); return preferredName; } //Will need to declare this method as abstract method in UMLPersistor protected String deriveLongName (AdminComponent ac ) { DataElement de = (DataElement)ac; String longName = de.getDataElementConcept().getLongName() + " " +de.getValueDomain().getLongName(); return longName; } private DataElement existingMapping(DataElement de) { List<String> eager = new ArrayList<String>(); eager.add(EagerConstants.AC_CS_CSI); List<DataElement> l = dataElementDAO.find(de, eager); if(l.size() == 0) throw new PersisterException(PropertyAccessor.getProperty("de.existing.error", ConventionUtil.publicIdVersion(de))); DataElement existingDe = l.get(0); return existingDe; } protected void sendProgressEvent(int status, int goal, String message) { if(progressListener != null) { ProgressEvent pEvent = new ProgressEvent(); pEvent.setMessage(message); pEvent.setStatus(status); pEvent.setGoal(goal); progressListener.newProgressEvent(pEvent); } } public void setProgressListener(ProgressListener listener) { progressListener = listener; } public void setPersisterUtil(PersisterUtil pu) { persisterUtil = pu; } private void initDAOs() { dataElementDAO = DAOAccessor.getDataElementDAO(); } }
true
true
public void persist() { DataElement de = DomainObjectFactory.newDataElement(); List<DataElement> des = elements.getElements(de); logger.debug("des..."); int count = 0; sendProgressEvent(count++, des.size(), "DEs"); if (des != null) { for (ListIterator<DataElement> it = des.listIterator(); it.hasNext();) { try { de = it.next(); sendProgressEvent(count++, des.size(), "DE : " + de.getLongName()); DataElement newDe = DomainObjectFactory.newDataElement(); de.setDataElementConcept( persisterUtil.lookupDec(de.getDataElementConcept().getId())); newDe.setDataElementConcept(de.getDataElementConcept()); ValueDomain vd = LookupUtil.lookupValueDomain(de.getValueDomain()); if(vd == null) { logger.error("Value Domain " + de.getValueDomain().getLongName() + " does not exist."); logger.error("CDE " + de.getLongName() + " DID NOT GET LOADED"); continue; } de.setValueDomain(vd); // } newDe.setValueDomain(de.getValueDomain()); if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { newDe = existingMapping(de); /* if DE alreay exists, check context * If context is different, add Used_by alt_name */ de.setId(newDe.getId()); if (!newDe.getContext().getId().equals(defaults.getContext().getId())) { AlternateName _an = DomainObjectFactory.newAlternateName(); _an.setName(defaults.getContext().getName()); _an.setType(AlternateName.TYPE_USED_BY); persisterUtil.addAlternateName(de, _an); } logger.info(PropertyAccessor.getProperty("mapped.to.existing.de")); } else { List l = dataElementDAO.find(newDe); de.setLongName(this.deriveLongName(de)); if (l.size() == 0) { de.setContext(defaults.getContext()); de.setPreferredName(this.derivePreferredName(de)); de.setVersion(new Float(1.0f)); de.setWorkflowStatus(defaults.getWorkflowStatus()); de.setPreferredDefinition( de.getDataElementConcept().getPreferredDefinition() + DE_PREFERRED_DEF_CONCAT_CHAR + de.getValueDomain().getPreferredDefinition() ); de.setAudit(defaults.getAudit()); de.setLifecycle(defaults.getLifecycle()); logger.debug("Creating DE: " + de.getLongName()); List<AlternateName> altNames = new ArrayList<AlternateName>(de.getAlternateNames()); List<Definition> altDefs = new ArrayList<Definition>(de.getDefinitions()); de.removeAlternateNames(); de.removeDefinitions(); newDe = dataElementDAO.create(de); // restore altNames for(AlternateName an : altNames) { de.addAlternateName(an); } // restore altDefs for(Definition def : altDefs) { de.addDefinition(def); } logger.info(PropertyAccessor.getProperty("created.de")); } else { newDe = (DataElement) l.get(0); logger.info(PropertyAccessor.getProperty("existed.de")); /* if DE alreay exists, check context * If context is different, add Used_by alt_name */ de.setId(newDe.getId()); if (!newDe.getContext().getId().equals(defaults.getContext().getId())) { persisterUtil.addAlternateName( de, defaults.getContext().getName(), AlternateName.TYPE_USED_BY, null); } } } LogUtil.logAc(newDe, logger); logger.info( PropertyAccessor.getProperty( "vd.preferredName", newDe.getValueDomain().getPreferredName())); de.setId(newDe.getId()); persisterUtil.addPackageClassification(de); for(AlternateName altName : de.getAlternateNames()) { persisterUtil.addAlternateName(de, altName); } for(Definition def : de.getDefinitions()) { persisterUtil.addAlternateDefinition(de, def); } /** * update the reference docs */ if (de.getReferenceDocuments() != null) { persisterUtil.updateRefDocs(de, de.getReferenceDocuments()); } it.set(newDe); } catch (PersisterException e) { logger.error("Could not persist DE: " + de.getLongName()); logger.error(e.getMessage()); } // end of try-catch } } }
public void persist() { DataElement de = DomainObjectFactory.newDataElement(); List<DataElement> des = elements.getElements(de); logger.debug("des..."); int count = 0; sendProgressEvent(count++, des.size(), "DEs"); if (des != null) { for (ListIterator<DataElement> it = des.listIterator(); it.hasNext();) { try { de = it.next(); sendProgressEvent(count++, des.size(), "DE : " + de.getLongName()); DataElement newDe = DomainObjectFactory.newDataElement(); de.setDataElementConcept( persisterUtil.lookupDec(de.getDataElementConcept().getId())); newDe.setDataElementConcept(de.getDataElementConcept()); ValueDomain vd = LookupUtil.lookupValueDomain(de.getValueDomain()); if(vd == null) { logger.error("Value Domain " + de.getValueDomain().getLongName() + " does not exist."); logger.error("CDE " + de.getLongName() + " DID NOT GET LOADED"); continue; } de.setValueDomain(vd); // } newDe.setValueDomain(de.getValueDomain()); if(!StringUtil.isEmpty(de.getPublicId()) && de.getVersion() != null) { newDe = existingMapping(de); /* if DE alreay exists, check context * If context is different, add Used_by alt_name */ de.setId(newDe.getId()); if (!newDe.getContext().getId().equals(defaults.getContext().getId())) { AlternateName _an = DomainObjectFactory.newAlternateName(); _an.setName(defaults.getContext().getName()); _an.setType(AlternateName.TYPE_USED_BY); persisterUtil.addAlternateName(de, _an); } logger.info(PropertyAccessor.getProperty("mapped.to.existing.de")); } else { List l = dataElementDAO.find(newDe); de.setLongName(this.deriveLongName(de)); if (l.size() == 0) { de.setContext(defaults.getContext()); de.setPreferredName(this.derivePreferredName(de)); de.setVersion(new Float(1.0f)); de.setWorkflowStatus(defaults.getWorkflowStatus()); de.setPreferredDefinition( de.getDataElementConcept().getPreferredDefinition() + DE_PREFERRED_DEF_CONCAT_CHAR + de.getValueDomain().getPreferredDefinition() ); de.setAudit(defaults.getAudit()); de.setLifecycle(defaults.getLifecycle()); logger.debug("Creating DE: " + de.getLongName()); List<AlternateName> altNames = new ArrayList<AlternateName>(de.getAlternateNames()); List<Definition> altDefs = new ArrayList<Definition>(de.getDefinitions()); de.removeAlternateNames(); de.removeDefinitions(); newDe = dataElementDAO.create(de); // restore altNames for(AlternateName an : altNames) { de.addAlternateName(an); } // restore altDefs for(Definition def : altDefs) { de.addDefinition(def); } logger.info(PropertyAccessor.getProperty("created.de")); } else { newDe = (DataElement) l.get(0); logger.info(PropertyAccessor.getProperty("existed.de")); /* if DE alreay exists, check context * If context is different, add Used_by alt_name */ de.setId(newDe.getId()); if (!newDe.getContext().getId().equals(defaults.getContext().getId())) { persisterUtil.addAlternateName( de, defaults.getContext().getName(), AlternateName.TYPE_USED_BY, null); } } } LogUtil.logAc(newDe, logger); logger.info( PropertyAccessor.getProperty( "vd.preferredName", newDe.getValueDomain().getPreferredName())); de.setId(newDe.getId()); persisterUtil.addPackageClassification(de); for(AlternateName altName : de.getAlternateNames()) { persisterUtil.addAlternateName(de, altName); } for(Definition def : de.getDefinitions()) { persisterUtil.addAlternateDefinition(de, def); } /** * update the reference docs */ if (de.getReferenceDocuments() != null) { persisterUtil.updateRefDocs(de); } it.set(newDe); } catch (PersisterException e) { logger.error("Could not persist DE: " + de.getLongName()); logger.error(e.getMessage()); } // end of try-catch } } }
diff --git a/main/java/org/spoutcraft/spoutcraftapi/gui/GenericScreen.java b/main/java/org/spoutcraft/spoutcraftapi/gui/GenericScreen.java index 1fe32213..e0225f04 100755 --- a/main/java/org/spoutcraft/spoutcraftapi/gui/GenericScreen.java +++ b/main/java/org/spoutcraft/spoutcraftapi/gui/GenericScreen.java @@ -1,230 +1,230 @@ /* * This file is part of Spoutcraft (http://wiki.getspout.org/). * * Spoutcraft is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Spoutcraft is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.spoutcraft.spoutcraftapi.gui; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.UUID; import org.lwjgl.opengl.GL11; import org.spoutcraft.spoutcraftapi.Spoutcraft; public abstract class GenericScreen extends GenericWidget implements Screen { protected HashMap<Widget, String> widgets = new HashMap<Widget, String>(); protected int playerId; protected boolean bgvis; protected int mouseX = -1, mouseY = -1; public GenericScreen() { screenWidth = Spoutcraft.getClient().getRenderDelegate().getScreenWidth(); screenHeight = Spoutcraft.getClient().getRenderDelegate().getScreenHeight(); } public GenericScreen(int playerId) { this.playerId = playerId; } @Override public int getVersion() { return super.getVersion() + 0; } public Widget[] getAttachedWidgets() { return getAttachedWidgets(false); } public Widget[] getAttachedWidgets(boolean recursive) { Widget[] list = new Widget[widgets.size()]; Set<Widget> allwidgets = new HashSet<Widget>(); allwidgets.addAll(widgets.keySet()); if(recursive) { for(Widget w:widgets.keySet()) { if(w instanceof Screen) { allwidgets.addAll(((Screen)w).getAttachedWidgetsAsSet(true)); } } } - allwidgets.toArray(list); + list = allwidgets.toArray(list); return list; } public Set<Widget> getAttachedWidgetsAsSet() { return getAttachedWidgetsAsSet(false); } public Set<Widget> getAttachedWidgetsAsSet(boolean recursive) { Set<Widget> allwidgets = new HashSet<Widget>(); allwidgets.addAll(widgets.keySet()); if(recursive) { for(Widget w:widgets.keySet()) { if(w instanceof Screen) { allwidgets.addAll(((Screen)w).getAttachedWidgetsAsSet(true)); } } } return allwidgets; } @Deprecated public Screen attachWidget(Widget widget) { return attachWidget(null, widget); } public Screen attachWidget(String plugin, Widget widget) { widgets.put(widget, plugin); widget.setPlugin(plugin); widget.setDirty(true); widget.setScreen(this); return this; } public Screen removeWidget(Widget widget) { widgets.remove(widget); widget.setScreen(null); return this; } public Screen removeWidgets(String p) { for (Widget i : getAttachedWidgets()) { if (widgets.get(i) != null && widgets.get(i).equals(p)) { removeWidget(i); } } return this; } public boolean containsWidget(Widget widget) { return containsWidget(widget.getId()); } public boolean containsWidget(UUID id) { return getWidget(id) != null; } public Widget getWidget(UUID id) { for (Widget w : widgets.keySet()) { if (w.getId().equals(id)) { return w; } } return null; } public boolean updateWidget(Widget widget) { if (widgets.containsKey(widget)) { String plugin = widgets.get(widget); widgets.remove(widget); widgets.put(widget, plugin); widget.setScreen(this); return true; } return false; } @Override public void onTick() { for (Widget widget : widgets.keySet()) { widget.onTick(); } screenWidth = Spoutcraft.getClient().getRenderDelegate().getScreenWidth(); screenHeight = Spoutcraft.getClient().getRenderDelegate().getScreenHeight(); } private int screenHeight, screenWidth; @Override public double getHeight() { return screenHeight > 0 ? screenHeight : 240; } @Override public double getWidth() { return screenWidth > 0 ? screenWidth : 427; } public GenericScreen setBgVisible(boolean enable) { bgvis = enable; return this; } public boolean isBgVisible() { return bgvis; } @Override public int getNumBytes() { return super.getNumBytes() + 1; } @Override public void readData(DataInputStream input) throws IOException { super.readData(input); setBgVisible(input.readBoolean()); } @Override public void writeData(DataOutputStream output) throws IOException { super.writeData(output); output.writeBoolean(isBgVisible()); } protected boolean canRender(Widget widget) { return widget.isVisible(); } RenderPriority[] rvalues = RenderPriority.values(); public void render() { for (RenderPriority priority : rvalues) { for (Widget widget : widgets.keySet()) { if (widget.getPriority() == priority && canRender(widget)) { GL11.glPushMatrix(); widget.render(); GL11.glPopMatrix(); } } } } public Screen setMouseX(int mouseX) { this.mouseX = mouseX; return this; } public Screen setMouseY(int mouseY) { this.mouseY = mouseY; return this; } public int getMouseX() { return mouseX; } public int getMouseY() { return mouseY; } @Override public Widget copy() { throw new UnsupportedOperationException("You can not create a copy of a screen"); } }
true
true
public Widget[] getAttachedWidgets(boolean recursive) { Widget[] list = new Widget[widgets.size()]; Set<Widget> allwidgets = new HashSet<Widget>(); allwidgets.addAll(widgets.keySet()); if(recursive) { for(Widget w:widgets.keySet()) { if(w instanceof Screen) { allwidgets.addAll(((Screen)w).getAttachedWidgetsAsSet(true)); } } } allwidgets.toArray(list); return list; }
public Widget[] getAttachedWidgets(boolean recursive) { Widget[] list = new Widget[widgets.size()]; Set<Widget> allwidgets = new HashSet<Widget>(); allwidgets.addAll(widgets.keySet()); if(recursive) { for(Widget w:widgets.keySet()) { if(w instanceof Screen) { allwidgets.addAll(((Screen)w).getAttachedWidgetsAsSet(true)); } } } list = allwidgets.toArray(list); return list; }
diff --git a/src/org/biojava/bio/symbol/AbstractReversibleTranslationTable.java b/src/org/biojava/bio/symbol/AbstractReversibleTranslationTable.java index 677d2a344..c2eea6d08 100644 --- a/src/org/biojava/bio/symbol/AbstractReversibleTranslationTable.java +++ b/src/org/biojava/bio/symbol/AbstractReversibleTranslationTable.java @@ -1,90 +1,90 @@ /* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.bio.symbol; import java.util.Iterator; import java.util.Set; import java.util.HashSet; /** * an abstract class implementing basic functionality * of a translation table that translates Symbols from * one Alphabet to another. * * @author Matthew Pocock * @author Keith James (docs) * @author Thomas Down * @author Greg Cox * @author Mark Schreiber * @author David Huen (refactoring) */ public abstract class AbstractReversibleTranslationTable extends AbstractTranslationTable implements ReversibleTranslationTable { public abstract Alphabet getSourceAlphabet(); public abstract Alphabet getTargetAlphabet(); /** * this method is expected to reverse-translate any symbol * in the source alphabet. Failure can be indicated * by returning a null if, for example, your method * only handles AtomicSymbols and you want BasisSymbols * to be taken apart. If you are sure the symbol is * illegal, you can throw the IllegalSymbolException * immediately to bypass further processing. * <p> * As an optimisation, if your method is capable of * immediately translating an ambiguity Symbol, just * return it and the alternate route of establishing * the translation through doing an ambiguity * lookup will be avoided. */ protected abstract Symbol doUntranslate(Symbol sym) throws IllegalSymbolException; public Symbol untranslate(final Symbol sym) throws IllegalSymbolException { // make an attempt to translate immediately Symbol s = doUntranslate(sym); // translation failed, validate and try an ambiguity lookup if(s == null) { if(sym instanceof AtomicSymbol) { //changed this from s to sym, since we already checked and s is null getSourceAlphabet().validate(sym); // the symbol was valid and still we can't handle it, bail out! throw new IllegalSymbolException("Unable to map " + sym.getName()); } else { if(sym == null) { throw new NullPointerException("Can't translate null"); } Set syms = new HashSet(); for (Iterator i = ((FiniteAlphabet) sym.getMatches()).iterator(); i.hasNext(); ) { Symbol is = (Symbol) i.next(); - syms.add(this.translate(is)); + syms.add(this.untranslate(is)); } s = getTargetAlphabet().getAmbiguity(syms); } } return s; } }
true
true
public Symbol untranslate(final Symbol sym) throws IllegalSymbolException { // make an attempt to translate immediately Symbol s = doUntranslate(sym); // translation failed, validate and try an ambiguity lookup if(s == null) { if(sym instanceof AtomicSymbol) { //changed this from s to sym, since we already checked and s is null getSourceAlphabet().validate(sym); // the symbol was valid and still we can't handle it, bail out! throw new IllegalSymbolException("Unable to map " + sym.getName()); } else { if(sym == null) { throw new NullPointerException("Can't translate null"); } Set syms = new HashSet(); for (Iterator i = ((FiniteAlphabet) sym.getMatches()).iterator(); i.hasNext(); ) { Symbol is = (Symbol) i.next(); syms.add(this.translate(is)); } s = getTargetAlphabet().getAmbiguity(syms); } } return s; }
public Symbol untranslate(final Symbol sym) throws IllegalSymbolException { // make an attempt to translate immediately Symbol s = doUntranslate(sym); // translation failed, validate and try an ambiguity lookup if(s == null) { if(sym instanceof AtomicSymbol) { //changed this from s to sym, since we already checked and s is null getSourceAlphabet().validate(sym); // the symbol was valid and still we can't handle it, bail out! throw new IllegalSymbolException("Unable to map " + sym.getName()); } else { if(sym == null) { throw new NullPointerException("Can't translate null"); } Set syms = new HashSet(); for (Iterator i = ((FiniteAlphabet) sym.getMatches()).iterator(); i.hasNext(); ) { Symbol is = (Symbol) i.next(); syms.add(this.untranslate(is)); } s = getTargetAlphabet().getAmbiguity(syms); } } return s; }
diff --git a/realtime/src/main/java/com/metamx/druid/realtime/firehose/WikipediaIrcDecoder.java b/realtime/src/main/java/com/metamx/druid/realtime/firehose/WikipediaIrcDecoder.java index b1ecf91554..fc45f5f4e9 100644 --- a/realtime/src/main/java/com/metamx/druid/realtime/firehose/WikipediaIrcDecoder.java +++ b/realtime/src/main/java/com/metamx/druid/realtime/firehose/WikipediaIrcDecoder.java @@ -1,222 +1,227 @@ /* * Druid - a distributed column store. * Copyright (C) 2013 Metamarkets Group Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.metamx.druid.realtime.firehose; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.model.Omni; import com.metamx.common.logger.Logger; import com.metamx.druid.input.InputRow; import org.apache.commons.io.FileUtils; import org.joda.time.DateTime; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.GZIPInputStream; class WikipediaIrcDecoder implements IrcDecoder { static final Logger log = new Logger(WikipediaIrcDecoder.class); final DatabaseReader geoLookup; static final Pattern pattern = Pattern.compile( "\\x0314\\[\\[\\x0307(.+?)\\x0314\\]\\]\\x034 (.*?)\\x0310.*\\x0302(http.+?)\\x03.+\\x0303(.+?)\\x03.+\\x03 (\\(([+-]\\d+)\\).*|.+) \\x0310(.+)\\x03" ); static final Pattern ipPattern = Pattern.compile("\\d+.\\d+.\\d+.\\d+"); static final Pattern shortnamePattern = Pattern.compile("#(\\w\\w)\\..*"); static final List<String> dimensionList = Lists.newArrayList( "page", "language", "user", "unpatrolled", "newPage", "robot", "anonymous", "namespace", "continent", "country", "region", "city" ); final Map<String, Map<String, String>> namespaces; public WikipediaIrcDecoder( Map<String, Map<String, String>> namespaces) { this(namespaces, null); } @JsonCreator public WikipediaIrcDecoder(@JsonProperty("namespaces") Map<String, Map<String, String>> namespaces, @JsonProperty("geoIpDatabase") String geoIpDatabase) { if(namespaces == null) { namespaces = Maps.newHashMap(); } this.namespaces = namespaces; File geoDb; if(geoIpDatabase != null) { geoDb = new File(geoIpDatabase); } else { try { String tmpDir = System.getProperty("java.io.tmpdir"); geoDb = new File(tmpDir, this.getClass().getCanonicalName() + ".GeoLite2-City.mmdb"); if(!geoDb.exists()) { log.info("Downloading geo ip database to [%s]", geoDb); FileUtils.copyInputStreamToFile( new GZIPInputStream( new URL("http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz").openStream() ), geoDb ); } } catch(IOException e) { throw new RuntimeException("Unable to download geo ip database [%s]", e); } } try { geoLookup = new DatabaseReader(geoDb); } catch(IOException e) { throw new RuntimeException("Unable to open geo ip lookup database", e); } } @Override public InputRow decodeMessage(final DateTime timestamp, String channel, String msg) { final Map<String, String> dimensions = Maps.newHashMap(); final Map<String, Float> metrics = Maps.newHashMap(); Matcher m = pattern.matcher(msg); if(!m.matches()) { throw new IllegalArgumentException("Invalid input format"); } Matcher shortname = shortnamePattern.matcher(channel); if(shortname.matches()) { dimensions.put("language", shortname.group(1)); } String page = m.group(1); String pageUrl = page.replaceAll("\\s", "_"); dimensions.put("page", pageUrl); String user = m.group(4); Matcher ipMatch = ipPattern.matcher(user); boolean anonymous = ipMatch.matches(); if(anonymous) { try { final InetAddress ip = InetAddress.getByName(ipMatch.group()); final Omni lookup = geoLookup.omni(ip); dimensions.put("continent", lookup.getContinent().getName()); dimensions.put("country", lookup.getCountry().getName()); dimensions.put("region", lookup.getMostSpecificSubdivision().getName()); dimensions.put("city", lookup.getCity().getName()); } catch(UnknownHostException e) { log.error(e, "invalid ip [%s]", ipMatch.group()); } catch(IOException e) { log.error(e, "error looking up geo ip"); } catch(GeoIp2Exception e) { log.error(e, "error looking up geo ip"); } } dimensions.put("user", user); final String flags = m.group(2); dimensions.put("unpatrolled", Boolean.toString(flags.contains("!"))); dimensions.put("newPage", Boolean.toString(flags.contains("N"))); dimensions.put("robot", Boolean.toString(flags.contains("B"))); dimensions.put("anonymous", Boolean.toString(anonymous)); String[] parts = page.split(":"); if(parts.length > 1 && !parts[1].startsWith(" ")) { Map<String, String> channelNamespaces = namespaces.get(channel); if(channelNamespaces != null && channelNamespaces.containsKey(parts[0])) { dimensions.put("namespace", channelNamespaces.get(parts[0])); } else { dimensions.put("namespace", "wikipedia"); } } else { dimensions.put("namespace", "article"); } float delta = m.group(6) != null ? Float.parseFloat(m.group(6)) : 0; metrics.put("delta", delta); metrics.put("added", Math.max(delta, 0)); metrics.put("deleted", Math.min(delta, 0)); return new InputRow() { @Override public List<String> getDimensions() { return dimensionList; } @Override public long getTimestampFromEpoch() { return timestamp.getMillis(); } @Override public List<String> getDimension(String dimension) { - return ImmutableList.of(dimensions.get(dimension)); + final String value = dimensions.get(dimension); + if(value != null) { + return ImmutableList.of(value); + } else { + return ImmutableList.of(); + } } @Override public float getFloatMetric(String metric) { return metrics.get(metric); } @Override public String toString() { return "WikipediaRow{" + "timestamp=" + timestamp + ", dimensions=" + dimensions + ", metrics=" + metrics + '}'; } }; } }
true
true
public InputRow decodeMessage(final DateTime timestamp, String channel, String msg) { final Map<String, String> dimensions = Maps.newHashMap(); final Map<String, Float> metrics = Maps.newHashMap(); Matcher m = pattern.matcher(msg); if(!m.matches()) { throw new IllegalArgumentException("Invalid input format"); } Matcher shortname = shortnamePattern.matcher(channel); if(shortname.matches()) { dimensions.put("language", shortname.group(1)); } String page = m.group(1); String pageUrl = page.replaceAll("\\s", "_"); dimensions.put("page", pageUrl); String user = m.group(4); Matcher ipMatch = ipPattern.matcher(user); boolean anonymous = ipMatch.matches(); if(anonymous) { try { final InetAddress ip = InetAddress.getByName(ipMatch.group()); final Omni lookup = geoLookup.omni(ip); dimensions.put("continent", lookup.getContinent().getName()); dimensions.put("country", lookup.getCountry().getName()); dimensions.put("region", lookup.getMostSpecificSubdivision().getName()); dimensions.put("city", lookup.getCity().getName()); } catch(UnknownHostException e) { log.error(e, "invalid ip [%s]", ipMatch.group()); } catch(IOException e) { log.error(e, "error looking up geo ip"); } catch(GeoIp2Exception e) { log.error(e, "error looking up geo ip"); } } dimensions.put("user", user); final String flags = m.group(2); dimensions.put("unpatrolled", Boolean.toString(flags.contains("!"))); dimensions.put("newPage", Boolean.toString(flags.contains("N"))); dimensions.put("robot", Boolean.toString(flags.contains("B"))); dimensions.put("anonymous", Boolean.toString(anonymous)); String[] parts = page.split(":"); if(parts.length > 1 && !parts[1].startsWith(" ")) { Map<String, String> channelNamespaces = namespaces.get(channel); if(channelNamespaces != null && channelNamespaces.containsKey(parts[0])) { dimensions.put("namespace", channelNamespaces.get(parts[0])); } else { dimensions.put("namespace", "wikipedia"); } } else { dimensions.put("namespace", "article"); } float delta = m.group(6) != null ? Float.parseFloat(m.group(6)) : 0; metrics.put("delta", delta); metrics.put("added", Math.max(delta, 0)); metrics.put("deleted", Math.min(delta, 0)); return new InputRow() { @Override public List<String> getDimensions() { return dimensionList; } @Override public long getTimestampFromEpoch() { return timestamp.getMillis(); } @Override public List<String> getDimension(String dimension) { return ImmutableList.of(dimensions.get(dimension)); } @Override public float getFloatMetric(String metric) { return metrics.get(metric); } @Override public String toString() { return "WikipediaRow{" + "timestamp=" + timestamp + ", dimensions=" + dimensions + ", metrics=" + metrics + '}'; } }; }
public InputRow decodeMessage(final DateTime timestamp, String channel, String msg) { final Map<String, String> dimensions = Maps.newHashMap(); final Map<String, Float> metrics = Maps.newHashMap(); Matcher m = pattern.matcher(msg); if(!m.matches()) { throw new IllegalArgumentException("Invalid input format"); } Matcher shortname = shortnamePattern.matcher(channel); if(shortname.matches()) { dimensions.put("language", shortname.group(1)); } String page = m.group(1); String pageUrl = page.replaceAll("\\s", "_"); dimensions.put("page", pageUrl); String user = m.group(4); Matcher ipMatch = ipPattern.matcher(user); boolean anonymous = ipMatch.matches(); if(anonymous) { try { final InetAddress ip = InetAddress.getByName(ipMatch.group()); final Omni lookup = geoLookup.omni(ip); dimensions.put("continent", lookup.getContinent().getName()); dimensions.put("country", lookup.getCountry().getName()); dimensions.put("region", lookup.getMostSpecificSubdivision().getName()); dimensions.put("city", lookup.getCity().getName()); } catch(UnknownHostException e) { log.error(e, "invalid ip [%s]", ipMatch.group()); } catch(IOException e) { log.error(e, "error looking up geo ip"); } catch(GeoIp2Exception e) { log.error(e, "error looking up geo ip"); } } dimensions.put("user", user); final String flags = m.group(2); dimensions.put("unpatrolled", Boolean.toString(flags.contains("!"))); dimensions.put("newPage", Boolean.toString(flags.contains("N"))); dimensions.put("robot", Boolean.toString(flags.contains("B"))); dimensions.put("anonymous", Boolean.toString(anonymous)); String[] parts = page.split(":"); if(parts.length > 1 && !parts[1].startsWith(" ")) { Map<String, String> channelNamespaces = namespaces.get(channel); if(channelNamespaces != null && channelNamespaces.containsKey(parts[0])) { dimensions.put("namespace", channelNamespaces.get(parts[0])); } else { dimensions.put("namespace", "wikipedia"); } } else { dimensions.put("namespace", "article"); } float delta = m.group(6) != null ? Float.parseFloat(m.group(6)) : 0; metrics.put("delta", delta); metrics.put("added", Math.max(delta, 0)); metrics.put("deleted", Math.min(delta, 0)); return new InputRow() { @Override public List<String> getDimensions() { return dimensionList; } @Override public long getTimestampFromEpoch() { return timestamp.getMillis(); } @Override public List<String> getDimension(String dimension) { final String value = dimensions.get(dimension); if(value != null) { return ImmutableList.of(value); } else { return ImmutableList.of(); } } @Override public float getFloatMetric(String metric) { return metrics.get(metric); } @Override public String toString() { return "WikipediaRow{" + "timestamp=" + timestamp + ", dimensions=" + dimensions + ", metrics=" + metrics + '}'; } }; }
diff --git a/src/no/runsafe/creativetoolbox/events/InteractEvents.java b/src/no/runsafe/creativetoolbox/events/InteractEvents.java index fc37772..d8d5963 100644 --- a/src/no/runsafe/creativetoolbox/events/InteractEvents.java +++ b/src/no/runsafe/creativetoolbox/events/InteractEvents.java @@ -1,137 +1,140 @@ package no.runsafe.creativetoolbox.events; import no.runsafe.creativetoolbox.PlotFilter; import no.runsafe.creativetoolbox.database.ApprovedPlotRepository; import no.runsafe.creativetoolbox.database.PlotApproval; import no.runsafe.framework.configuration.IConfiguration; import no.runsafe.framework.event.IAsyncEvent; import no.runsafe.framework.event.IConfigurationChanged; import no.runsafe.framework.event.player.IPlayerInteractEntityEvent; import no.runsafe.framework.event.player.IPlayerRightClickBlock; import no.runsafe.framework.server.RunsafeLocation; import no.runsafe.framework.server.RunsafeServer; import no.runsafe.framework.server.block.RunsafeBlock; import no.runsafe.framework.server.event.player.RunsafePlayerInteractEntityEvent; import no.runsafe.framework.server.item.RunsafeItemStack; import no.runsafe.framework.server.player.RunsafePlayer; import no.runsafe.worldguardbridge.WorldGuardInterface; import java.util.List; import java.util.Set; public class InteractEvents implements IPlayerRightClickBlock, IPlayerInteractEntityEvent, IConfigurationChanged, IAsyncEvent { public InteractEvents( PlotFilter plotFilter, WorldGuardInterface worldGuard, ApprovedPlotRepository plotRepository ) { this.worldGuardInterface = worldGuard; this.plotFilter = plotFilter; this.plotRepository = plotRepository; } @Override public boolean OnPlayerRightClick(RunsafePlayer player, RunsafeItemStack itemInHand, RunsafeBlock block) { if (itemInHand != null && itemInHand.getItemId() == listItem) { this.listPlotsByLocation(block.getLocation(), player); return false; } return true; } @Override public void OnPlayerInteractEntityEvent(RunsafePlayerInteractEntityEvent event) { if (event.getRightClicked() instanceof RunsafePlayer && event.getPlayer().hasPermission("runsafe.creative.list")) { if (event.getPlayer().getItemInHand() != null && event.getPlayer().getItemInHand().getItemId() == listItem) { this.listPlotsByPlayer((RunsafePlayer) event.getRightClicked(), event.getPlayer()); event.setCancelled(true); } } } @Override public void OnConfigurationChanged(IConfiguration configuration) { listItem = configuration.getConfigValueAsInt("list_item"); } private void listPlotsByPlayer(RunsafePlayer checkPlayer, RunsafePlayer triggerPlayer) { if (!this.worldGuardInterface.serverHasWorldGuard()) { triggerPlayer.sendMessage("Error: No WorldGuard installed."); return; } List<String> regions = plotFilter.apply(worldGuardInterface.getOwnedRegions(checkPlayer, checkPlayer.getWorld())); if (!regions.isEmpty()) for (String regionName : regions) this.listRegion(regionName, triggerPlayer, true); else if (triggerPlayer.hasPermission("runsafe.creative.list.showname")) triggerPlayer.sendMessage(String.format("%s does not own any regions.", checkPlayer.getPrettyName())); else triggerPlayer.sendMessage("No regions owned by this player."); } private void listPlotsByLocation(RunsafeLocation location, RunsafePlayer player) { if (!this.worldGuardInterface.serverHasWorldGuard()) { player.sendMessage("Error: No WorldGuard installed."); return; } List<String> regions = plotFilter.apply(worldGuardInterface.getRegionsAtLocation(location)); if (regions != null && !regions.isEmpty()) for (String regionName : regions) this.listRegion(regionName, player, false); else player.sendMessage("No regions found at this point."); } private void listRegion(String regionName, RunsafePlayer player, Boolean simple) { if (player.hasPermission("runsafe.creative.approval.read")) { PlotApproval approval = plotRepository.get(regionName); if (approval == null || approval.getApproved() == null) player.sendColouredMessage("Region: " + regionName); else player.sendColouredMessage("Region: %s [Approved %s]", regionName, approval.getApproved()); } else player.sendMessage("Region: " + regionName); if (!simple) { Set<String> owners = worldGuardInterface.getOwners(player.getWorld(), regionName); Set<String> members = worldGuardInterface.getMembers(player.getWorld(), regionName); for (String owner : owners) { RunsafePlayer theOwner = RunsafeServer.Instance.getPlayer(owner); player.sendColouredMessage(" Owner: " + theOwner.getPrettyName()); if (player.hasPermission("runsafe.creative.list.seen")) - player.sendColouredMessage(" " + theOwner.getLastSeen(player)); + { + String seen = theOwner.getLastSeen(player); + player.sendColouredMessage(" " + (seen == null ? "Player never seen" : seen)); + } } for (String member : members) player.sendColouredMessage(" Member: " + RunsafeServer.Instance.getPlayer(member).getPrettyName()); } } private final WorldGuardInterface worldGuardInterface; private int listItem; private final PlotFilter plotFilter; private final ApprovedPlotRepository plotRepository; }
true
true
private void listRegion(String regionName, RunsafePlayer player, Boolean simple) { if (player.hasPermission("runsafe.creative.approval.read")) { PlotApproval approval = plotRepository.get(regionName); if (approval == null || approval.getApproved() == null) player.sendColouredMessage("Region: " + regionName); else player.sendColouredMessage("Region: %s [Approved %s]", regionName, approval.getApproved()); } else player.sendMessage("Region: " + regionName); if (!simple) { Set<String> owners = worldGuardInterface.getOwners(player.getWorld(), regionName); Set<String> members = worldGuardInterface.getMembers(player.getWorld(), regionName); for (String owner : owners) { RunsafePlayer theOwner = RunsafeServer.Instance.getPlayer(owner); player.sendColouredMessage(" Owner: " + theOwner.getPrettyName()); if (player.hasPermission("runsafe.creative.list.seen")) player.sendColouredMessage(" " + theOwner.getLastSeen(player)); } for (String member : members) player.sendColouredMessage(" Member: " + RunsafeServer.Instance.getPlayer(member).getPrettyName()); } }
private void listRegion(String regionName, RunsafePlayer player, Boolean simple) { if (player.hasPermission("runsafe.creative.approval.read")) { PlotApproval approval = plotRepository.get(regionName); if (approval == null || approval.getApproved() == null) player.sendColouredMessage("Region: " + regionName); else player.sendColouredMessage("Region: %s [Approved %s]", regionName, approval.getApproved()); } else player.sendMessage("Region: " + regionName); if (!simple) { Set<String> owners = worldGuardInterface.getOwners(player.getWorld(), regionName); Set<String> members = worldGuardInterface.getMembers(player.getWorld(), regionName); for (String owner : owners) { RunsafePlayer theOwner = RunsafeServer.Instance.getPlayer(owner); player.sendColouredMessage(" Owner: " + theOwner.getPrettyName()); if (player.hasPermission("runsafe.creative.list.seen")) { String seen = theOwner.getLastSeen(player); player.sendColouredMessage(" " + (seen == null ? "Player never seen" : seen)); } } for (String member : members) player.sendColouredMessage(" Member: " + RunsafeServer.Instance.getPlayer(member).getPrettyName()); } }
diff --git a/src/com/oppian/oikos/util/DateFormatter.java b/src/com/oppian/oikos/util/DateFormatter.java index 95b73ba..134c0b1 100644 --- a/src/com/oppian/oikos/util/DateFormatter.java +++ b/src/com/oppian/oikos/util/DateFormatter.java @@ -1,26 +1,26 @@ package com.oppian.oikos.util; import java.util.Calendar; import java.util.Date; import android.text.format.DateFormat; public class DateFormatter { public static String formatToYesterdayOrToday(Date dateTime) { Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime); Calendar today = Calendar.getInstance(); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { return "Today"; } else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) { return "Yesterday"; } else { - return DateFormat.format("MMM d", yesterday).toString(); + return DateFormat.format("MMM d", dateTime).toString(); } } }
true
true
public static String formatToYesterdayOrToday(Date dateTime) { Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime); Calendar today = Calendar.getInstance(); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { return "Today"; } else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) { return "Yesterday"; } else { return DateFormat.format("MMM d", yesterday).toString(); } }
public static String formatToYesterdayOrToday(Date dateTime) { Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime); Calendar today = Calendar.getInstance(); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { return "Today"; } else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) { return "Yesterday"; } else { return DateFormat.format("MMM d", dateTime).toString(); } }
diff --git a/src/me/Kruithne/MinecartsMod/MMPoweredMinecart.java b/src/me/Kruithne/MinecartsMod/MMPoweredMinecart.java index fd284b3..b37feb2 100644 --- a/src/me/Kruithne/MinecartsMod/MMPoweredMinecart.java +++ b/src/me/Kruithne/MinecartsMod/MMPoweredMinecart.java @@ -1,72 +1,72 @@ package me.Kruithne.MinecartsMod; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.block.Block; import org.bukkit.entity.Minecart; import org.bukkit.entity.PoweredMinecart; import org.bukkit.util.Vector; public class MMPoweredMinecart { public PoweredMinecart cart; boolean powered = false; Server server; public MMPoweredMinecart(PoweredMinecart cart, Server server) { this.cart = cart; this.server = server; } public boolean isOnStraightRail() { Block blockBelow = this.cart.getLocation().getBlock(); if (blockBelow.getType() == Material.RAILS) { byte dataValue = blockBelow.getData(); if (dataValue == 0 || dataValue == 1) return true; } return false; } public boolean isOnSlopedRail() { Block blockBelow = this.cart.getLocation().getBlock(); if (blockBelow.getType() == Material.RAILS) { byte dataValue = blockBelow.getData(); if (dataValue == 2 || dataValue == 3 || dataValue == 4 || dataValue == 5) return true; } return false; } public boolean isPowered() { return this.powered; } public void gainSpeed(Double speed) { Vector direction = this.cart.getLocation().getDirection(); if (this.isOnSlopedRail() || this.isOnStraightRail()) { //this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") was on slope/straight, setting speed."); this.cart.setVelocity(new Vector(direction.getX() * speed, direction.getY(), direction.getZ() * speed)); } else { //this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") was not on valid track, MAKING IT SLOW."); this.cart.setVelocity(new Vector(direction.getX() * 0.1, direction.getY(), direction.getZ() * 0.1)); } this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") going in direction:"); this.server.broadcastMessage("X: " + direction.getX()); - this.server.broadcastMessage("|: " + direction.getZ()); + this.server.broadcastMessage("Z: " + direction.getZ()); } }
true
true
public void gainSpeed(Double speed) { Vector direction = this.cart.getLocation().getDirection(); if (this.isOnSlopedRail() || this.isOnStraightRail()) { //this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") was on slope/straight, setting speed."); this.cart.setVelocity(new Vector(direction.getX() * speed, direction.getY(), direction.getZ() * speed)); } else { //this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") was not on valid track, MAKING IT SLOW."); this.cart.setVelocity(new Vector(direction.getX() * 0.1, direction.getY(), direction.getZ() * 0.1)); } this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") going in direction:"); this.server.broadcastMessage("X: " + direction.getX()); this.server.broadcastMessage("|: " + direction.getZ()); }
public void gainSpeed(Double speed) { Vector direction = this.cart.getLocation().getDirection(); if (this.isOnSlopedRail() || this.isOnStraightRail()) { //this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") was on slope/straight, setting speed."); this.cart.setVelocity(new Vector(direction.getX() * speed, direction.getY(), direction.getZ() * speed)); } else { //this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") was not on valid track, MAKING IT SLOW."); this.cart.setVelocity(new Vector(direction.getX() * 0.1, direction.getY(), direction.getZ() * 0.1)); } this.server.broadcastMessage("Minecart (" + this.cart.getEntityId() + ") going in direction:"); this.server.broadcastMessage("X: " + direction.getX()); this.server.broadcastMessage("Z: " + direction.getZ()); }
diff --git a/site/src/main/java/org/soluvas/web/site/MultitenantPage.java b/site/src/main/java/org/soluvas/web/site/MultitenantPage.java index 65609fdc..310b2ea7 100644 --- a/site/src/main/java/org/soluvas/web/site/MultitenantPage.java +++ b/site/src/main/java/org/soluvas/web/site/MultitenantPage.java @@ -1,130 +1,132 @@ package org.soluvas.web.site; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.wicket.Application; import org.apache.wicket.markup.html.WebPage; import org.ops4j.pax.wicket.api.PaxWicketBean; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.soluvas.commons.tenant.TenantRef; import org.soluvas.web.site.osgi.WebTenantUtils; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; /** * Page supporting multi-tenant injection. * * The Wicket app's {@link Application#getApplicationKey()} must be {tenantId}_{tenantEnv}. * * @todo We can support Pax Wicket's PaxWicketBean "injectionSource" implementation. * @author ceefour */ @SuppressWarnings("serial") public class MultitenantPage extends WebPage { private transient Logger log = LoggerFactory .getLogger(MultitenantPage.class); @PaxWicketBean(name="blueprintBundleContext") private transient BundleContext bundleContext; /** * List of get-ed services (to unget). */ private transient final Map<Field, ServiceReference<?>> serviceRefs = new HashMap<Field, ServiceReference<?>>(); public MultitenantPage() { super(); getTenantServices(); } @Override protected void onAfterRender() { ungetTenantServices(); super.onAfterRender(); } @Override protected void finalize() throws Throwable { ungetTenantServices(); super.finalize(); } protected void getTenantServices() { TenantRef tenant = WebTenantUtils.getTenant(); final String tenantId = tenant.getTenantId(); final String tenantEnv = tenant.getTenantEnv(); Class<?> clazz = getClass(); List<Field> fields = new ArrayList<Field>(); while (clazz != null) { fields.addAll(ImmutableList.copyOf(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } for (Field field : fields) { TenantService tenantService = field.getAnnotation(TenantService.class); if (tenantService == null) continue; final String className = Strings.isNullOrEmpty(tenantService.objectClass()) ? field.getType().getName() : tenantService.objectClass(); final String namespace = tenantService.value(); final String additionalFilter = Optional.fromNullable(tenantService.filter()).or(""); log.trace("Lookup {} for tenantId={} tenantEnv={} namespace={} filter: {}", new Object[] { className, tenantId, tenantEnv, namespace, additionalFilter }); final String namespaceFilter = !Strings.isNullOrEmpty(namespace) ? "(namespace=" + namespace + ")" : ""; String filter = "(&(tenantId=" + tenantId + ")(tenantEnv=" + tenantEnv + ")" + namespaceFilter + additionalFilter + ")"; ServiceReference<?> serviceRef = null; try { ServiceReference<?>[] foundRefs = bundleContext .getServiceReferences(className, filter); if (foundRefs == null || foundRefs.length == 0) - throw new RuntimeException("Cannot find " + className + " service with filter " + filter); + throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + ", " + + className + " service with filter " + filter + " not found"); serviceRef = foundRefs[0]; } catch (InvalidSyntaxException e) { - throw new RuntimeException("Cannot find " + className + " service with filter " + filter, e); + throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + ", invalid " + + className + " service with filter " + filter, e); } Object bean = bundleContext.getService(serviceRef); serviceRefs.put(field, serviceRef); log.trace("Injecting {}#{} as {}", new Object[] { getPageClass().getName(), field.getName(), bean }); final boolean wasAccessible = field.isAccessible(); field.setAccessible(true); try { field.set(this, bean); } catch (Exception e) { log.error("Cannot inject " + getPageClass().getName() + "#" + field.getName() + " as " + bean, e); throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + " as " + bean, e); } finally { field.setAccessible(wasAccessible); } } } protected void ungetTenantServices() { for (Entry<Field, ServiceReference<?>> entry : serviceRefs.entrySet()) { final Field field = entry.getKey(); log.trace("Unsetting {}#{}", new Object[] { getPageClass().getName(), field.getName() }); final boolean wasAccessible = field.isAccessible(); field.setAccessible(true); try { field.set(this, null); } catch (Exception e) { log.warn("Cannot unset " + getPageClass().getName() + "." + field.getName(), e); } finally { field.setAccessible(wasAccessible); } bundleContext.ungetService(entry.getValue()); } serviceRefs.clear(); } }
false
true
protected void getTenantServices() { TenantRef tenant = WebTenantUtils.getTenant(); final String tenantId = tenant.getTenantId(); final String tenantEnv = tenant.getTenantEnv(); Class<?> clazz = getClass(); List<Field> fields = new ArrayList<Field>(); while (clazz != null) { fields.addAll(ImmutableList.copyOf(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } for (Field field : fields) { TenantService tenantService = field.getAnnotation(TenantService.class); if (tenantService == null) continue; final String className = Strings.isNullOrEmpty(tenantService.objectClass()) ? field.getType().getName() : tenantService.objectClass(); final String namespace = tenantService.value(); final String additionalFilter = Optional.fromNullable(tenantService.filter()).or(""); log.trace("Lookup {} for tenantId={} tenantEnv={} namespace={} filter: {}", new Object[] { className, tenantId, tenantEnv, namespace, additionalFilter }); final String namespaceFilter = !Strings.isNullOrEmpty(namespace) ? "(namespace=" + namespace + ")" : ""; String filter = "(&(tenantId=" + tenantId + ")(tenantEnv=" + tenantEnv + ")" + namespaceFilter + additionalFilter + ")"; ServiceReference<?> serviceRef = null; try { ServiceReference<?>[] foundRefs = bundleContext .getServiceReferences(className, filter); if (foundRefs == null || foundRefs.length == 0) throw new RuntimeException("Cannot find " + className + " service with filter " + filter); serviceRef = foundRefs[0]; } catch (InvalidSyntaxException e) { throw new RuntimeException("Cannot find " + className + " service with filter " + filter, e); } Object bean = bundleContext.getService(serviceRef); serviceRefs.put(field, serviceRef); log.trace("Injecting {}#{} as {}", new Object[] { getPageClass().getName(), field.getName(), bean }); final boolean wasAccessible = field.isAccessible(); field.setAccessible(true); try { field.set(this, bean); } catch (Exception e) { log.error("Cannot inject " + getPageClass().getName() + "#" + field.getName() + " as " + bean, e); throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + " as " + bean, e); } finally { field.setAccessible(wasAccessible); } } }
protected void getTenantServices() { TenantRef tenant = WebTenantUtils.getTenant(); final String tenantId = tenant.getTenantId(); final String tenantEnv = tenant.getTenantEnv(); Class<?> clazz = getClass(); List<Field> fields = new ArrayList<Field>(); while (clazz != null) { fields.addAll(ImmutableList.copyOf(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); } for (Field field : fields) { TenantService tenantService = field.getAnnotation(TenantService.class); if (tenantService == null) continue; final String className = Strings.isNullOrEmpty(tenantService.objectClass()) ? field.getType().getName() : tenantService.objectClass(); final String namespace = tenantService.value(); final String additionalFilter = Optional.fromNullable(tenantService.filter()).or(""); log.trace("Lookup {} for tenantId={} tenantEnv={} namespace={} filter: {}", new Object[] { className, tenantId, tenantEnv, namespace, additionalFilter }); final String namespaceFilter = !Strings.isNullOrEmpty(namespace) ? "(namespace=" + namespace + ")" : ""; String filter = "(&(tenantId=" + tenantId + ")(tenantEnv=" + tenantEnv + ")" + namespaceFilter + additionalFilter + ")"; ServiceReference<?> serviceRef = null; try { ServiceReference<?>[] foundRefs = bundleContext .getServiceReferences(className, filter); if (foundRefs == null || foundRefs.length == 0) throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + ", " + className + " service with filter " + filter + " not found"); serviceRef = foundRefs[0]; } catch (InvalidSyntaxException e) { throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + ", invalid " + className + " service with filter " + filter, e); } Object bean = bundleContext.getService(serviceRef); serviceRefs.put(field, serviceRef); log.trace("Injecting {}#{} as {}", new Object[] { getPageClass().getName(), field.getName(), bean }); final boolean wasAccessible = field.isAccessible(); field.setAccessible(true); try { field.set(this, bean); } catch (Exception e) { log.error("Cannot inject " + getPageClass().getName() + "#" + field.getName() + " as " + bean, e); throw new RuntimeException("Cannot inject " + getPageClass().getName() + "#" + field.getName() + " as " + bean, e); } finally { field.setAccessible(wasAccessible); } } }
diff --git a/src/com/quicinc/fmradio/FMTransmitterConfigReceiver.java b/src/com/quicinc/fmradio/FMTransmitterConfigReceiver.java index f08fd57..eb63bb1 100644 --- a/src/com/quicinc/fmradio/FMTransmitterConfigReceiver.java +++ b/src/com/quicinc/fmradio/FMTransmitterConfigReceiver.java @@ -1,81 +1,81 @@ /* * Copyright (c) 2011, Code Aurora Forum. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Code Aurora nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.quicinc.fmradio; import android.content.Intent; import android.content.BroadcastReceiver; import android.content.pm.PackageManager; import android.content.Context; import android.content.ComponentName; import android.util.Log; import android.os.SystemProperties; import java.io.FileReader; import java.lang.String; public class FMTransmitterConfigReceiver extends BroadcastReceiver { private static FileReader socinfo_fd; private static char[] socinfo = new char[20]; private static String build_id = "1"; private static final String TAG = "FMFolderConfigReceiver"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "Received intent: " + action); if((action != null) && action.equals("android.intent.action.BOOT_COMPLETED")) { Log.d(TAG, "boot complete intent received"); boolean isFmTransmitterSupported = SystemProperties.getBoolean("ro.fm.transmitter",true); - if ("msm7630_surf".equals(SystemProperties.get("ro.product.device"))) { + if ("msm7630_surf".equals(SystemProperties.get("ro.board.platform"))) { Log.d(TAG,"this is msm7630_surf"); try { socinfo_fd = new FileReader("/sys/devices/system/soc/soc0/build_id"); socinfo_fd.read(socinfo,0,20); socinfo_fd.close(); } catch(Exception e) { Log.e(TAG,"Exception in FileReader"); } Log.d(TAG, "socinfo=" +socinfo); build_id = new String(socinfo,17,1); Log.d(TAG, "build_id=" +build_id); } if ((!isFmTransmitterSupported) || (build_id.equals("0"))) { PackageManager pManager = context.getPackageManager(); if (pManager != null) { Log.d(TAG, "disableing the FM Transmitter"); ComponentName fmTransmitter = new ComponentName("com.quicinc.fmradio", "com.quicinc.fmradio.FMTransmitterActivity"); pManager.setComponentEnabledSetting(fmTransmitter, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } } } }
true
true
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "Received intent: " + action); if((action != null) && action.equals("android.intent.action.BOOT_COMPLETED")) { Log.d(TAG, "boot complete intent received"); boolean isFmTransmitterSupported = SystemProperties.getBoolean("ro.fm.transmitter",true); if ("msm7630_surf".equals(SystemProperties.get("ro.product.device"))) { Log.d(TAG,"this is msm7630_surf"); try { socinfo_fd = new FileReader("/sys/devices/system/soc/soc0/build_id"); socinfo_fd.read(socinfo,0,20); socinfo_fd.close(); } catch(Exception e) { Log.e(TAG,"Exception in FileReader"); } Log.d(TAG, "socinfo=" +socinfo); build_id = new String(socinfo,17,1); Log.d(TAG, "build_id=" +build_id); } if ((!isFmTransmitterSupported) || (build_id.equals("0"))) { PackageManager pManager = context.getPackageManager(); if (pManager != null) { Log.d(TAG, "disableing the FM Transmitter"); ComponentName fmTransmitter = new ComponentName("com.quicinc.fmradio", "com.quicinc.fmradio.FMTransmitterActivity"); pManager.setComponentEnabledSetting(fmTransmitter, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } } }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "Received intent: " + action); if((action != null) && action.equals("android.intent.action.BOOT_COMPLETED")) { Log.d(TAG, "boot complete intent received"); boolean isFmTransmitterSupported = SystemProperties.getBoolean("ro.fm.transmitter",true); if ("msm7630_surf".equals(SystemProperties.get("ro.board.platform"))) { Log.d(TAG,"this is msm7630_surf"); try { socinfo_fd = new FileReader("/sys/devices/system/soc/soc0/build_id"); socinfo_fd.read(socinfo,0,20); socinfo_fd.close(); } catch(Exception e) { Log.e(TAG,"Exception in FileReader"); } Log.d(TAG, "socinfo=" +socinfo); build_id = new String(socinfo,17,1); Log.d(TAG, "build_id=" +build_id); } if ((!isFmTransmitterSupported) || (build_id.equals("0"))) { PackageManager pManager = context.getPackageManager(); if (pManager != null) { Log.d(TAG, "disableing the FM Transmitter"); ComponentName fmTransmitter = new ComponentName("com.quicinc.fmradio", "com.quicinc.fmradio.FMTransmitterActivity"); pManager.setComponentEnabledSetting(fmTransmitter, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } } } }
diff --git a/src/com/palmergames/bukkit/TownyChat/Command/JoinCommand.java b/src/com/palmergames/bukkit/TownyChat/Command/JoinCommand.java index 6505545..ea3a17f 100644 --- a/src/com/palmergames/bukkit/TownyChat/Command/JoinCommand.java +++ b/src/com/palmergames/bukkit/TownyChat/Command/JoinCommand.java @@ -1,84 +1,84 @@ package com.palmergames.bukkit.TownyChat.Command; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.palmergames.bukkit.TownyChat.Chat; import com.palmergames.bukkit.TownyChat.channels.Channel; import com.palmergames.bukkit.towny.TownyMessaging; import com.palmergames.bukkit.towny.object.TownyUniverse; public class JoinCommand implements CommandExecutor { Chat plugin = null; public JoinCommand(Chat instance) { this.plugin = instance; } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If not our command if ((!label.equalsIgnoreCase("join") || args.length != 1) && (!label.equalsIgnoreCase("ch") || args.length != 2 || !args[0].equalsIgnoreCase("join"))) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] Error: Invalid command!"); return false; } if (!(sender instanceof Player)) { return false; // Don't think it can happen but ... } Player player = ((Player)sender); String name = null; - if (label.equalsIgnoreCase("leave")){ + if (label.equalsIgnoreCase("join")){ name = args[0]; } else { name = args[1]; } Channel chan = plugin.getChannelsHandler().getChannel(name); // If we can't find the channel by name, look up all the channel commands for an alias if (chan == null) { for(Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) { for (String command : chan2.getCommands()) { if (command.equalsIgnoreCase(name)) { chan = chan2; break; } } if (chan != null) { break; } } } if (chan == null) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] There is no channel called &f" + name); return true; } // You can join if: // - Towny doesn't recognize your permissions plugin // - channel has no permission set OR [by default they don't] // - channel has permission set AND: // - player has channel permission String joinPerm = chan.getPermission(); if ((joinPerm != null && (plugin.getTowny().isPermissions() && !TownyUniverse.getPermissionSource().has(player, joinPerm)))) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] You cannot join &f" + chan.getName()); return true; } if (!chan.join(sender.getName())){ TownyMessaging.sendMsg(sender, "[TownyChat] You are already in &f" + chan.getName()); return true; } TownyMessaging.sendMsg(sender, "[TownyChat] You joined &f" + chan.getName()); return true; } }
true
true
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If not our command if ((!label.equalsIgnoreCase("join") || args.length != 1) && (!label.equalsIgnoreCase("ch") || args.length != 2 || !args[0].equalsIgnoreCase("join"))) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] Error: Invalid command!"); return false; } if (!(sender instanceof Player)) { return false; // Don't think it can happen but ... } Player player = ((Player)sender); String name = null; if (label.equalsIgnoreCase("leave")){ name = args[0]; } else { name = args[1]; } Channel chan = plugin.getChannelsHandler().getChannel(name); // If we can't find the channel by name, look up all the channel commands for an alias if (chan == null) { for(Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) { for (String command : chan2.getCommands()) { if (command.equalsIgnoreCase(name)) { chan = chan2; break; } } if (chan != null) { break; } } } if (chan == null) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] There is no channel called &f" + name); return true; } // You can join if: // - Towny doesn't recognize your permissions plugin // - channel has no permission set OR [by default they don't] // - channel has permission set AND: // - player has channel permission String joinPerm = chan.getPermission(); if ((joinPerm != null && (plugin.getTowny().isPermissions() && !TownyUniverse.getPermissionSource().has(player, joinPerm)))) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] You cannot join &f" + chan.getName()); return true; } if (!chan.join(sender.getName())){ TownyMessaging.sendMsg(sender, "[TownyChat] You are already in &f" + chan.getName()); return true; } TownyMessaging.sendMsg(sender, "[TownyChat] You joined &f" + chan.getName()); return true; }
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { // If not our command if ((!label.equalsIgnoreCase("join") || args.length != 1) && (!label.equalsIgnoreCase("ch") || args.length != 2 || !args[0].equalsIgnoreCase("join"))) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] Error: Invalid command!"); return false; } if (!(sender instanceof Player)) { return false; // Don't think it can happen but ... } Player player = ((Player)sender); String name = null; if (label.equalsIgnoreCase("join")){ name = args[0]; } else { name = args[1]; } Channel chan = plugin.getChannelsHandler().getChannel(name); // If we can't find the channel by name, look up all the channel commands for an alias if (chan == null) { for(Channel chan2 : plugin.getChannelsHandler().getAllChannels().values()) { for (String command : chan2.getCommands()) { if (command.equalsIgnoreCase(name)) { chan = chan2; break; } } if (chan != null) { break; } } } if (chan == null) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] There is no channel called &f" + name); return true; } // You can join if: // - Towny doesn't recognize your permissions plugin // - channel has no permission set OR [by default they don't] // - channel has permission set AND: // - player has channel permission String joinPerm = chan.getPermission(); if ((joinPerm != null && (plugin.getTowny().isPermissions() && !TownyUniverse.getPermissionSource().has(player, joinPerm)))) { TownyMessaging.sendErrorMsg(sender, "[TownyChat] You cannot join &f" + chan.getName()); return true; } if (!chan.join(sender.getName())){ TownyMessaging.sendMsg(sender, "[TownyChat] You are already in &f" + chan.getName()); return true; } TownyMessaging.sendMsg(sender, "[TownyChat] You joined &f" + chan.getName()); return true; }
diff --git a/src/org/openstreetmap/josm/gui/layer/markerlayer/ButtonMarker.java b/src/org/openstreetmap/josm/gui/layer/markerlayer/ButtonMarker.java index 090716aa..bc3f6486 100644 --- a/src/org/openstreetmap/josm/gui/layer/markerlayer/ButtonMarker.java +++ b/src/org/openstreetmap/josm/gui/layer/markerlayer/ButtonMarker.java @@ -1,67 +1,67 @@ // License: GPL. Copyright 2007 by Immanuel Scholz and others package org.openstreetmap.josm.gui.layer.markerlayer; import java.awt.Graphics; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import javax.swing.BorderFactory; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import org.openstreetmap.josm.Main; import org.openstreetmap.josm.data.coor.LatLon; import org.openstreetmap.josm.gui.MapView; /** * Marker class with button look-and-feel. * * @author Frederik Ramm <[email protected]> * */ public class ButtonMarker extends Marker { private Rectangle buttonRectangle; public ButtonMarker(LatLon ll, String buttonImage, MarkerLayer parentLayer, double time, double offset) { super(ll, null, buttonImage, parentLayer, time, offset); buttonRectangle = new Rectangle(0, 0, symbol.getIconWidth(), symbol.getIconHeight()); } public ButtonMarker(LatLon ll, String text, String buttonImage, MarkerLayer parentLayer, double time, double offset) { super(ll, text, buttonImage, parentLayer, time, offset); buttonRectangle = new Rectangle(0, 0, symbol.getIconWidth(), symbol.getIconHeight()); } @Override public boolean containsPoint(Point p) { Point screen = Main.map.mapView.getPoint(getEastNorth()); buttonRectangle.setLocation(screen.x+4, screen.y+2); return buttonRectangle.contains(p); } @Override public void paint(Graphics g, MapView mv, boolean mousePressed, String show) { if (! show.equalsIgnoreCase("show")) { super.paint(g, mv, mousePressed, show); return; } Point screen = mv.getPoint(getEastNorth()); buttonRectangle.setLocation(screen.x+4, screen.y+2); symbol.paintIcon(mv, g, screen.x+4, screen.y+2); Border b; Point mousePosition = mv.getMousePosition(); // mouse is inside the window - if (mousePosition != null && mousePressed) { + if (mousePosition != null && mousePressed && containsPoint(mousePosition)) { b = BorderFactory.createBevelBorder(BevelBorder.LOWERED); } else { b = BorderFactory.createBevelBorder(BevelBorder.RAISED); } Insets inset = b.getBorderInsets(mv); Rectangle r = new Rectangle(buttonRectangle); r.grow((inset.top+inset.bottom)/2, (inset.left+inset.right)/2); b.paintBorder(mv, g, r.x, r.y, r.width, r.height); if ((text != null) && (show.equalsIgnoreCase("show")) && Main.pref.getBoolean("marker.buttonlabels", true)) g.drawString(text, screen.x+4, screen.y+2); } }
true
true
@Override public void paint(Graphics g, MapView mv, boolean mousePressed, String show) { if (! show.equalsIgnoreCase("show")) { super.paint(g, mv, mousePressed, show); return; } Point screen = mv.getPoint(getEastNorth()); buttonRectangle.setLocation(screen.x+4, screen.y+2); symbol.paintIcon(mv, g, screen.x+4, screen.y+2); Border b; Point mousePosition = mv.getMousePosition(); // mouse is inside the window if (mousePosition != null && mousePressed) { b = BorderFactory.createBevelBorder(BevelBorder.LOWERED); } else { b = BorderFactory.createBevelBorder(BevelBorder.RAISED); } Insets inset = b.getBorderInsets(mv); Rectangle r = new Rectangle(buttonRectangle); r.grow((inset.top+inset.bottom)/2, (inset.left+inset.right)/2); b.paintBorder(mv, g, r.x, r.y, r.width, r.height); if ((text != null) && (show.equalsIgnoreCase("show")) && Main.pref.getBoolean("marker.buttonlabels", true)) g.drawString(text, screen.x+4, screen.y+2); }
@Override public void paint(Graphics g, MapView mv, boolean mousePressed, String show) { if (! show.equalsIgnoreCase("show")) { super.paint(g, mv, mousePressed, show); return; } Point screen = mv.getPoint(getEastNorth()); buttonRectangle.setLocation(screen.x+4, screen.y+2); symbol.paintIcon(mv, g, screen.x+4, screen.y+2); Border b; Point mousePosition = mv.getMousePosition(); // mouse is inside the window if (mousePosition != null && mousePressed && containsPoint(mousePosition)) { b = BorderFactory.createBevelBorder(BevelBorder.LOWERED); } else { b = BorderFactory.createBevelBorder(BevelBorder.RAISED); } Insets inset = b.getBorderInsets(mv); Rectangle r = new Rectangle(buttonRectangle); r.grow((inset.top+inset.bottom)/2, (inset.left+inset.right)/2); b.paintBorder(mv, g, r.x, r.y, r.width, r.height); if ((text != null) && (show.equalsIgnoreCase("show")) && Main.pref.getBoolean("marker.buttonlabels", true)) g.drawString(text, screen.x+4, screen.y+2); }
diff --git a/aa-server/src/main/java/edu/umich/eecs/tac/is/TACAAResultManager.java b/aa-server/src/main/java/edu/umich/eecs/tac/is/TACAAResultManager.java index ff67595..eb78cf7 100644 --- a/aa-server/src/main/java/edu/umich/eecs/tac/is/TACAAResultManager.java +++ b/aa-server/src/main/java/edu/umich/eecs/tac/is/TACAAResultManager.java @@ -1,274 +1,274 @@ package edu.umich.eecs.tac.is; /** * @author Patrick Jordan, Lee Callender */ import se.sics.tasim.is.common.ResultManager; import se.sics.tasim.is.common.InfoServer; import se.sics.tasim.logtool.LogReader; import se.sics.tasim.logtool.ParticipantInfo; import se.sics.isl.util.FormatUtils; import java.io.IOException; import java.io.FileWriter; import java.util.logging.Logger; import java.util.Arrays; import com.botbox.html.HtmlWriter; import com.botbox.html.HtmlUtils; import edu.umich.eecs.tac.props.AAInfo; import edu.umich.eecs.tac.TACAAConstants; import edu.umich.eecs.tac.Participant; import edu.umich.eecs.tac.TACAASimulationInfo; //TODO-WRITE THIS CLASS public class TACAAResultManager extends ResultManager { private static final Logger log = Logger.getLogger(TACAAResultManager.class.getName()); private static final String POSITIVE_PARTICIPANT_COLOR = "#0000c0"; private static final String NEUTRAL_PARTICIPANT_COLOR = null; private static final String NEGATIVE_PARTICIPANT_COLOR = "#c00000"; public TACAAResultManager() { } protected void generateResult() throws IOException { TACAASimulationInfo simInfo; LogReader reader = getLogReader(); int simulationID = reader.getSimulationID(); String serverName = reader.getServerName(); reader.setContext(new AAInfo().createContext()); try { simInfo = new TACAASimulationInfo(reader); } catch (Exception e) { throw (IOException) new IOException("could not parse simulation log " + simulationID) .initCause(e); } // go through the whole logfile and find the scores of the agents... String destinationFile = getDestinationPath() + "index.html"; log.info("generating results for simulation " + simulationID + " to " + destinationFile); HtmlWriter html = new HtmlWriter(new FileWriter(destinationFile)); Participant[] participants = simInfo.getParticipantsByRole(TACAAConstants.ADVERTISER); if (participants != null) { participants = participants.clone(); Arrays.sort(participants, Participant.getResultComparator()); } html.pageStart("Results for game " + simulationID + '@' + serverName); html.h3("Result for game " + simulationID + '@' + serverName + " played at " // Should not access InfoServer! FIX THIS!!! + InfoServer.getServerTimeAsString(reader.getStartTime())); html.table("border=1").colgroup(1).colgroup(11, "align=right").tr() .th("Player") .th("Revenue", "align=center") .th("Cost", "align=center") .th("Impressions", "align=center") .th("Clicks", "align=center") .th("Conversions", "align=center") .th("CTR", "align=center") .th("CPM", "align=center") .th("CPC", "align=center") .th("VPC", "align=center") .th("ROI", "align=center") .th("Result", "align=center"); ParticipantInfo[] agentInfos = null; String[] agentColors = null; double[] agentScores = null; if (participants != null) { agentInfos = new ParticipantInfo[participants.length]; agentColors = new String[participants.length]; agentScores = new double[participants.length]; for (int i = 0, n = participants.length; i < n; i++) { Participant player = participants[i]; ParticipantInfo agentInfo = player.getInfo(); String name = agentInfo.getName(); double cost = player.getCost(); double revenue = player.getRevenue(); double result = player.getResult(); long impressions = player.getImpressions(); long clicks = player.getClicks(); - long conversions = player.getClicks(); + long conversions = player.getConversions(); double roi = player.getROI(); double cpc = player.getCPC(); double ctr = player.getCTR(); double cpm = player.getCPI() * 1000.0; double vpc = player.getValuePerClick(); agentInfos[i] = agentInfo; if (result < 0) { agentColors[i] = NEGATIVE_PARTICIPANT_COLOR; } else if (result > 0) { agentColors[i] = POSITIVE_PARTICIPANT_COLOR; } else { agentColors[i] = NEUTRAL_PARTICIPANT_COLOR; } agentScores[i] = result; html.tr().td(agentInfo.isBuiltinAgent() ? "<em>" + name + "</em>" : name) .td(getAmountAsString(revenue)) .td(getAmountAsString(cost)) .td(getAmountAsString(impressions)) .td(getAmountAsString(clicks)) .td(getAmountAsString(conversions)); if(!Double.isNaN(ctr)) { html.td(getAmountAsString(ctr * 100)).text(" %"); } else { html.td("0"); } if(!Double.isNaN(cpm)) { html.td(getAmountAsString(ctr)); } else { html.td("0"); } if(!Double.isNaN(cpc)) { html.td(getAmountAsString(cpc)); } else { html.td("0"); } if(!Double.isNaN(vpc)) { html.td(); formatAmount(html,vpc); } else { html.td("0"); } if(!Double.isNaN(roi)) { html.td(); formatAmount(html, roi * 100, " %"); } else { html.td("0"); } html.td(); formatAmount(html, result); } } html.tableEnd(); html.text("Download game data ").tag('a').attr("href", getGameLogName()).text("here").tagEnd('a').p(); /*html.table("border=1").colgroup(1).colgroup(2, "align=right").colgroup(2).colgroup(1, "align=right").tr().th("Player").th("Orders", "align=center").th("Utilization", "align=center").th("Deliveries (on&nbsp;time/late/missed)", "colspan=2").th("DPerf", "align=center"); if (participants != null) { for (int i = 0, n = participants.length; i < n; i++) { Participant player = participants[i]; ParticipantInfo agentInfo = player.getInfo(); String name = agentInfo.getName(); int orders = player.getCustomerOrders(); int deliveries = player.getCustomerDeliveries(); html.tr().td(agentInfo.isBuiltinAgent() ? "<em>" + name + "</em>" : name).td("" + orders) .td("" + player.getAverageUtilization()).text('%').td(); if (orders > 0) { int lateDeliveries = player.getCustomerLateDeliveries(); int missedDeliveries = player.getCustomerMissedDeliveries(); int onTime = (int) (100d * (deliveries - lateDeliveries) / orders + 0.5); int late = (int) (100d * lateDeliveries / orders + 0.5); int missed = (int) (100d * missedDeliveries / orders + 0.5); HtmlUtils.progress(html, 100, 8, onTime, late, missed); html.td().text(deliveries - lateDeliveries).text("&nbsp;/&nbsp;").text(lateDeliveries) .text("&nbsp;/&nbsp;").text(missedDeliveries); html.td("" + onTime + '%'); // html.td().text(onTime).text("%&nbsp;/&nbsp;") // .text(late).text("%&nbsp;/&nbsp;") // .text(missed).text('%'); } else { html.text("&nbsp;").td("&nbsp;").td("0%"); } } } html.tableEnd(); */ html.p(); /*html.table("border=1").tr().th("Simulation Parameters", "colspan=2").tr().td("Simulation:").td( "" + simulationID + " (" + simInfo.getSimulationType() + ')').tr().td("Server:").td( serverName + " (" + simInfo.getServerVersion() + ')'); // ServerConfig sConfig = simInfo.getServerConfig(); // if (sConfig != null) { // } int bankDebtInterestRate = simInfo.getBankDebtInterestRate(); int bankDepositInterestRate = simInfo.getBankDepositInterestRate(); if (bankDepositInterestRate >= 0 && bankDebtInterestRate >= 0) { html.tr().td("Bank interest (debt/deposit):").td( "" + bankDebtInterestRate + "% / " + bankDepositInterestRate + '%'); } int storageCost = simInfo.getStorageCost(); if (storageCost >= 0) { html.tr().td("Storage Cost:").td("" + storageCost + '%'); } html.tableEnd();*/ html.p().tag("hr"); html.pageEnd(); html.close(); addSimulationToHistory(agentInfos, agentColors); addSimulationResult(agentInfos, agentScores); } private String getAmountAsString(double amount) { return FormatUtils.formatDouble(amount, "&nbsp;"); // String text = Long.toString(amount); // int length = text.length(); // if (length > 3) { // StringBuffer sb = new StringBuffer(); // int pos = 0; // int part = length % 3; // if (part > 0) { // sb.append(text.substring(0, part)); // pos += part; // } // while (pos < length) { // if (pos > 1 || (pos == 1 && text.charAt(0) != '-')) { // sb.append("&nbsp;"); // } // sb.append(text.substring(pos, pos + 3)); // pos += 3; // } // text = sb.toString(); // } // return text; } private void formatAmount(HtmlWriter html, double amount) { formatAmount(html, amount, ""); } private void formatAmount(HtmlWriter html, double amount, String postfix) { if (amount < 0) { html.tag("font", "color=red").text(getAmountAsString(amount)).text(postfix).tagEnd("font"); } else { html.text(getAmountAsString(amount)).text(postfix); } } }
true
true
protected void generateResult() throws IOException { TACAASimulationInfo simInfo; LogReader reader = getLogReader(); int simulationID = reader.getSimulationID(); String serverName = reader.getServerName(); reader.setContext(new AAInfo().createContext()); try { simInfo = new TACAASimulationInfo(reader); } catch (Exception e) { throw (IOException) new IOException("could not parse simulation log " + simulationID) .initCause(e); } // go through the whole logfile and find the scores of the agents... String destinationFile = getDestinationPath() + "index.html"; log.info("generating results for simulation " + simulationID + " to " + destinationFile); HtmlWriter html = new HtmlWriter(new FileWriter(destinationFile)); Participant[] participants = simInfo.getParticipantsByRole(TACAAConstants.ADVERTISER); if (participants != null) { participants = participants.clone(); Arrays.sort(participants, Participant.getResultComparator()); } html.pageStart("Results for game " + simulationID + '@' + serverName); html.h3("Result for game " + simulationID + '@' + serverName + " played at " // Should not access InfoServer! FIX THIS!!! + InfoServer.getServerTimeAsString(reader.getStartTime())); html.table("border=1").colgroup(1).colgroup(11, "align=right").tr() .th("Player") .th("Revenue", "align=center") .th("Cost", "align=center") .th("Impressions", "align=center") .th("Clicks", "align=center") .th("Conversions", "align=center") .th("CTR", "align=center") .th("CPM", "align=center") .th("CPC", "align=center") .th("VPC", "align=center") .th("ROI", "align=center") .th("Result", "align=center"); ParticipantInfo[] agentInfos = null; String[] agentColors = null; double[] agentScores = null; if (participants != null) { agentInfos = new ParticipantInfo[participants.length]; agentColors = new String[participants.length]; agentScores = new double[participants.length]; for (int i = 0, n = participants.length; i < n; i++) { Participant player = participants[i]; ParticipantInfo agentInfo = player.getInfo(); String name = agentInfo.getName(); double cost = player.getCost(); double revenue = player.getRevenue(); double result = player.getResult(); long impressions = player.getImpressions(); long clicks = player.getClicks(); long conversions = player.getClicks(); double roi = player.getROI(); double cpc = player.getCPC(); double ctr = player.getCTR(); double cpm = player.getCPI() * 1000.0; double vpc = player.getValuePerClick(); agentInfos[i] = agentInfo; if (result < 0) { agentColors[i] = NEGATIVE_PARTICIPANT_COLOR; } else if (result > 0) { agentColors[i] = POSITIVE_PARTICIPANT_COLOR; } else { agentColors[i] = NEUTRAL_PARTICIPANT_COLOR; } agentScores[i] = result; html.tr().td(agentInfo.isBuiltinAgent() ? "<em>" + name + "</em>" : name) .td(getAmountAsString(revenue)) .td(getAmountAsString(cost)) .td(getAmountAsString(impressions)) .td(getAmountAsString(clicks)) .td(getAmountAsString(conversions)); if(!Double.isNaN(ctr)) { html.td(getAmountAsString(ctr * 100)).text(" %"); } else { html.td("0"); } if(!Double.isNaN(cpm)) { html.td(getAmountAsString(ctr)); } else { html.td("0"); } if(!Double.isNaN(cpc)) { html.td(getAmountAsString(cpc)); } else { html.td("0"); } if(!Double.isNaN(vpc)) { html.td(); formatAmount(html,vpc); } else { html.td("0"); } if(!Double.isNaN(roi)) { html.td(); formatAmount(html, roi * 100, " %"); } else { html.td("0"); } html.td(); formatAmount(html, result); } } html.tableEnd(); html.text("Download game data ").tag('a').attr("href", getGameLogName()).text("here").tagEnd('a').p(); /*html.table("border=1").colgroup(1).colgroup(2, "align=right").colgroup(2).colgroup(1, "align=right").tr().th("Player").th("Orders", "align=center").th("Utilization", "align=center").th("Deliveries (on&nbsp;time/late/missed)", "colspan=2").th("DPerf", "align=center"); if (participants != null) { for (int i = 0, n = participants.length; i < n; i++) { Participant player = participants[i]; ParticipantInfo agentInfo = player.getInfo(); String name = agentInfo.getName(); int orders = player.getCustomerOrders(); int deliveries = player.getCustomerDeliveries(); html.tr().td(agentInfo.isBuiltinAgent() ? "<em>" + name + "</em>" : name).td("" + orders) .td("" + player.getAverageUtilization()).text('%').td(); if (orders > 0) { int lateDeliveries = player.getCustomerLateDeliveries(); int missedDeliveries = player.getCustomerMissedDeliveries(); int onTime = (int) (100d * (deliveries - lateDeliveries) / orders + 0.5); int late = (int) (100d * lateDeliveries / orders + 0.5); int missed = (int) (100d * missedDeliveries / orders + 0.5); HtmlUtils.progress(html, 100, 8, onTime, late, missed); html.td().text(deliveries - lateDeliveries).text("&nbsp;/&nbsp;").text(lateDeliveries) .text("&nbsp;/&nbsp;").text(missedDeliveries); html.td("" + onTime + '%'); // html.td().text(onTime).text("%&nbsp;/&nbsp;") // .text(late).text("%&nbsp;/&nbsp;") // .text(missed).text('%'); } else { html.text("&nbsp;").td("&nbsp;").td("0%"); } } } html.tableEnd(); */ html.p(); /*html.table("border=1").tr().th("Simulation Parameters", "colspan=2").tr().td("Simulation:").td( "" + simulationID + " (" + simInfo.getSimulationType() + ')').tr().td("Server:").td( serverName + " (" + simInfo.getServerVersion() + ')'); // ServerConfig sConfig = simInfo.getServerConfig(); // if (sConfig != null) { // } int bankDebtInterestRate = simInfo.getBankDebtInterestRate(); int bankDepositInterestRate = simInfo.getBankDepositInterestRate(); if (bankDepositInterestRate >= 0 && bankDebtInterestRate >= 0) { html.tr().td("Bank interest (debt/deposit):").td( "" + bankDebtInterestRate + "% / " + bankDepositInterestRate + '%'); } int storageCost = simInfo.getStorageCost(); if (storageCost >= 0) { html.tr().td("Storage Cost:").td("" + storageCost + '%'); } html.tableEnd();*/ html.p().tag("hr"); html.pageEnd(); html.close(); addSimulationToHistory(agentInfos, agentColors); addSimulationResult(agentInfos, agentScores); }
protected void generateResult() throws IOException { TACAASimulationInfo simInfo; LogReader reader = getLogReader(); int simulationID = reader.getSimulationID(); String serverName = reader.getServerName(); reader.setContext(new AAInfo().createContext()); try { simInfo = new TACAASimulationInfo(reader); } catch (Exception e) { throw (IOException) new IOException("could not parse simulation log " + simulationID) .initCause(e); } // go through the whole logfile and find the scores of the agents... String destinationFile = getDestinationPath() + "index.html"; log.info("generating results for simulation " + simulationID + " to " + destinationFile); HtmlWriter html = new HtmlWriter(new FileWriter(destinationFile)); Participant[] participants = simInfo.getParticipantsByRole(TACAAConstants.ADVERTISER); if (participants != null) { participants = participants.clone(); Arrays.sort(participants, Participant.getResultComparator()); } html.pageStart("Results for game " + simulationID + '@' + serverName); html.h3("Result for game " + simulationID + '@' + serverName + " played at " // Should not access InfoServer! FIX THIS!!! + InfoServer.getServerTimeAsString(reader.getStartTime())); html.table("border=1").colgroup(1).colgroup(11, "align=right").tr() .th("Player") .th("Revenue", "align=center") .th("Cost", "align=center") .th("Impressions", "align=center") .th("Clicks", "align=center") .th("Conversions", "align=center") .th("CTR", "align=center") .th("CPM", "align=center") .th("CPC", "align=center") .th("VPC", "align=center") .th("ROI", "align=center") .th("Result", "align=center"); ParticipantInfo[] agentInfos = null; String[] agentColors = null; double[] agentScores = null; if (participants != null) { agentInfos = new ParticipantInfo[participants.length]; agentColors = new String[participants.length]; agentScores = new double[participants.length]; for (int i = 0, n = participants.length; i < n; i++) { Participant player = participants[i]; ParticipantInfo agentInfo = player.getInfo(); String name = agentInfo.getName(); double cost = player.getCost(); double revenue = player.getRevenue(); double result = player.getResult(); long impressions = player.getImpressions(); long clicks = player.getClicks(); long conversions = player.getConversions(); double roi = player.getROI(); double cpc = player.getCPC(); double ctr = player.getCTR(); double cpm = player.getCPI() * 1000.0; double vpc = player.getValuePerClick(); agentInfos[i] = agentInfo; if (result < 0) { agentColors[i] = NEGATIVE_PARTICIPANT_COLOR; } else if (result > 0) { agentColors[i] = POSITIVE_PARTICIPANT_COLOR; } else { agentColors[i] = NEUTRAL_PARTICIPANT_COLOR; } agentScores[i] = result; html.tr().td(agentInfo.isBuiltinAgent() ? "<em>" + name + "</em>" : name) .td(getAmountAsString(revenue)) .td(getAmountAsString(cost)) .td(getAmountAsString(impressions)) .td(getAmountAsString(clicks)) .td(getAmountAsString(conversions)); if(!Double.isNaN(ctr)) { html.td(getAmountAsString(ctr * 100)).text(" %"); } else { html.td("0"); } if(!Double.isNaN(cpm)) { html.td(getAmountAsString(ctr)); } else { html.td("0"); } if(!Double.isNaN(cpc)) { html.td(getAmountAsString(cpc)); } else { html.td("0"); } if(!Double.isNaN(vpc)) { html.td(); formatAmount(html,vpc); } else { html.td("0"); } if(!Double.isNaN(roi)) { html.td(); formatAmount(html, roi * 100, " %"); } else { html.td("0"); } html.td(); formatAmount(html, result); } } html.tableEnd(); html.text("Download game data ").tag('a').attr("href", getGameLogName()).text("here").tagEnd('a').p(); /*html.table("border=1").colgroup(1).colgroup(2, "align=right").colgroup(2).colgroup(1, "align=right").tr().th("Player").th("Orders", "align=center").th("Utilization", "align=center").th("Deliveries (on&nbsp;time/late/missed)", "colspan=2").th("DPerf", "align=center"); if (participants != null) { for (int i = 0, n = participants.length; i < n; i++) { Participant player = participants[i]; ParticipantInfo agentInfo = player.getInfo(); String name = agentInfo.getName(); int orders = player.getCustomerOrders(); int deliveries = player.getCustomerDeliveries(); html.tr().td(agentInfo.isBuiltinAgent() ? "<em>" + name + "</em>" : name).td("" + orders) .td("" + player.getAverageUtilization()).text('%').td(); if (orders > 0) { int lateDeliveries = player.getCustomerLateDeliveries(); int missedDeliveries = player.getCustomerMissedDeliveries(); int onTime = (int) (100d * (deliveries - lateDeliveries) / orders + 0.5); int late = (int) (100d * lateDeliveries / orders + 0.5); int missed = (int) (100d * missedDeliveries / orders + 0.5); HtmlUtils.progress(html, 100, 8, onTime, late, missed); html.td().text(deliveries - lateDeliveries).text("&nbsp;/&nbsp;").text(lateDeliveries) .text("&nbsp;/&nbsp;").text(missedDeliveries); html.td("" + onTime + '%'); // html.td().text(onTime).text("%&nbsp;/&nbsp;") // .text(late).text("%&nbsp;/&nbsp;") // .text(missed).text('%'); } else { html.text("&nbsp;").td("&nbsp;").td("0%"); } } } html.tableEnd(); */ html.p(); /*html.table("border=1").tr().th("Simulation Parameters", "colspan=2").tr().td("Simulation:").td( "" + simulationID + " (" + simInfo.getSimulationType() + ')').tr().td("Server:").td( serverName + " (" + simInfo.getServerVersion() + ')'); // ServerConfig sConfig = simInfo.getServerConfig(); // if (sConfig != null) { // } int bankDebtInterestRate = simInfo.getBankDebtInterestRate(); int bankDepositInterestRate = simInfo.getBankDepositInterestRate(); if (bankDepositInterestRate >= 0 && bankDebtInterestRate >= 0) { html.tr().td("Bank interest (debt/deposit):").td( "" + bankDebtInterestRate + "% / " + bankDepositInterestRate + '%'); } int storageCost = simInfo.getStorageCost(); if (storageCost >= 0) { html.tr().td("Storage Cost:").td("" + storageCost + '%'); } html.tableEnd();*/ html.p().tag("hr"); html.pageEnd(); html.close(); addSimulationToHistory(agentInfos, agentColors); addSimulationResult(agentInfos, agentScores); }
diff --git a/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java b/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java index 36cbff5..ab631e8 100644 --- a/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java +++ b/servo-core/src/main/java/com/netflix/servo/publish/FileMetricObserver.java @@ -1,110 +1,110 @@ /* * #%L * servo * %% * Copyright (C) 2011 - 2012 Netflix * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.netflix.servo.publish; import com.google.common.base.Preconditions; import com.google.common.io.Closeables; import com.netflix.servo.Metric; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.TimeZone; /** * Writes observations to a file. The format is a basic text file with tabs * separating the fields. */ public final class FileMetricObserver extends BaseMetricObserver { private static final Logger LOGGER = LoggerFactory.getLogger(FileMetricObserver.class); private static final String FILE_DATE_FORMAT = "yyyy_dd_MM_HH_mm_ss_SSS"; private static final String ISO_DATE_FORMAT = "yyyy-dd-MM'T'HH:mm:ss.SSS"; private final File dir; private final SimpleDateFormat fileFormat; private final SimpleDateFormat isoFormat; /** * Creates a new instance that stores files in {@code dir} with a prefix of * {@code name} and a suffix of a timestamp in the format * {@code yyyy_dd_MM_HH_mm_ss_SSS}. * * @param name name to use as a prefix on files * @param dir directory where observations will be stored */ public FileMetricObserver(String name, File dir) { this(name, String.format("'%s'_%s'.log'", name, FILE_DATE_FORMAT), dir); } /** * Creates a new instance that stores files in {@code dir} with a name that * is created using {@code namePattern}. * * @param name name of the observer * @param namePattern date format pattern used to create the file names * @param dir directory where observations will be stored */ public FileMetricObserver(String name, String namePattern, File dir) { super(name); this.dir = dir; fileFormat = new SimpleDateFormat(namePattern); fileFormat.setTimeZone(TimeZone.getTimeZone("UTC")); isoFormat = new SimpleDateFormat(ISO_DATE_FORMAT); isoFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } /** {@inheritDoc} */ public void updateImpl(List<Metric> metrics) { Preconditions.checkNotNull(metrics); File file = new File(dir, fileFormat.format(new Date())); Writer out = null; try { - LOGGER.debug("writing %d metrics to file %s", metrics.size(), file); + LOGGER.debug("writing {} metrics to file {}", metrics.size(), file); OutputStream fileOut = new FileOutputStream(file, true); out = new OutputStreamWriter(fileOut, "UTF-8"); for (Metric m : metrics) { String timestamp = isoFormat.format(new Date(m.getTimestamp())); out.append(m.getConfig().getName()).append('\t') .append(m.getConfig().getTags().toString()).append('\t') .append(timestamp).append('\t') .append(m.getValue().toString()).append('\n'); } } catch (IOException e) { incrementFailedCount(); LOGGER.error("failed to write update to file " + file, e); } finally { Closeables.closeQuietly(out); } } }
true
true
public void updateImpl(List<Metric> metrics) { Preconditions.checkNotNull(metrics); File file = new File(dir, fileFormat.format(new Date())); Writer out = null; try { LOGGER.debug("writing %d metrics to file %s", metrics.size(), file); OutputStream fileOut = new FileOutputStream(file, true); out = new OutputStreamWriter(fileOut, "UTF-8"); for (Metric m : metrics) { String timestamp = isoFormat.format(new Date(m.getTimestamp())); out.append(m.getConfig().getName()).append('\t') .append(m.getConfig().getTags().toString()).append('\t') .append(timestamp).append('\t') .append(m.getValue().toString()).append('\n'); } } catch (IOException e) { incrementFailedCount(); LOGGER.error("failed to write update to file " + file, e); } finally { Closeables.closeQuietly(out); } }
public void updateImpl(List<Metric> metrics) { Preconditions.checkNotNull(metrics); File file = new File(dir, fileFormat.format(new Date())); Writer out = null; try { LOGGER.debug("writing {} metrics to file {}", metrics.size(), file); OutputStream fileOut = new FileOutputStream(file, true); out = new OutputStreamWriter(fileOut, "UTF-8"); for (Metric m : metrics) { String timestamp = isoFormat.format(new Date(m.getTimestamp())); out.append(m.getConfig().getName()).append('\t') .append(m.getConfig().getTags().toString()).append('\t') .append(timestamp).append('\t') .append(m.getValue().toString()).append('\n'); } } catch (IOException e) { incrementFailedCount(); LOGGER.error("failed to write update to file " + file, e); } finally { Closeables.closeQuietly(out); } }
diff --git a/src/jbsdiff/Patch.java b/src/jbsdiff/Patch.java index dd5a96c..552dd80 100644 --- a/src/jbsdiff/Patch.java +++ b/src/jbsdiff/Patch.java @@ -1,136 +1,136 @@ /* Copyright (c) 2013, Colorado State University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package jbsdiff; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorStreamFactory; /** * This class provides functionality for using an old file and a patch to * generate a new file using the bsdiff patching algorithm. * * @author malensek */ public class Patch { /** * Using an old file and its accompanying patch, this method generates a new * (updated) file and writes it to an {@link OutputStream}. */ public static void patch(byte[] old, byte[] patch, OutputStream out) throws CompressorException, InvalidHeaderException, IOException { /* Read bsdiff header */ InputStream headerIn = new ByteArrayInputStream(patch); Header header = new Header(headerIn); headerIn.close(); /* Set up InputStreams for reading different regions of the patch */ InputStream controlIn, dataIn, extraIn; controlIn = new ByteArrayInputStream(patch); dataIn = new ByteArrayInputStream(patch); extraIn = new ByteArrayInputStream(patch); try { /* Seek to the correct offsets in each stream */ controlIn.skip(Header.HEADER_SIZE); dataIn.skip(Header.HEADER_SIZE + header.getControlLength()); extraIn.skip(Header.HEADER_SIZE + header.getControlLength() + header.getDiffLength()); /* Set up compressed streams */ CompressorStreamFactory compressor = new CompressorStreamFactory(); - compressor.createCompressorInputStream(controlIn); - compressor.createCompressorInputStream(dataIn); - compressor.createCompressorInputStream(extraIn); + controlIn = compressor.createCompressorInputStream(controlIn); + dataIn = compressor.createCompressorInputStream(dataIn); + extraIn = compressor.createCompressorInputStream(extraIn); /* Start patching */ int newPointer = 0, oldPointer = 0; byte[] output = new byte[header.getOutputLength()]; while (newPointer < output.length) { ControlBlock control = new ControlBlock(controlIn); /* Read diff string */ read(dataIn, output, newPointer, control.getDiffLength()); /* Add old data to diff string */ for (int i = 0; i < control.getDiffLength(); ++i) { if ((oldPointer + i >= 0) && oldPointer + i < old.length) { output[newPointer + i] += old[oldPointer + i]; } } newPointer += control.getDiffLength(); oldPointer += control.getDiffLength(); /* Copy the extra string to the output */ read(extraIn, output, newPointer, control.getExtraLength()); newPointer += control.getExtraLength(); oldPointer += control.getSeekLength(); } out.write(output); } catch (Exception e) { throw e; } finally { controlIn.close(); dataIn.close(); extraIn.close(); } } /** * Reads data from an InputStream, and throws an {@link IOException} if * fewer bytes were read than requested. Since the lengths of data in a * bsdiff patch are explicitly encoded in the control blocks, reading less * than expected is an unrecoverable error. * * @param in InputStream to read from * @param dest byte array to read data into * @param off offset in dest to write data at * @param len length of the read */ private static void read(InputStream in, byte[] dest, int off, int len) throws IOException { if (len == 0) { /* We don't need to do anything */ return; } int read = in.read(dest, off, len); if (read < len) { throw new IOException("Corrupt patch; bytes expected = " + len + " bytes read = " + read); } } }
true
true
public static void patch(byte[] old, byte[] patch, OutputStream out) throws CompressorException, InvalidHeaderException, IOException { /* Read bsdiff header */ InputStream headerIn = new ByteArrayInputStream(patch); Header header = new Header(headerIn); headerIn.close(); /* Set up InputStreams for reading different regions of the patch */ InputStream controlIn, dataIn, extraIn; controlIn = new ByteArrayInputStream(patch); dataIn = new ByteArrayInputStream(patch); extraIn = new ByteArrayInputStream(patch); try { /* Seek to the correct offsets in each stream */ controlIn.skip(Header.HEADER_SIZE); dataIn.skip(Header.HEADER_SIZE + header.getControlLength()); extraIn.skip(Header.HEADER_SIZE + header.getControlLength() + header.getDiffLength()); /* Set up compressed streams */ CompressorStreamFactory compressor = new CompressorStreamFactory(); compressor.createCompressorInputStream(controlIn); compressor.createCompressorInputStream(dataIn); compressor.createCompressorInputStream(extraIn); /* Start patching */ int newPointer = 0, oldPointer = 0; byte[] output = new byte[header.getOutputLength()]; while (newPointer < output.length) { ControlBlock control = new ControlBlock(controlIn); /* Read diff string */ read(dataIn, output, newPointer, control.getDiffLength()); /* Add old data to diff string */ for (int i = 0; i < control.getDiffLength(); ++i) { if ((oldPointer + i >= 0) && oldPointer + i < old.length) { output[newPointer + i] += old[oldPointer + i]; } } newPointer += control.getDiffLength(); oldPointer += control.getDiffLength(); /* Copy the extra string to the output */ read(extraIn, output, newPointer, control.getExtraLength()); newPointer += control.getExtraLength(); oldPointer += control.getSeekLength(); } out.write(output); } catch (Exception e) { throw e; } finally { controlIn.close(); dataIn.close(); extraIn.close(); } }
public static void patch(byte[] old, byte[] patch, OutputStream out) throws CompressorException, InvalidHeaderException, IOException { /* Read bsdiff header */ InputStream headerIn = new ByteArrayInputStream(patch); Header header = new Header(headerIn); headerIn.close(); /* Set up InputStreams for reading different regions of the patch */ InputStream controlIn, dataIn, extraIn; controlIn = new ByteArrayInputStream(patch); dataIn = new ByteArrayInputStream(patch); extraIn = new ByteArrayInputStream(patch); try { /* Seek to the correct offsets in each stream */ controlIn.skip(Header.HEADER_SIZE); dataIn.skip(Header.HEADER_SIZE + header.getControlLength()); extraIn.skip(Header.HEADER_SIZE + header.getControlLength() + header.getDiffLength()); /* Set up compressed streams */ CompressorStreamFactory compressor = new CompressorStreamFactory(); controlIn = compressor.createCompressorInputStream(controlIn); dataIn = compressor.createCompressorInputStream(dataIn); extraIn = compressor.createCompressorInputStream(extraIn); /* Start patching */ int newPointer = 0, oldPointer = 0; byte[] output = new byte[header.getOutputLength()]; while (newPointer < output.length) { ControlBlock control = new ControlBlock(controlIn); /* Read diff string */ read(dataIn, output, newPointer, control.getDiffLength()); /* Add old data to diff string */ for (int i = 0; i < control.getDiffLength(); ++i) { if ((oldPointer + i >= 0) && oldPointer + i < old.length) { output[newPointer + i] += old[oldPointer + i]; } } newPointer += control.getDiffLength(); oldPointer += control.getDiffLength(); /* Copy the extra string to the output */ read(extraIn, output, newPointer, control.getExtraLength()); newPointer += control.getExtraLength(); oldPointer += control.getSeekLength(); } out.write(output); } catch (Exception e) { throw e; } finally { controlIn.close(); dataIn.close(); extraIn.close(); } }
diff --git a/src/org/androidaalto/droidkino/xml/FinnikoSAXParser.java b/src/org/androidaalto/droidkino/xml/FinnikoSAXParser.java index 56c11a4..9304b54 100644 --- a/src/org/androidaalto/droidkino/xml/FinnikoSAXParser.java +++ b/src/org/androidaalto/droidkino/xml/FinnikoSAXParser.java @@ -1,456 +1,456 @@ /******************************************************************************* Copyright: 2011 Android Aalto Community This file is part of Droidkino. Droidkino is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Droidkino is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Droidkino; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ package org.androidaalto.droidkino.xml; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.androidaalto.droidkino.beans.MovieInfo; import org.androidaalto.droidkino.beans.MovieSchedule; import org.androidaalto.droidkino.beans.MovieTrailer; import org.androidaalto.droidkino.beans.TheatreArea; import android.sax.Element; import android.sax.EndElementListener; import android.sax.EndTextElementListener; import android.sax.RootElement; import android.util.Xml; /** * A SAX implementation of the Base FinnKino XML parser * * @author marcostong17 * @see BaseFinnkinoParser * @see MovieParser * */ public class FinnikoSAXParser extends BaseFinnkinoParser { /** * @throws MalformedURLException */ public FinnikoSAXParser() throws MalformedURLException { super(); } @Override public List<MovieInfo> parseMovies(String areaId) { final MovieInfo movieInfo = new MovieInfo(); final MovieTrailer movieTrailer = new MovieTrailer(); final List<MovieInfo> movies = new ArrayList<MovieInfo>(); RootElement root = new RootElement(EVENTS); Element event = root.getChild(EVENT); Element images = event.getChild(IMAGES); Element videos = event.getChild(VIDEOS); Element eventVideo = videos.getChild(EVENT_VIDEO); event.setEndElementListener(new EndElementListener() { @Override public void end() { movies.add(movieInfo.copy()); } }); eventVideo.setEndElementListener(new EndElementListener() { @Override public void end() { movieInfo.addMovieTrailer(movieTrailer.copy()); } }); event.getChild(ID).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventId(body); } }); event.getChild(TITLE).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieInfo.setTitle(body); } }); event.getChild(ORIGINAL_TITLE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setOriginalTitle(body); } }); event.getChild(PRODUCTION_YEAR).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setProductionYear(body); } }); event.getChild(LENGTH_IN_MINUTES).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setLenghtInMinutes(body); } }); event.getChild(DATE_LOCAL_RELEASE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setDtLocalRelease(body); } }); event.getChild(RATING_LABEL).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setRatingLabel(body); } }); event.getChild(LOGAL_DISTRIBUTOR_NAME).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setLocalDistributorName(body); } }); event.getChild(GLOBAL_DISTRIBUTOR_NAME).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setGlobalDistributorName(body); } }); event.getChild(GENRES).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setGenres(body); } }); event.getChild(SYNOPSIS).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setSynopsis(body); } }); images.getChild(EVENT_SMALL_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventSmallImagePortrait(body); } }); images.getChild(EVENT_LARGE_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventLargeImagePortrait(body); } }); images.getChild(EVENT_SMALL_IMAGE_LANDSCAPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventSmallImageLandscape(body); } }); images.getChild(EVENT_LARGE_IMAGE_LANDSCAPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventLargeImageLandscape(body); } }); eventVideo.getChild(TITLE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { - movieInfo.setTitle(body); + movieTrailer.setTitle(body); } }); eventVideo.getChild(LOCATION).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setLocation(body); } }); eventVideo.getChild(THUMBNAIL_LOCATION).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setThumbnailLocation(body); } }); eventVideo.getChild(MEDIA_RESOURCE_FORMAT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setMediaResourceFormat(body); } }); eventVideo.getChild(MEDIA_RESOURCE_SUB_TYPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setMediaResourceSubType(body); } }); try { StringBuffer urlStringBuffer = new StringBuffer(BASE_FINN_FINO_URL); urlStringBuffer.append(EVENTS); if (areaId != null) { urlStringBuffer.append("?"); urlStringBuffer.append(PARAM_AREA); urlStringBuffer.append("="); urlStringBuffer.append(areaId); } URL url = new URL(urlStringBuffer.toString()); Xml.parse(this.getInputStream(url), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } return movies; } @Override public List<TheatreArea> parseAreas() { final TheatreArea theatreArea = new TheatreArea(); final List<TheatreArea> theatres = new ArrayList<TheatreArea>(); RootElement root = new RootElement(THEATRE_AREAS); Element area = root.getChild(THEATRE_AREA); area.setEndElementListener(new EndElementListener() { @Override public void end() { theatres.add(theatreArea.copy()); } }); area.getChild(ID).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { theatreArea.setId(body); } }); area.getChild(NAME).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { theatreArea.setName(body); } }); try { URL url = new URL(BASE_FINN_FINO_URL + THEATRE_AREAS); Xml.parse(this.getInputStream(url), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } return theatres; } @Override public List<MovieSchedule> parseSchedules(String areaId, String date, String eventId) { final MovieSchedule movieSchedule = new MovieSchedule(); final List<MovieSchedule> schedules = new ArrayList<MovieSchedule>(); RootElement root = new RootElement(SCHEDULE); Element shows = root.getChild(SHOWS); Element show = shows.getChild(SHOW); Element images = show.getChild(IMAGES); show.setEndElementListener(new EndElementListener() { @Override public void end() { schedules.add(movieSchedule.copy()); } }); show.getChild(EVENT_ID).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setEventId(body); } }); show.getChild(TITLE).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setTitle(body); } }); show.getChild(LENGTH_IN_MINUTES).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setLengthInMinutes(Integer.parseInt(body)); } }); show.getChild(THEATRE_ID).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setTheatreId(body); } }); show.getChild(THEATRE).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setTheatre(body); } }); show.getChild(THEATRE_AUDITORIUM).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setTheatreAuditorium(body); } }); show.getChild(DTTM_SHOW_START).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setDttmShowStart(body); } }); show.getChild(PRESENTATION_METHOD_AND_LANGAUGE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { if (body.startsWith("3D")) { movieSchedule.set3D(true); if (body.substring(2).length() > 0) { movieSchedule.setLanguage(body.substring(3)); } } else { movieSchedule.set3D(false); movieSchedule.setLanguage(body); } } }); images.getChild(EVENT_SMALL_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieSchedule.setEventSmallImagePortrait(body); } }); try { StringBuffer urlStringBuffer = new StringBuffer(BASE_FINN_FINO_URL); urlStringBuffer.append(SCHEDULE); if (areaId != null || date != null) { urlStringBuffer.append("?"); urlStringBuffer.append(PARAM_AREA); urlStringBuffer.append("="); urlStringBuffer.append(areaId); urlStringBuffer.append("&"); urlStringBuffer.append(PARAM_DATE); urlStringBuffer.append("="); urlStringBuffer.append(date); } URL url = new URL(urlStringBuffer.toString()); Xml.parse(this.getInputStream(url), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } return schedules; } }
true
true
public List<MovieInfo> parseMovies(String areaId) { final MovieInfo movieInfo = new MovieInfo(); final MovieTrailer movieTrailer = new MovieTrailer(); final List<MovieInfo> movies = new ArrayList<MovieInfo>(); RootElement root = new RootElement(EVENTS); Element event = root.getChild(EVENT); Element images = event.getChild(IMAGES); Element videos = event.getChild(VIDEOS); Element eventVideo = videos.getChild(EVENT_VIDEO); event.setEndElementListener(new EndElementListener() { @Override public void end() { movies.add(movieInfo.copy()); } }); eventVideo.setEndElementListener(new EndElementListener() { @Override public void end() { movieInfo.addMovieTrailer(movieTrailer.copy()); } }); event.getChild(ID).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventId(body); } }); event.getChild(TITLE).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieInfo.setTitle(body); } }); event.getChild(ORIGINAL_TITLE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setOriginalTitle(body); } }); event.getChild(PRODUCTION_YEAR).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setProductionYear(body); } }); event.getChild(LENGTH_IN_MINUTES).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setLenghtInMinutes(body); } }); event.getChild(DATE_LOCAL_RELEASE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setDtLocalRelease(body); } }); event.getChild(RATING_LABEL).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setRatingLabel(body); } }); event.getChild(LOGAL_DISTRIBUTOR_NAME).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setLocalDistributorName(body); } }); event.getChild(GLOBAL_DISTRIBUTOR_NAME).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setGlobalDistributorName(body); } }); event.getChild(GENRES).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setGenres(body); } }); event.getChild(SYNOPSIS).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setSynopsis(body); } }); images.getChild(EVENT_SMALL_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventSmallImagePortrait(body); } }); images.getChild(EVENT_LARGE_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventLargeImagePortrait(body); } }); images.getChild(EVENT_SMALL_IMAGE_LANDSCAPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventSmallImageLandscape(body); } }); images.getChild(EVENT_LARGE_IMAGE_LANDSCAPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventLargeImageLandscape(body); } }); eventVideo.getChild(TITLE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setTitle(body); } }); eventVideo.getChild(LOCATION).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setLocation(body); } }); eventVideo.getChild(THUMBNAIL_LOCATION).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setThumbnailLocation(body); } }); eventVideo.getChild(MEDIA_RESOURCE_FORMAT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setMediaResourceFormat(body); } }); eventVideo.getChild(MEDIA_RESOURCE_SUB_TYPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setMediaResourceSubType(body); } }); try { StringBuffer urlStringBuffer = new StringBuffer(BASE_FINN_FINO_URL); urlStringBuffer.append(EVENTS); if (areaId != null) { urlStringBuffer.append("?"); urlStringBuffer.append(PARAM_AREA); urlStringBuffer.append("="); urlStringBuffer.append(areaId); } URL url = new URL(urlStringBuffer.toString()); Xml.parse(this.getInputStream(url), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } return movies; }
public List<MovieInfo> parseMovies(String areaId) { final MovieInfo movieInfo = new MovieInfo(); final MovieTrailer movieTrailer = new MovieTrailer(); final List<MovieInfo> movies = new ArrayList<MovieInfo>(); RootElement root = new RootElement(EVENTS); Element event = root.getChild(EVENT); Element images = event.getChild(IMAGES); Element videos = event.getChild(VIDEOS); Element eventVideo = videos.getChild(EVENT_VIDEO); event.setEndElementListener(new EndElementListener() { @Override public void end() { movies.add(movieInfo.copy()); } }); eventVideo.setEndElementListener(new EndElementListener() { @Override public void end() { movieInfo.addMovieTrailer(movieTrailer.copy()); } }); event.getChild(ID).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventId(body); } }); event.getChild(TITLE).setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { movieInfo.setTitle(body); } }); event.getChild(ORIGINAL_TITLE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setOriginalTitle(body); } }); event.getChild(PRODUCTION_YEAR).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setProductionYear(body); } }); event.getChild(LENGTH_IN_MINUTES).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setLenghtInMinutes(body); } }); event.getChild(DATE_LOCAL_RELEASE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setDtLocalRelease(body); } }); event.getChild(RATING_LABEL).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setRatingLabel(body); } }); event.getChild(LOGAL_DISTRIBUTOR_NAME).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setLocalDistributorName(body); } }); event.getChild(GLOBAL_DISTRIBUTOR_NAME).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setGlobalDistributorName(body); } }); event.getChild(GENRES).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setGenres(body); } }); event.getChild(SYNOPSIS).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setSynopsis(body); } }); images.getChild(EVENT_SMALL_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventSmallImagePortrait(body); } }); images.getChild(EVENT_LARGE_IMAGE_PORTRAIT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventLargeImagePortrait(body); } }); images.getChild(EVENT_SMALL_IMAGE_LANDSCAPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventSmallImageLandscape(body); } }); images.getChild(EVENT_LARGE_IMAGE_LANDSCAPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieInfo.setEventLargeImageLandscape(body); } }); eventVideo.getChild(TITLE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setTitle(body); } }); eventVideo.getChild(LOCATION).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setLocation(body); } }); eventVideo.getChild(THUMBNAIL_LOCATION).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setThumbnailLocation(body); } }); eventVideo.getChild(MEDIA_RESOURCE_FORMAT).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setMediaResourceFormat(body); } }); eventVideo.getChild(MEDIA_RESOURCE_SUB_TYPE).setEndTextElementListener( new EndTextElementListener() { @Override public void end(String body) { movieTrailer.setMediaResourceSubType(body); } }); try { StringBuffer urlStringBuffer = new StringBuffer(BASE_FINN_FINO_URL); urlStringBuffer.append(EVENTS); if (areaId != null) { urlStringBuffer.append("?"); urlStringBuffer.append(PARAM_AREA); urlStringBuffer.append("="); urlStringBuffer.append(areaId); } URL url = new URL(urlStringBuffer.toString()); Xml.parse(this.getInputStream(url), Xml.Encoding.UTF_8, root.getContentHandler()); } catch (Exception e) { throw new RuntimeException(e); } return movies; }
diff --git a/orcid-core/src/main/java/org/orcid/core/cli/SendEventEmail.java b/orcid-core/src/main/java/org/orcid/core/cli/SendEventEmail.java index 1aeead977e..08ab9074df 100644 --- a/orcid-core/src/main/java/org/orcid/core/cli/SendEventEmail.java +++ b/orcid-core/src/main/java/org/orcid/core/cli/SendEventEmail.java @@ -1,184 +1,184 @@ /** * ============================================================================= * * ORCID (R) Open Source * http://orcid.org * * Copyright (c) 2012-2013 ORCID, Inc. * Licensed under an MIT-Style License (MIT) * http://orcid.org/open-source-license * * This copyright and license information (including a link to the full license) * shall be included in its entirety in all copies or substantial portion of * the software. * * ============================================================================= */ package org.orcid.core.cli; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang3.time.DurationFormatUtils; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import org.orcid.core.manager.NotificationManager; import org.orcid.core.manager.OrcidProfileManager; import org.orcid.core.manager.TemplateManager; import org.orcid.core.manager.impl.MailGunManager; import org.orcid.core.manager.impl.OrcidUrlManager; import org.orcid.jaxb.model.message.OrcidProfile; import org.orcid.persistence.dao.GenericDao; import org.orcid.persistence.dao.ProfileDao; import org.orcid.persistence.jpa.entities.ProfileEventEntity; import org.orcid.persistence.jpa.entities.ProfileEventType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; /** * * @author rcpeters * */ public class SendEventEmail { private ProfileDao profileDao; private OrcidProfileManager orcidProfileManager; private MailGunManager mailGunManager; private TemplateManager templateManager; private GenericDao<ProfileEventEntity, Long> profileEventDao; private OrcidUrlManager orcidUrlManager; private NotificationManager notificationManager; private TransactionTemplate transactionTemplate; private static Logger LOG = LoggerFactory.getLogger(SendEventEmail.class); private static final int CHUNK_SIZE = 1000; @Option(name = "-testSendToOrcids", usage = "Send validation email to following ORCID Ids") private String orcs; @Option(name = "-run", usage = "Runs sendEmailByEvent, which loops through all orcids who haven't been verified and not sent the crossref email and sends the crossref email") private String run; public static void main(String... args) { SendEventEmail se = new SendEventEmail(); CmdLineParser parser = new CmdLineParser(se); if (args == null) { parser.printUsage(System.err); } try { parser.parseArgument(args); se.execute(); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); } } private void execute() { init(); if (run != null && run.equalsIgnoreCase("true")) { sendEmailByEvent(); } else if (orcs != null) { for (String orc : orcs.split(" ")) { sendEmail(orc); } } } private boolean sendEmail(String orcid) { OrcidProfile orcidProfile = orcidProfileManager.retrieveOrcidProfile(orcid); if (orcidProfile.getOrcidBio() != null && orcidProfile.getOrcidBio().getContactDetails() != null && orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail() != null && orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue() != null) { try { String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue(); String emailFriendlyName = notificationManager.deriveEmailFriendlyName(orcidProfile); Map<String, Object> templateParams = new HashMap<String, Object>(); templateParams.put("emailName", emailFriendlyName); String verificationUrl = null; try { verificationUrl = notificationManager.createVerificationUrl(email, new URI(orcidUrlManager.getBaseUrl())); } catch (URISyntaxException e) { LOG.debug("SendEventEmail exception", e); } templateParams.put("verificationUrl", verificationUrl); templateParams.put("orcid", orcidProfile.getOrcid().getValue()); templateParams.put("baseUri", orcidUrlManager.getBaseUrl()); String text = templateManager.processTemplate("verification_email_w_crossref.ftl", templateParams); String html = templateManager.processTemplate("verification_email_w_crossref_html.ftl", templateParams); - mailGunManager.sendSimpleVerfiyEmail("[email protected]", "[email protected]", "Please verify your email", text, html); + mailGunManager.sendSimpleVerfiyEmail("[email protected]", email, "Please verify your email", text, html); } catch (Exception e) { LOG.error("Exception trying to send email to: " +orcid, e); return false; } return true; } return false; } private void sendEmailByEvent() { long startTime = System.currentTimeMillis(); @SuppressWarnings("unchecked") List<String> orcids = Collections.EMPTY_LIST; int doneCount = 0; do { orcids = profileDao.findByEventType(CHUNK_SIZE, ProfileEventType.EMAIL_VERIFY_CROSSREF_MARKETING_CHECK, null, true); for (final String orcid : orcids) { LOG.info("Migrating emails for profile: {}", orcid); transactionTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { OrcidProfile orcidProfile = orcidProfileManager.retrieveOrcidProfile(orcid); profileEventDao.persist(new ProfileEventEntity(orcid, ProfileEventType.EMAIL_VERIFY_CROSSREF_MARKETING_CHECK)); if (orcidProfile.isDeactivated()) { profileEventDao.persist(new ProfileEventEntity(orcid, ProfileEventType.EMAIL_VERIFY_CROSSREF_MARKETING_SKIPPED)); } else { if (sendEmail(orcid)) profileEventDao.persist(new ProfileEventEntity(orcid, ProfileEventType.EMAIL_VERIFY_CROSSREF_MARKETING_SENT)); } } }); doneCount++; } LOG.info("Sending crossref verify emails on number: {}", doneCount); } while (!orcids.isEmpty()); long endTime = System.currentTimeMillis(); String timeTaken = DurationFormatUtils.formatDurationHMS(endTime - startTime); LOG.info("Sending crossref verify emails: doneCount={}, timeTaken={} (H:m:s.S)", doneCount, timeTaken); } private void init() { ApplicationContext context = new ClassPathXmlApplicationContext("orcid-core-context.xml"); profileDao = (ProfileDao) context.getBean("profileDao"); profileEventDao = (GenericDao<ProfileEventEntity, Long>) context.getBean("profileEventDao"); mailGunManager = (MailGunManager) context.getBean("mailGunManager"); orcidProfileManager = (OrcidProfileManager) context.getBean("orcidProfileManager"); transactionTemplate = (TransactionTemplate) context.getBean("transactionTemplate"); notificationManager = (NotificationManager) context.getBean("notificationManager"); templateManager = (TemplateManager) context.getBean("templateManager"); orcidUrlManager = (OrcidUrlManager) context.getBean("orcidUrlManager"); } }
true
true
private boolean sendEmail(String orcid) { OrcidProfile orcidProfile = orcidProfileManager.retrieveOrcidProfile(orcid); if (orcidProfile.getOrcidBio() != null && orcidProfile.getOrcidBio().getContactDetails() != null && orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail() != null && orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue() != null) { try { String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue(); String emailFriendlyName = notificationManager.deriveEmailFriendlyName(orcidProfile); Map<String, Object> templateParams = new HashMap<String, Object>(); templateParams.put("emailName", emailFriendlyName); String verificationUrl = null; try { verificationUrl = notificationManager.createVerificationUrl(email, new URI(orcidUrlManager.getBaseUrl())); } catch (URISyntaxException e) { LOG.debug("SendEventEmail exception", e); } templateParams.put("verificationUrl", verificationUrl); templateParams.put("orcid", orcidProfile.getOrcid().getValue()); templateParams.put("baseUri", orcidUrlManager.getBaseUrl()); String text = templateManager.processTemplate("verification_email_w_crossref.ftl", templateParams); String html = templateManager.processTemplate("verification_email_w_crossref_html.ftl", templateParams); mailGunManager.sendSimpleVerfiyEmail("[email protected]", "[email protected]", "Please verify your email", text, html); } catch (Exception e) { LOG.error("Exception trying to send email to: " +orcid, e); return false; } return true; } return false; }
private boolean sendEmail(String orcid) { OrcidProfile orcidProfile = orcidProfileManager.retrieveOrcidProfile(orcid); if (orcidProfile.getOrcidBio() != null && orcidProfile.getOrcidBio().getContactDetails() != null && orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail() != null && orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue() != null) { try { String email = orcidProfile.getOrcidBio().getContactDetails().retrievePrimaryEmail().getValue(); String emailFriendlyName = notificationManager.deriveEmailFriendlyName(orcidProfile); Map<String, Object> templateParams = new HashMap<String, Object>(); templateParams.put("emailName", emailFriendlyName); String verificationUrl = null; try { verificationUrl = notificationManager.createVerificationUrl(email, new URI(orcidUrlManager.getBaseUrl())); } catch (URISyntaxException e) { LOG.debug("SendEventEmail exception", e); } templateParams.put("verificationUrl", verificationUrl); templateParams.put("orcid", orcidProfile.getOrcid().getValue()); templateParams.put("baseUri", orcidUrlManager.getBaseUrl()); String text = templateManager.processTemplate("verification_email_w_crossref.ftl", templateParams); String html = templateManager.processTemplate("verification_email_w_crossref_html.ftl", templateParams); mailGunManager.sendSimpleVerfiyEmail("[email protected]", email, "Please verify your email", text, html); } catch (Exception e) { LOG.error("Exception trying to send email to: " +orcid, e); return false; } return true; } return false; }
diff --git a/src/oving1/ServingArea.java b/src/oving1/ServingArea.java index 8ff64cc..f1cd978 100644 --- a/src/oving1/ServingArea.java +++ b/src/oving1/ServingArea.java @@ -1,46 +1,46 @@ package oving1; import java.util.ArrayList; public class ServingArea { private static int capacity = SushiBar.capacity; private static ArrayList<Customer> customers = new ArrayList<Customer>(); private static int orders = 0; private static int eatenOrders = 0; private static int takeAwayOrders = 0; private static int id = 1; public ServingArea(int capacity){ this.capacity = capacity; } public static Boolean isSpace(){ return customers.size() < capacity; } public synchronized static Boolean getBool(){ return customers.size() < capacity; } public synchronized static void handleCustomer(Customer customer, Boolean bool){ if (customers.size() < capacity && bool && customer.getId()==id){ id++; customers.add(customer); orders += customer.getOrders(); eatenOrders += customer.getEatenOrders(); takeAwayOrders += customer.getEatenOrders(); System.out.println("Before Add: "+customer.getId()+id); System.out.println("Add: " + ServingArea.customers.size()+ " id "+customer.getId()); } else if(!bool){ customers.remove(customer); System.out.println("Remove: " + ServingArea.customers.size() + " id "+customer.getId()); Customer newCustomer = SushiBar.door.handleCustomer(null, false); - new Thread(newCustomer).notify(); + newCustomer.notifyMe(); } else{ System.out.println("Else "+customer.getId()); customer.waitMe(); } } }
true
true
public synchronized static void handleCustomer(Customer customer, Boolean bool){ if (customers.size() < capacity && bool && customer.getId()==id){ id++; customers.add(customer); orders += customer.getOrders(); eatenOrders += customer.getEatenOrders(); takeAwayOrders += customer.getEatenOrders(); System.out.println("Before Add: "+customer.getId()+id); System.out.println("Add: " + ServingArea.customers.size()+ " id "+customer.getId()); } else if(!bool){ customers.remove(customer); System.out.println("Remove: " + ServingArea.customers.size() + " id "+customer.getId()); Customer newCustomer = SushiBar.door.handleCustomer(null, false); new Thread(newCustomer).notify(); } else{ System.out.println("Else "+customer.getId()); customer.waitMe(); } }
public synchronized static void handleCustomer(Customer customer, Boolean bool){ if (customers.size() < capacity && bool && customer.getId()==id){ id++; customers.add(customer); orders += customer.getOrders(); eatenOrders += customer.getEatenOrders(); takeAwayOrders += customer.getEatenOrders(); System.out.println("Before Add: "+customer.getId()+id); System.out.println("Add: " + ServingArea.customers.size()+ " id "+customer.getId()); } else if(!bool){ customers.remove(customer); System.out.println("Remove: " + ServingArea.customers.size() + " id "+customer.getId()); Customer newCustomer = SushiBar.door.handleCustomer(null, false); newCustomer.notifyMe(); } else{ System.out.println("Else "+customer.getId()); customer.waitMe(); } }
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java b/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java index 026cc4f57..0414affc8 100644 --- a/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java +++ b/solr/core/src/java/org/apache/solr/search/grouping/endresulttransformer/GroupedEndResultTransformer.java @@ -1,112 +1,112 @@ package org.apache.solr.search.grouping.endresulttransformer; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.grouping.GroupDocs; import org.apache.lucene.search.grouping.TopGroups; import org.apache.lucene.util.BytesRef; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.handler.component.ResponseBuilder; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.SolrIndexSearcher; import org.apache.solr.search.grouping.distributed.command.QueryCommandResult; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Implementation of {@link EndResultTransformer} that keeps each grouped result separate in the final response. */ public class GroupedEndResultTransformer implements EndResultTransformer { private final SolrIndexSearcher searcher; public GroupedEndResultTransformer(SolrIndexSearcher searcher) { this.searcher = searcher; } /** * {@inheritDoc} */ @Override public void transform(Map<String, ?> result, ResponseBuilder rb, SolrDocumentSource solrDocumentSource) { - NamedList<Object> commands = new NamedList<Object>(); + NamedList<Object> commands = new SimpleOrderedMap<Object>(); for (Map.Entry<String, ?> entry : result.entrySet()) { Object value = entry.getValue(); if (TopGroups.class.isInstance(value)) { @SuppressWarnings("unchecked") TopGroups<BytesRef> topGroups = (TopGroups<BytesRef>) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", rb.totalHitCount); Integer totalGroupCount = rb.mergedGroupCounts.get(entry.getKey()); if (totalGroupCount != null) { command.add("ngroups", totalGroupCount); } List<NamedList> groups = new ArrayList<NamedList>(); SchemaField groupField = searcher.getSchema().getField(entry.getKey()); FieldType groupFieldType = groupField.getType(); for (GroupDocs<BytesRef> group : topGroups.groups) { SimpleOrderedMap<Object> groupResult = new SimpleOrderedMap<Object>(); if (group.groupValue != null) { groupResult.add( "groupValue", groupFieldType.toObject(groupField.createField(group.groupValue.utf8ToString(), 1.0f)) ); } else { groupResult.add("groupValue", null); } SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(group.totalHits); if (!Float.isNaN(group.maxScore)) { docList.setMaxScore(group.maxScore); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc : group.scoreDocs) { docList.add(solrDocumentSource.retrieve(scoreDoc)); } groupResult.add("doclist", docList); groups.add(groupResult); } command.add("groups", groups); commands.add(entry.getKey(), command); } else if (QueryCommandResult.class.isInstance(value)) { QueryCommandResult queryCommandResult = (QueryCommandResult) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", queryCommandResult.getMatches()); SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(queryCommandResult.getTopDocs().totalHits); if (!Float.isNaN(queryCommandResult.getTopDocs().getMaxScore())) { docList.setMaxScore(queryCommandResult.getTopDocs().getMaxScore()); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc :queryCommandResult.getTopDocs().scoreDocs){ docList.add(solrDocumentSource.retrieve(scoreDoc)); } command.add("doclist", docList); commands.add(entry.getKey(), command); } } rb.rsp.add("grouped", commands); } }
true
true
public void transform(Map<String, ?> result, ResponseBuilder rb, SolrDocumentSource solrDocumentSource) { NamedList<Object> commands = new NamedList<Object>(); for (Map.Entry<String, ?> entry : result.entrySet()) { Object value = entry.getValue(); if (TopGroups.class.isInstance(value)) { @SuppressWarnings("unchecked") TopGroups<BytesRef> topGroups = (TopGroups<BytesRef>) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", rb.totalHitCount); Integer totalGroupCount = rb.mergedGroupCounts.get(entry.getKey()); if (totalGroupCount != null) { command.add("ngroups", totalGroupCount); } List<NamedList> groups = new ArrayList<NamedList>(); SchemaField groupField = searcher.getSchema().getField(entry.getKey()); FieldType groupFieldType = groupField.getType(); for (GroupDocs<BytesRef> group : topGroups.groups) { SimpleOrderedMap<Object> groupResult = new SimpleOrderedMap<Object>(); if (group.groupValue != null) { groupResult.add( "groupValue", groupFieldType.toObject(groupField.createField(group.groupValue.utf8ToString(), 1.0f)) ); } else { groupResult.add("groupValue", null); } SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(group.totalHits); if (!Float.isNaN(group.maxScore)) { docList.setMaxScore(group.maxScore); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc : group.scoreDocs) { docList.add(solrDocumentSource.retrieve(scoreDoc)); } groupResult.add("doclist", docList); groups.add(groupResult); } command.add("groups", groups); commands.add(entry.getKey(), command); } else if (QueryCommandResult.class.isInstance(value)) { QueryCommandResult queryCommandResult = (QueryCommandResult) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", queryCommandResult.getMatches()); SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(queryCommandResult.getTopDocs().totalHits); if (!Float.isNaN(queryCommandResult.getTopDocs().getMaxScore())) { docList.setMaxScore(queryCommandResult.getTopDocs().getMaxScore()); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc :queryCommandResult.getTopDocs().scoreDocs){ docList.add(solrDocumentSource.retrieve(scoreDoc)); } command.add("doclist", docList); commands.add(entry.getKey(), command); } } rb.rsp.add("grouped", commands); }
public void transform(Map<String, ?> result, ResponseBuilder rb, SolrDocumentSource solrDocumentSource) { NamedList<Object> commands = new SimpleOrderedMap<Object>(); for (Map.Entry<String, ?> entry : result.entrySet()) { Object value = entry.getValue(); if (TopGroups.class.isInstance(value)) { @SuppressWarnings("unchecked") TopGroups<BytesRef> topGroups = (TopGroups<BytesRef>) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", rb.totalHitCount); Integer totalGroupCount = rb.mergedGroupCounts.get(entry.getKey()); if (totalGroupCount != null) { command.add("ngroups", totalGroupCount); } List<NamedList> groups = new ArrayList<NamedList>(); SchemaField groupField = searcher.getSchema().getField(entry.getKey()); FieldType groupFieldType = groupField.getType(); for (GroupDocs<BytesRef> group : topGroups.groups) { SimpleOrderedMap<Object> groupResult = new SimpleOrderedMap<Object>(); if (group.groupValue != null) { groupResult.add( "groupValue", groupFieldType.toObject(groupField.createField(group.groupValue.utf8ToString(), 1.0f)) ); } else { groupResult.add("groupValue", null); } SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(group.totalHits); if (!Float.isNaN(group.maxScore)) { docList.setMaxScore(group.maxScore); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc : group.scoreDocs) { docList.add(solrDocumentSource.retrieve(scoreDoc)); } groupResult.add("doclist", docList); groups.add(groupResult); } command.add("groups", groups); commands.add(entry.getKey(), command); } else if (QueryCommandResult.class.isInstance(value)) { QueryCommandResult queryCommandResult = (QueryCommandResult) value; NamedList<Object> command = new SimpleOrderedMap<Object>(); command.add("matches", queryCommandResult.getMatches()); SolrDocumentList docList = new SolrDocumentList(); docList.setNumFound(queryCommandResult.getTopDocs().totalHits); if (!Float.isNaN(queryCommandResult.getTopDocs().getMaxScore())) { docList.setMaxScore(queryCommandResult.getTopDocs().getMaxScore()); } docList.setStart(rb.getGroupingSpec().getGroupOffset()); for (ScoreDoc scoreDoc :queryCommandResult.getTopDocs().scoreDocs){ docList.add(solrDocumentSource.retrieve(scoreDoc)); } command.add("doclist", docList); commands.add(entry.getKey(), command); } } rb.rsp.add("grouped", commands); }
diff --git a/lucene/src/test/org/apache/lucene/index/TestFieldsReader.java b/lucene/src/test/org/apache/lucene/index/TestFieldsReader.java index 82316867..e8f05382 100644 --- a/lucene/src/test/org/apache/lucene/index/TestFieldsReader.java +++ b/lucene/src/test/org/apache/lucene/index/TestFieldsReader.java @@ -1,510 +1,510 @@ package org.apache.lucene.index; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.lucene.analysis.WhitespaceAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldSelector; import org.apache.lucene.document.FieldSelectorResult; import org.apache.lucene.document.Fieldable; import org.apache.lucene.document.LoadFirstFieldSelector; import org.apache.lucene.document.SetBasedFieldSelector; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.AlreadyClosedException; import org.apache.lucene.store.BufferedIndexInput; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.IndexInput; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; public class TestFieldsReader extends LuceneTestCase { private RAMDirectory dir = new RAMDirectory(); private Document testDoc = new Document(); private FieldInfos fieldInfos = null; private final static String TEST_SEGMENT_NAME = "_0"; public TestFieldsReader(String s) { super(s); } @Override protected void setUp() throws Exception { super.setUp(); fieldInfos = new FieldInfos(); DocHelper.setupDoc(testDoc); fieldInfos.add(testDoc); IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)); ((LogMergePolicy) conf.getMergePolicy()).setUseCompoundFile(false); ((LogMergePolicy) conf.getMergePolicy()).setUseCompoundDocStore(false); IndexWriter writer = new IndexWriter(dir, conf); writer.addDocument(testDoc); writer.close(); } public void test() throws IOException { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader.size() == 1); Document doc = reader.doc(0, null); assertTrue(doc != null); assertTrue(doc.getField(DocHelper.TEXT_FIELD_1_KEY) != null); Fieldable field = doc.getField(DocHelper.TEXT_FIELD_2_KEY); assertTrue(field != null); assertTrue(field.isTermVectorStored() == true); assertTrue(field.isStoreOffsetWithTermVector() == true); assertTrue(field.isStorePositionWithTermVector() == true); assertTrue(field.getOmitNorms() == false); assertTrue(field.getOmitTermFreqAndPositions() == false); field = doc.getField(DocHelper.TEXT_FIELD_3_KEY); assertTrue(field != null); assertTrue(field.isTermVectorStored() == false); assertTrue(field.isStoreOffsetWithTermVector() == false); assertTrue(field.isStorePositionWithTermVector() == false); assertTrue(field.getOmitNorms() == true); assertTrue(field.getOmitTermFreqAndPositions() == false); field = doc.getField(DocHelper.NO_TF_KEY); assertTrue(field != null); assertTrue(field.isTermVectorStored() == false); assertTrue(field.isStoreOffsetWithTermVector() == false); assertTrue(field.isStorePositionWithTermVector() == false); assertTrue(field.getOmitNorms() == false); assertTrue(field.getOmitTermFreqAndPositions() == true); reader.close(); } public void testLazyFields() throws Exception { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader.size() == 1); Set<String> loadFieldNames = new HashSet<String>(); loadFieldNames.add(DocHelper.TEXT_FIELD_1_KEY); loadFieldNames.add(DocHelper.TEXT_FIELD_UTF1_KEY); Set<String> lazyFieldNames = new HashSet<String>(); //new String[]{DocHelper.LARGE_LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_BINARY_KEY}; lazyFieldNames.add(DocHelper.LARGE_LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_BINARY_KEY); lazyFieldNames.add(DocHelper.TEXT_FIELD_UTF2_KEY); SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames); Document doc = reader.doc(0, fieldSelector); assertTrue("doc is null and it shouldn't be", doc != null); Fieldable field = doc.getFieldable(DocHelper.LAZY_FIELD_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("field is not lazy and it should be", field.isLazy()); String value = field.stringValue(); assertTrue("value is null and it shouldn't be", value != null); assertTrue(value + " is not equal to " + DocHelper.LAZY_FIELD_TEXT, value.equals(DocHelper.LAZY_FIELD_TEXT) == true); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF1_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF1_TEXT) == true); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF2_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == true); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF2_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF2_TEXT) == true); field = doc.getFieldable(DocHelper.LAZY_FIELD_BINARY_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("stringValue isn't null for lazy binary field", field.stringValue() == null); byte [] bytes = field.getBinaryValue(); assertTrue("bytes is null and it shouldn't be", bytes != null); assertTrue("", DocHelper.LAZY_FIELD_BINARY_BYTES.length == bytes.length); assertTrue("calling binaryValue() twice should give same reference", field.getBinaryValue() == field.getBinaryValue()); for (int i = 0; i < bytes.length; i++) { assertTrue("byte[" + i + "] is mismatched", bytes[i] == DocHelper.LAZY_FIELD_BINARY_BYTES[i]); } } public void testLatentFields() throws Exception { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader != null); assertTrue(reader.size() == 1); - Set loadFieldNames = new HashSet(); + Set<String> loadFieldNames = new HashSet<String>(); loadFieldNames.add(DocHelper.TEXT_FIELD_1_KEY); loadFieldNames.add(DocHelper.TEXT_FIELD_UTF1_KEY); - Set lazyFieldNames = new HashSet(); + Set<String> lazyFieldNames = new HashSet<String>(); //new String[]{DocHelper.LARGE_LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_BINARY_KEY}; lazyFieldNames.add(DocHelper.LARGE_LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_BINARY_KEY); lazyFieldNames.add(DocHelper.TEXT_FIELD_UTF2_KEY); // Use LATENT instead of LAZY SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames) { public FieldSelectorResult accept(String fieldName) { final FieldSelectorResult result = super.accept(fieldName); - if (result.equals(FieldSelectorResult.LAZY_LOAD)) { + if (result == FieldSelectorResult.LAZY_LOAD) { return FieldSelectorResult.LATENT; } else { return result; } } }; Document doc = reader.doc(0, fieldSelector); assertTrue("doc is null and it shouldn't be", doc != null); Fieldable field = doc.getFieldable(DocHelper.LAZY_FIELD_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("field is not lazy and it should be", field.isLazy()); String value = field.stringValue(); assertTrue("value is null and it shouldn't be", value != null); assertTrue(value + " is not equal to " + DocHelper.LAZY_FIELD_TEXT, value.equals(DocHelper.LAZY_FIELD_TEXT) == true); assertTrue("calling stringValue() twice should give different references", field.stringValue() != field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF1_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF1_TEXT) == true); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF2_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == true); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF2_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF2_TEXT) == true); assertTrue("calling stringValue() twice should give different references", field.stringValue() != field.stringValue()); field = doc.getFieldable(DocHelper.LAZY_FIELD_BINARY_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("stringValue isn't null for lazy binary field", field.stringValue() == null); assertTrue("calling binaryValue() twice should give different references", field.getBinaryValue() != field.getBinaryValue()); byte [] bytes = field.getBinaryValue(); assertTrue("bytes is null and it shouldn't be", bytes != null); assertTrue("", DocHelper.LAZY_FIELD_BINARY_BYTES.length == bytes.length); for (int i = 0; i < bytes.length; i++) { assertTrue("byte[" + i + "] is mismatched", bytes[i] == DocHelper.LAZY_FIELD_BINARY_BYTES[i]); } } public void testLazyFieldsAfterClose() throws Exception { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader.size() == 1); Set<String> loadFieldNames = new HashSet<String>(); loadFieldNames.add(DocHelper.TEXT_FIELD_1_KEY); loadFieldNames.add(DocHelper.TEXT_FIELD_UTF1_KEY); Set<String> lazyFieldNames = new HashSet<String>(); lazyFieldNames.add(DocHelper.LARGE_LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_BINARY_KEY); lazyFieldNames.add(DocHelper.TEXT_FIELD_UTF2_KEY); SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames); Document doc = reader.doc(0, fieldSelector); assertTrue("doc is null and it shouldn't be", doc != null); Fieldable field = doc.getFieldable(DocHelper.LAZY_FIELD_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("field is not lazy and it should be", field.isLazy()); reader.close(); try { field.stringValue(); fail("did not hit AlreadyClosedException as expected"); } catch (AlreadyClosedException e) { // expected } } public void testLoadFirst() throws Exception { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader.size() == 1); LoadFirstFieldSelector fieldSelector = new LoadFirstFieldSelector(); Document doc = reader.doc(0, fieldSelector); assertTrue("doc is null and it shouldn't be", doc != null); int count = 0; List<Fieldable> l = doc.getFields(); for (final Fieldable fieldable : l ) { Field field = (Field) fieldable; assertTrue("field is null and it shouldn't be", field != null); String sv = field.stringValue(); assertTrue("sv is null and it shouldn't be", sv != null); count++; } assertTrue(count + " does not equal: " + 1, count == 1); } /** * Not really a test per se, but we should have some way of assessing whether this is worthwhile. * <p/> * Must test using a File based directory * * @throws Exception */ public void testLazyPerformance() throws Exception { String userName = System.getProperty("user.name"); File file = new File(TEMP_DIR, "lazyDir" + userName); _TestUtil.rmDir(file); FSDirectory tmpDir = FSDirectory.open(file); assertTrue(tmpDir != null); IndexWriterConfig conf = new IndexWriterConfig(TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE); ((LogMergePolicy) conf.getMergePolicy()).setUseCompoundFile(false); IndexWriter writer = new IndexWriter(tmpDir, conf); writer.addDocument(testDoc); writer.close(); assertTrue(fieldInfos != null); FieldsReader reader; long lazyTime = 0; long regularTime = 0; int length = 50; Set<String> lazyFieldNames = new HashSet<String>(); lazyFieldNames.add(DocHelper.LARGE_LAZY_FIELD_KEY); SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(Collections. <String> emptySet(), lazyFieldNames); for (int i = 0; i < length; i++) { reader = new FieldsReader(tmpDir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader.size() == 1); Document doc; doc = reader.doc(0, null);//Load all of them assertTrue("doc is null and it shouldn't be", doc != null); Fieldable field = doc.getFieldable(DocHelper.LARGE_LAZY_FIELD_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("field is lazy", field.isLazy() == false); String value; long start; long finish; start = System.currentTimeMillis(); //On my machine this was always 0ms. value = field.stringValue(); finish = System.currentTimeMillis(); assertTrue("value is null and it shouldn't be", value != null); regularTime += (finish - start); reader.close(); reader = null; doc = null; //Hmmm, are we still in cache??? System.gc(); reader = new FieldsReader(tmpDir, TEST_SEGMENT_NAME, fieldInfos); doc = reader.doc(0, fieldSelector); field = doc.getFieldable(DocHelper.LARGE_LAZY_FIELD_KEY); assertTrue("field is not lazy", field.isLazy() == true); start = System.currentTimeMillis(); //On my machine this took around 50 - 70ms value = field.stringValue(); finish = System.currentTimeMillis(); assertTrue("value is null and it shouldn't be", value != null); lazyTime += (finish - start); reader.close(); } if (VERBOSE) { System.out.println("Average Non-lazy time (should be very close to zero): " + regularTime / length + " ms for " + length + " reads"); System.out.println("Average Lazy Time (should be greater than zero): " + lazyTime / length + " ms for " + length + " reads"); } } public void testLoadSize() throws IOException { FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); Document doc; doc = reader.doc(0, new FieldSelector(){ public FieldSelectorResult accept(String fieldName) { if (fieldName.equals(DocHelper.TEXT_FIELD_1_KEY) || fieldName.equals(DocHelper.LAZY_FIELD_BINARY_KEY)) return FieldSelectorResult.SIZE; else if (fieldName.equals(DocHelper.TEXT_FIELD_3_KEY)) return FieldSelectorResult.LOAD; else return FieldSelectorResult.NO_LOAD; } }); Fieldable f1 = doc.getFieldable(DocHelper.TEXT_FIELD_1_KEY); Fieldable f3 = doc.getFieldable(DocHelper.TEXT_FIELD_3_KEY); Fieldable fb = doc.getFieldable(DocHelper.LAZY_FIELD_BINARY_KEY); assertTrue(f1.isBinary()); assertTrue(!f3.isBinary()); assertTrue(fb.isBinary()); assertSizeEquals(2*DocHelper.FIELD_1_TEXT.length(), f1.getBinaryValue()); assertEquals(DocHelper.FIELD_3_TEXT, f3.stringValue()); assertSizeEquals(DocHelper.LAZY_FIELD_BINARY_BYTES.length, fb.getBinaryValue()); reader.close(); } private void assertSizeEquals(int size, byte[] sizebytes) { assertEquals((byte) (size>>>24), sizebytes[0]); assertEquals((byte) (size>>>16), sizebytes[1]); assertEquals((byte) (size>>> 8), sizebytes[2]); assertEquals((byte) size , sizebytes[3]); } public static class FaultyFSDirectory extends Directory { FSDirectory fsDir; public FaultyFSDirectory(File dir) throws IOException { fsDir = FSDirectory.open(dir); lockFactory = fsDir.getLockFactory(); } @Override public IndexInput openInput(String name) throws IOException { return new FaultyIndexInput(fsDir.openInput(name)); } @Override public String[] listAll() throws IOException { return fsDir.listAll(); } @Override public boolean fileExists(String name) throws IOException { return fsDir.fileExists(name); } @Override public long fileModified(String name) throws IOException { return fsDir.fileModified(name); } @Override public void touchFile(String name) throws IOException { fsDir.touchFile(name); } @Override public void deleteFile(String name) throws IOException { fsDir.deleteFile(name); } @Override public long fileLength(String name) throws IOException { return fsDir.fileLength(name); } @Override public IndexOutput createOutput(String name) throws IOException { return fsDir.createOutput(name); } @Override public void close() throws IOException { fsDir.close(); } } private static class FaultyIndexInput extends BufferedIndexInput { IndexInput delegate; static boolean doFail; int count; private FaultyIndexInput(IndexInput delegate) { this.delegate = delegate; } private void simOutage() throws IOException { if (doFail && count++ % 2 == 1) { throw new IOException("Simulated network outage"); } } @Override public void readInternal(byte[] b, int offset, int length) throws IOException { simOutage(); delegate.readBytes(b, offset, length); } @Override public void seekInternal(long pos) throws IOException { //simOutage(); delegate.seek(pos); } @Override public long length() { return delegate.length(); } @Override public void close() throws IOException { delegate.close(); } @Override public Object clone() { return new FaultyIndexInput((IndexInput) delegate.clone()); } } // LUCENE-1262 public void testExceptions() throws Throwable { File indexDir = new File(TEMP_DIR, "testfieldswriterexceptions"); try { Directory dir = new FaultyFSDirectory(indexDir); IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig( TEST_VERSION_CURRENT, new WhitespaceAnalyzer(TEST_VERSION_CURRENT)).setOpenMode(OpenMode.CREATE)); for(int i=0;i<2;i++) writer.addDocument(testDoc); writer.optimize(); writer.close(); IndexReader reader = IndexReader.open(dir, true); FaultyIndexInput.doFail = true; boolean exc = false; for(int i=0;i<2;i++) { try { reader.document(i); } catch (IOException ioe) { // expected exc = true; } try { reader.document(i); } catch (IOException ioe) { // expected exc = true; } } assertTrue(exc); reader.close(); dir.close(); } finally { _TestUtil.rmDir(indexDir); } } }
false
true
public void testLatentFields() throws Exception { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader != null); assertTrue(reader.size() == 1); Set loadFieldNames = new HashSet(); loadFieldNames.add(DocHelper.TEXT_FIELD_1_KEY); loadFieldNames.add(DocHelper.TEXT_FIELD_UTF1_KEY); Set lazyFieldNames = new HashSet(); //new String[]{DocHelper.LARGE_LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_BINARY_KEY}; lazyFieldNames.add(DocHelper.LARGE_LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_BINARY_KEY); lazyFieldNames.add(DocHelper.TEXT_FIELD_UTF2_KEY); // Use LATENT instead of LAZY SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames) { public FieldSelectorResult accept(String fieldName) { final FieldSelectorResult result = super.accept(fieldName); if (result.equals(FieldSelectorResult.LAZY_LOAD)) { return FieldSelectorResult.LATENT; } else { return result; } } }; Document doc = reader.doc(0, fieldSelector); assertTrue("doc is null and it shouldn't be", doc != null); Fieldable field = doc.getFieldable(DocHelper.LAZY_FIELD_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("field is not lazy and it should be", field.isLazy()); String value = field.stringValue(); assertTrue("value is null and it shouldn't be", value != null); assertTrue(value + " is not equal to " + DocHelper.LAZY_FIELD_TEXT, value.equals(DocHelper.LAZY_FIELD_TEXT) == true); assertTrue("calling stringValue() twice should give different references", field.stringValue() != field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF1_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF1_TEXT) == true); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF2_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == true); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF2_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF2_TEXT) == true); assertTrue("calling stringValue() twice should give different references", field.stringValue() != field.stringValue()); field = doc.getFieldable(DocHelper.LAZY_FIELD_BINARY_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("stringValue isn't null for lazy binary field", field.stringValue() == null); assertTrue("calling binaryValue() twice should give different references", field.getBinaryValue() != field.getBinaryValue()); byte [] bytes = field.getBinaryValue(); assertTrue("bytes is null and it shouldn't be", bytes != null); assertTrue("", DocHelper.LAZY_FIELD_BINARY_BYTES.length == bytes.length); for (int i = 0; i < bytes.length; i++) { assertTrue("byte[" + i + "] is mismatched", bytes[i] == DocHelper.LAZY_FIELD_BINARY_BYTES[i]); } }
public void testLatentFields() throws Exception { assertTrue(dir != null); assertTrue(fieldInfos != null); FieldsReader reader = new FieldsReader(dir, TEST_SEGMENT_NAME, fieldInfos); assertTrue(reader != null); assertTrue(reader.size() == 1); Set<String> loadFieldNames = new HashSet<String>(); loadFieldNames.add(DocHelper.TEXT_FIELD_1_KEY); loadFieldNames.add(DocHelper.TEXT_FIELD_UTF1_KEY); Set<String> lazyFieldNames = new HashSet<String>(); //new String[]{DocHelper.LARGE_LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_KEY, DocHelper.LAZY_FIELD_BINARY_KEY}; lazyFieldNames.add(DocHelper.LARGE_LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_KEY); lazyFieldNames.add(DocHelper.LAZY_FIELD_BINARY_KEY); lazyFieldNames.add(DocHelper.TEXT_FIELD_UTF2_KEY); // Use LATENT instead of LAZY SetBasedFieldSelector fieldSelector = new SetBasedFieldSelector(loadFieldNames, lazyFieldNames) { public FieldSelectorResult accept(String fieldName) { final FieldSelectorResult result = super.accept(fieldName); if (result == FieldSelectorResult.LAZY_LOAD) { return FieldSelectorResult.LATENT; } else { return result; } } }; Document doc = reader.doc(0, fieldSelector); assertTrue("doc is null and it shouldn't be", doc != null); Fieldable field = doc.getFieldable(DocHelper.LAZY_FIELD_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("field is not lazy and it should be", field.isLazy()); String value = field.stringValue(); assertTrue("value is null and it shouldn't be", value != null); assertTrue(value + " is not equal to " + DocHelper.LAZY_FIELD_TEXT, value.equals(DocHelper.LAZY_FIELD_TEXT) == true); assertTrue("calling stringValue() twice should give different references", field.stringValue() != field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF1_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == false); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF1_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF1_TEXT) == true); assertTrue("calling stringValue() twice should give same reference", field.stringValue() == field.stringValue()); field = doc.getFieldable(DocHelper.TEXT_FIELD_UTF2_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("Field is lazy and it should not be", field.isLazy() == true); assertTrue(field.stringValue() + " is not equal to " + DocHelper.FIELD_UTF2_TEXT, field.stringValue().equals(DocHelper.FIELD_UTF2_TEXT) == true); assertTrue("calling stringValue() twice should give different references", field.stringValue() != field.stringValue()); field = doc.getFieldable(DocHelper.LAZY_FIELD_BINARY_KEY); assertTrue("field is null and it shouldn't be", field != null); assertTrue("stringValue isn't null for lazy binary field", field.stringValue() == null); assertTrue("calling binaryValue() twice should give different references", field.getBinaryValue() != field.getBinaryValue()); byte [] bytes = field.getBinaryValue(); assertTrue("bytes is null and it shouldn't be", bytes != null); assertTrue("", DocHelper.LAZY_FIELD_BINARY_BYTES.length == bytes.length); for (int i = 0; i < bytes.length; i++) { assertTrue("byte[" + i + "] is mismatched", bytes[i] == DocHelper.LAZY_FIELD_BINARY_BYTES[i]); } }
diff --git a/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java b/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java index 6a83630bf..51fdf9921 100644 --- a/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java +++ b/modules/cpr/src/main/java/org/atmosphere/container/JettyWebSocketUtil.java @@ -1,106 +1,107 @@ /* * Copyright 2012 Jeanfrancois Arcand * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.atmosphere.container; import org.atmosphere.cpr.ApplicationConfig; import org.atmosphere.cpr.AsynchronousProcessor; import org.atmosphere.cpr.AtmosphereServlet; import org.atmosphere.websocket.WebSocket; import org.eclipse.jetty.websocket.WebSocketFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import static org.atmosphere.cpr.HeaderConfig.WEBSOCKET_UPGRADE; public class JettyWebSocketUtil { private static final Logger logger = LoggerFactory.getLogger(JettyWebSocketUtil.class); public final static AtmosphereServlet.Action doService(AsynchronousProcessor cometSupport, HttpServletRequest req, HttpServletResponse res, WebSocketFactory webSocketFactory) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().split(","); for (String upgrade : e) { if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) { webSocketEnabled = true; break; } } } Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED); if (b == null) b = Boolean.FALSE; if (!webSocketEnabled) { + logger.error("Invalid WebSocketRequest: No Connection header with browser {}.", req.getHeader("User-Agent")); return null; } else { if (webSocketFactory != null && !b) { req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true); webSocketFactory.acceptWebSocket(req, res); return new AtmosphereServlet.Action(); } AtmosphereServlet.Action action = cometSupport.suspended(req, res); if (action.type == AtmosphereServlet.Action.TYPE.SUSPEND) { logger.debug("Suspending response: {}", res); } else if (action.type == AtmosphereServlet.Action.TYPE.RESUME) { logger.debug("Resume response: {}", res); req.setAttribute(WebSocket.WEBSOCKET_RESUME, true); } return action; } } public final static WebSocketFactory getFactory(final AtmosphereServlet.AtmosphereConfig config) { WebSocketFactory webSocketFactory = new WebSocketFactory(new WebSocketFactory.Acceptor() { public boolean checkOrigin(HttpServletRequest request, String origin) { // Allow all origins logger.debug("WebSocket-checkOrigin request {} with origin {}", request.getRequestURI(), origin); return true; } public org.eclipse.jetty.websocket.WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { logger.debug("WebSocket-connect request {} with protocol {}", request.getRequestURI(), protocol); return new JettyWebSocketHandler(request, config.getServlet(), config.getServlet().getWebSocketProtocol()); } }); int bufferSize = 8192; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE) != null) { bufferSize = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE)); } logger.info("WebSocket Buffer side {}", bufferSize); webSocketFactory.setBufferSize(bufferSize); int timeOut = 5 * 60000; if (config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME) != null) { timeOut = Integer.valueOf(config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME)); } logger.info("WebSocket idle timeout {}", timeOut); webSocketFactory.setMaxIdleTime(timeOut); return webSocketFactory; } }
true
true
public final static AtmosphereServlet.Action doService(AsynchronousProcessor cometSupport, HttpServletRequest req, HttpServletResponse res, WebSocketFactory webSocketFactory) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().split(","); for (String upgrade : e) { if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) { webSocketEnabled = true; break; } } } Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED); if (b == null) b = Boolean.FALSE; if (!webSocketEnabled) { return null; } else { if (webSocketFactory != null && !b) { req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true); webSocketFactory.acceptWebSocket(req, res); return new AtmosphereServlet.Action(); } AtmosphereServlet.Action action = cometSupport.suspended(req, res); if (action.type == AtmosphereServlet.Action.TYPE.SUSPEND) { logger.debug("Suspending response: {}", res); } else if (action.type == AtmosphereServlet.Action.TYPE.RESUME) { logger.debug("Resume response: {}", res); req.setAttribute(WebSocket.WEBSOCKET_RESUME, true); } return action; } }
public final static AtmosphereServlet.Action doService(AsynchronousProcessor cometSupport, HttpServletRequest req, HttpServletResponse res, WebSocketFactory webSocketFactory) throws IOException, ServletException { boolean webSocketEnabled = false; if (req.getHeaders("Connection") != null && req.getHeaders("Connection").hasMoreElements()) { String[] e = req.getHeaders("Connection").nextElement().split(","); for (String upgrade : e) { if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) { webSocketEnabled = true; break; } } } Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED); if (b == null) b = Boolean.FALSE; if (!webSocketEnabled) { logger.error("Invalid WebSocketRequest: No Connection header with browser {}.", req.getHeader("User-Agent")); return null; } else { if (webSocketFactory != null && !b) { req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true); webSocketFactory.acceptWebSocket(req, res); return new AtmosphereServlet.Action(); } AtmosphereServlet.Action action = cometSupport.suspended(req, res); if (action.type == AtmosphereServlet.Action.TYPE.SUSPEND) { logger.debug("Suspending response: {}", res); } else if (action.type == AtmosphereServlet.Action.TYPE.RESUME) { logger.debug("Resume response: {}", res); req.setAttribute(WebSocket.WEBSOCKET_RESUME, true); } return action; } }
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaBootstrapEditor.java b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaBootstrapEditor.java index 25657cbc..6c94beb7 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaBootstrapEditor.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/JcaBootstrapEditor.java @@ -1,165 +1,165 @@ package org.jboss.as.console.client.shared.subsys.jca; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import org.jboss.as.console.client.Console; import org.jboss.as.console.client.shared.help.FormHelpPanel; import org.jboss.as.console.client.shared.subsys.Baseadress; import org.jboss.as.console.client.shared.subsys.jca.model.JcaBootstrapContext; import org.jboss.as.console.client.shared.subsys.jca.model.JcaWorkmanager; import org.jboss.as.console.client.shared.viewframework.builder.MultipleToOneLayout; import org.jboss.as.console.client.widgets.forms.FormToolStrip; import org.jboss.ballroom.client.widgets.forms.ComboBoxItem; import org.jboss.ballroom.client.widgets.forms.Form; import org.jboss.ballroom.client.widgets.forms.TextItem; import org.jboss.ballroom.client.widgets.tables.DefaultCellTable; import org.jboss.ballroom.client.widgets.tools.ToolButton; import org.jboss.ballroom.client.widgets.tools.ToolStrip; import org.jboss.ballroom.client.widgets.window.Feedback; import org.jboss.dmr.client.ModelNode; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Heiko Braun * @date 11/29/11 */ public class JcaBootstrapEditor { private ListDataProvider<JcaBootstrapContext> dataProvider; private DefaultCellTable<JcaBootstrapContext> table ; private ComboBoxItem workmanager; private JcaPresenter presenter; public JcaBootstrapEditor(JcaPresenter presenter) { this.presenter = presenter; } Widget asWidget() { final Form<JcaBootstrapContext> form = new Form<JcaBootstrapContext>(JcaBootstrapContext.class); form.setEnabled(false); table = new DefaultCellTable<JcaBootstrapContext>(10); dataProvider = new ListDataProvider<JcaBootstrapContext>(); dataProvider.addDataDisplay(table); TextColumn<JcaBootstrapContext> name = new TextColumn<JcaBootstrapContext>() { @Override public String getValue(JcaBootstrapContext record) { return record.getName(); } }; table.addColumn(name, "Name"); ToolStrip topLevelTools = new ToolStrip(); topLevelTools.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_add(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewContextDialogue(); } })); topLevelTools.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_remove(), new ClickHandler() { @Override public void onClick(ClickEvent event) { Feedback.confirm( Console.MESSAGES.deleteTitle("Bootstrap Context"), Console.MESSAGES.deleteConfirm("Bootstrap Context"), new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if(isConfirmed) presenter.onDeleteBootstrapContext(form.getEditedEntity()); } }); } })); TextItem contextName = new TextItem("name", "Name"); workmanager = new ComboBoxItem("workmanager", "Work Manager"); form.setFields(contextName, workmanager); form.setNumColumns(2); form.bind(table); SafeHtmlBuilder description = new SafeHtmlBuilder(); description.appendHtmlConstant(Console.CONSTANTS.subsys_jca_boostrap_config_desc()); FormToolStrip<JcaBootstrapContext> formTools = new FormToolStrip<JcaBootstrapContext>( form, new FormToolStrip.FormCallback<JcaBootstrapContext>() { @Override public void onSave(Map<String, Object> changeset) { presenter.onSaveBootstrapContext(form.getEditedEntity(), changeset); } @Override public void onDelete(JcaBootstrapContext entity) { } } ); formTools.providesDeleteOp(false); final FormHelpPanel helpPanel = new FormHelpPanel( new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = Baseadress.get(); address.add("subsystem", "jca"); address.add("bootstrap-context", "*"); return address; } }, form ); VerticalPanel formPanel = new VerticalPanel(); formPanel.setStyleName("fill-layout-width"); formPanel.add(formTools.asWidget()); formPanel.add(helpPanel.asWidget()); formPanel.add(form.asWidget()); Widget panel = new MultipleToOneLayout() .setPlain(true) .setTitle("Bootstrap") .setHeadline("JCA Bootstrap Contexts") .setDescription(description.toSafeHtml()) .setMaster(Console.MESSAGES.available("Bootstrap Context"), table) - .setTopLevelTools(topLevelTools.asWidget()) + .setMasterTools(topLevelTools.asWidget()) .setDetail(Console.CONSTANTS.common_label_selection(), formPanel) .build(); return panel; } public void setManagers(List<JcaWorkmanager> managers) { List<String> names = new ArrayList<String>(managers.size()); for(JcaWorkmanager manager : managers) names.add(manager.getName()); workmanager.setValueMap(names); } public void setContexts(List<JcaBootstrapContext> contexts) { dataProvider.setList(contexts); if(!contexts.isEmpty()) table.getSelectionModel().setSelected(contexts.get(0), true); } }
true
true
Widget asWidget() { final Form<JcaBootstrapContext> form = new Form<JcaBootstrapContext>(JcaBootstrapContext.class); form.setEnabled(false); table = new DefaultCellTable<JcaBootstrapContext>(10); dataProvider = new ListDataProvider<JcaBootstrapContext>(); dataProvider.addDataDisplay(table); TextColumn<JcaBootstrapContext> name = new TextColumn<JcaBootstrapContext>() { @Override public String getValue(JcaBootstrapContext record) { return record.getName(); } }; table.addColumn(name, "Name"); ToolStrip topLevelTools = new ToolStrip(); topLevelTools.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_add(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewContextDialogue(); } })); topLevelTools.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_remove(), new ClickHandler() { @Override public void onClick(ClickEvent event) { Feedback.confirm( Console.MESSAGES.deleteTitle("Bootstrap Context"), Console.MESSAGES.deleteConfirm("Bootstrap Context"), new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if(isConfirmed) presenter.onDeleteBootstrapContext(form.getEditedEntity()); } }); } })); TextItem contextName = new TextItem("name", "Name"); workmanager = new ComboBoxItem("workmanager", "Work Manager"); form.setFields(contextName, workmanager); form.setNumColumns(2); form.bind(table); SafeHtmlBuilder description = new SafeHtmlBuilder(); description.appendHtmlConstant(Console.CONSTANTS.subsys_jca_boostrap_config_desc()); FormToolStrip<JcaBootstrapContext> formTools = new FormToolStrip<JcaBootstrapContext>( form, new FormToolStrip.FormCallback<JcaBootstrapContext>() { @Override public void onSave(Map<String, Object> changeset) { presenter.onSaveBootstrapContext(form.getEditedEntity(), changeset); } @Override public void onDelete(JcaBootstrapContext entity) { } } ); formTools.providesDeleteOp(false); final FormHelpPanel helpPanel = new FormHelpPanel( new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = Baseadress.get(); address.add("subsystem", "jca"); address.add("bootstrap-context", "*"); return address; } }, form ); VerticalPanel formPanel = new VerticalPanel(); formPanel.setStyleName("fill-layout-width"); formPanel.add(formTools.asWidget()); formPanel.add(helpPanel.asWidget()); formPanel.add(form.asWidget()); Widget panel = new MultipleToOneLayout() .setPlain(true) .setTitle("Bootstrap") .setHeadline("JCA Bootstrap Contexts") .setDescription(description.toSafeHtml()) .setMaster(Console.MESSAGES.available("Bootstrap Context"), table) .setTopLevelTools(topLevelTools.asWidget()) .setDetail(Console.CONSTANTS.common_label_selection(), formPanel) .build(); return panel; }
Widget asWidget() { final Form<JcaBootstrapContext> form = new Form<JcaBootstrapContext>(JcaBootstrapContext.class); form.setEnabled(false); table = new DefaultCellTable<JcaBootstrapContext>(10); dataProvider = new ListDataProvider<JcaBootstrapContext>(); dataProvider.addDataDisplay(table); TextColumn<JcaBootstrapContext> name = new TextColumn<JcaBootstrapContext>() { @Override public String getValue(JcaBootstrapContext record) { return record.getName(); } }; table.addColumn(name, "Name"); ToolStrip topLevelTools = new ToolStrip(); topLevelTools.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_add(), new ClickHandler() { @Override public void onClick(ClickEvent event) { presenter.launchNewContextDialogue(); } })); topLevelTools.addToolButtonRight(new ToolButton(Console.CONSTANTS.common_label_remove(), new ClickHandler() { @Override public void onClick(ClickEvent event) { Feedback.confirm( Console.MESSAGES.deleteTitle("Bootstrap Context"), Console.MESSAGES.deleteConfirm("Bootstrap Context"), new Feedback.ConfirmationHandler() { @Override public void onConfirmation(boolean isConfirmed) { if(isConfirmed) presenter.onDeleteBootstrapContext(form.getEditedEntity()); } }); } })); TextItem contextName = new TextItem("name", "Name"); workmanager = new ComboBoxItem("workmanager", "Work Manager"); form.setFields(contextName, workmanager); form.setNumColumns(2); form.bind(table); SafeHtmlBuilder description = new SafeHtmlBuilder(); description.appendHtmlConstant(Console.CONSTANTS.subsys_jca_boostrap_config_desc()); FormToolStrip<JcaBootstrapContext> formTools = new FormToolStrip<JcaBootstrapContext>( form, new FormToolStrip.FormCallback<JcaBootstrapContext>() { @Override public void onSave(Map<String, Object> changeset) { presenter.onSaveBootstrapContext(form.getEditedEntity(), changeset); } @Override public void onDelete(JcaBootstrapContext entity) { } } ); formTools.providesDeleteOp(false); final FormHelpPanel helpPanel = new FormHelpPanel( new FormHelpPanel.AddressCallback() { @Override public ModelNode getAddress() { ModelNode address = Baseadress.get(); address.add("subsystem", "jca"); address.add("bootstrap-context", "*"); return address; } }, form ); VerticalPanel formPanel = new VerticalPanel(); formPanel.setStyleName("fill-layout-width"); formPanel.add(formTools.asWidget()); formPanel.add(helpPanel.asWidget()); formPanel.add(form.asWidget()); Widget panel = new MultipleToOneLayout() .setPlain(true) .setTitle("Bootstrap") .setHeadline("JCA Bootstrap Contexts") .setDescription(description.toSafeHtml()) .setMaster(Console.MESSAGES.available("Bootstrap Context"), table) .setMasterTools(topLevelTools.asWidget()) .setDetail(Console.CONSTANTS.common_label_selection(), formPanel) .build(); return panel; }
diff --git a/src/TorperfProcessor.java b/src/TorperfProcessor.java index d2bb050..b851249 100644 --- a/src/TorperfProcessor.java +++ b/src/TorperfProcessor.java @@ -1,152 +1,159 @@ import java.io.*; import java.text.*; import java.util.*; import java.util.logging.*; public class TorperfProcessor { public TorperfProcessor(String torperfDirectory) { Logger logger = Logger.getLogger(TorperfProcessor.class.getName()); File rawFile = new File("stats/torperf-raw"); File statsFile = new File("stats/torperf-stats"); File torperfDir = new File(torperfDirectory); SortedMap<String, String> rawObs = new TreeMap<String, String>(); SortedMap<String, String> stats = new TreeMap<String, String>(); try { if (rawFile.exists()) { logger.fine("Reading file " + rawFile.getAbsolutePath() + "..."); BufferedReader br = new BufferedReader(new FileReader(rawFile)); String line = br.readLine(); // ignore header while ((line = br.readLine()) != null) { if (line.split(",").length != 4) { logger.warning("Corrupt line in " + rawFile.getAbsolutePath() + "!"); break; } String key = line.substring(0, line.lastIndexOf(",")); + if (line.substring(line.lastIndexOf(",") + 1).startsWith("-")) { + /* If completion time is negative, this is because we had an + * integer overflow bug. Fix this. */ + long newValue = Long.parseLong(line.substring( + line.lastIndexOf(",") + 1)) + 100000000L; + line = key + "," + newValue; + } rawObs.put(key, line); } br.close(); logger.fine("Finished reading file " + rawFile.getAbsolutePath() + "."); } if (statsFile.exists()) { logger.fine("Reading file " + statsFile.getAbsolutePath() + "..."); BufferedReader br = new BufferedReader(new FileReader(statsFile)); String line = br.readLine(); // ignore header while ((line = br.readLine()) != null) { String key = line.split(",")[0] + "," + line.split(",")[1]; stats.put(key, line); } br.close(); logger.fine("Finished reading file " + statsFile.getAbsolutePath() + "."); } if (torperfDir.exists()) { logger.fine("Importing files in " + torperfDirectory + "/..."); Stack<File> filesInInputDir = new Stack<File>(); filesInInputDir.add(torperfDir); while (!filesInInputDir.isEmpty()) { File pop = filesInInputDir.pop(); if (pop.isDirectory()) { for (File f : pop.listFiles()) { filesInInputDir.add(f); - } + } } else { String source = pop.getName().substring(0, pop.getName().indexOf(".")); BufferedReader br = new BufferedReader(new FileReader(pop)); String line = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); while ((line = br.readLine()) != null) { String[] parts = line.split(" "); // remove defective lines as they occurred on gabelmoo as well // as and incomplete downloads if (parts.length == 20 && parts[0].length() == 10 && !parts[16].equals("0")) { long startSec = Long.parseLong(parts[0]); String dateTime = formatter.format( new Date(startSec * 1000L)); - long completeMillis = Long.parseLong(parts[16].substring(5)) + long completeMillis = Long.parseLong(parts[16]) * 1000L + Long.parseLong(parts[17]) / 1000L - - Long.parseLong(parts[0].substring(5)) * 1000L + - Long.parseLong(parts[0]) * 1000L + Long.parseLong(parts[1]) / 1000L; String key = source + "," + dateTime; String value = key + "," + completeMillis; if (!rawObs.containsKey(key)) { rawObs.put(key, value); // TODO if torperf-stats generation takes long, compile // list of dates that have changes for torperf-stats and // only re-generate those } } } br.close(); } } logger.fine("Finished importing files in " + torperfDirectory + "/."); } if (rawObs.size() > 0) { logger.fine("Writing file " + rawFile.getAbsolutePath() + "..."); rawFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(rawFile)); bw.append("source,date,start,completemillis\n"); String tempSourceDate = null; Iterator<Map.Entry<String, String>> it = rawObs.entrySet().iterator(); List<Long> dlTimes = new ArrayList<Long>(); boolean haveWrittenFinalLine = false; while (it.hasNext() || !haveWrittenFinalLine) { Map.Entry<String, String> next = it.hasNext() ? it.next() : null; if (tempSourceDate != null && (next == null || !(next.getValue().split(",")[0] + "," + next.getValue().split(",")[1]).equals(tempSourceDate))) { if (dlTimes.size() > 4) { Collections.sort(dlTimes); long q1 = dlTimes.get(dlTimes.size() / 4 - 1); long md = dlTimes.get(dlTimes.size() / 2 - 1); long q3 = dlTimes.get(dlTimes.size() * 3 / 4 - 1); stats.put(tempSourceDate, tempSourceDate + "," + q1 + "," + md + "," + q3); } dlTimes.clear(); if (next == null) { haveWrittenFinalLine = true; } } if (next != null) { bw.append(next.getValue() + "\n"); String[] parts = next.getValue().split(","); tempSourceDate = parts[0] + "," + parts[1]; dlTimes.add(Long.parseLong(parts[3])); } } bw.close(); logger.fine("Finished writing file " + rawFile.getAbsolutePath() + "."); } if (stats.size() > 0) { logger.fine("Writing file " + statsFile.getAbsolutePath() + "..."); statsFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(statsFile)); bw.append("source,date,q1,md,q3\n"); // TODO should we handle missing days? for (String s : stats.values()) { bw.append(s + "\n"); } bw.close(); logger.fine("Finished writing file " + statsFile.getAbsolutePath() + "."); } } catch (IOException e) { logger.log(Level.WARNING, "Failed writing " + rawFile.getAbsolutePath() + " or " + statsFile.getAbsolutePath() + "!", e); } } }
false
true
public TorperfProcessor(String torperfDirectory) { Logger logger = Logger.getLogger(TorperfProcessor.class.getName()); File rawFile = new File("stats/torperf-raw"); File statsFile = new File("stats/torperf-stats"); File torperfDir = new File(torperfDirectory); SortedMap<String, String> rawObs = new TreeMap<String, String>(); SortedMap<String, String> stats = new TreeMap<String, String>(); try { if (rawFile.exists()) { logger.fine("Reading file " + rawFile.getAbsolutePath() + "..."); BufferedReader br = new BufferedReader(new FileReader(rawFile)); String line = br.readLine(); // ignore header while ((line = br.readLine()) != null) { if (line.split(",").length != 4) { logger.warning("Corrupt line in " + rawFile.getAbsolutePath() + "!"); break; } String key = line.substring(0, line.lastIndexOf(",")); rawObs.put(key, line); } br.close(); logger.fine("Finished reading file " + rawFile.getAbsolutePath() + "."); } if (statsFile.exists()) { logger.fine("Reading file " + statsFile.getAbsolutePath() + "..."); BufferedReader br = new BufferedReader(new FileReader(statsFile)); String line = br.readLine(); // ignore header while ((line = br.readLine()) != null) { String key = line.split(",")[0] + "," + line.split(",")[1]; stats.put(key, line); } br.close(); logger.fine("Finished reading file " + statsFile.getAbsolutePath() + "."); } if (torperfDir.exists()) { logger.fine("Importing files in " + torperfDirectory + "/..."); Stack<File> filesInInputDir = new Stack<File>(); filesInInputDir.add(torperfDir); while (!filesInInputDir.isEmpty()) { File pop = filesInInputDir.pop(); if (pop.isDirectory()) { for (File f : pop.listFiles()) { filesInInputDir.add(f); } } else { String source = pop.getName().substring(0, pop.getName().indexOf(".")); BufferedReader br = new BufferedReader(new FileReader(pop)); String line = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); while ((line = br.readLine()) != null) { String[] parts = line.split(" "); // remove defective lines as they occurred on gabelmoo as well // as and incomplete downloads if (parts.length == 20 && parts[0].length() == 10 && !parts[16].equals("0")) { long startSec = Long.parseLong(parts[0]); String dateTime = formatter.format( new Date(startSec * 1000L)); long completeMillis = Long.parseLong(parts[16].substring(5)) * 1000L + Long.parseLong(parts[17]) / 1000L - Long.parseLong(parts[0].substring(5)) * 1000L + Long.parseLong(parts[1]) / 1000L; String key = source + "," + dateTime; String value = key + "," + completeMillis; if (!rawObs.containsKey(key)) { rawObs.put(key, value); // TODO if torperf-stats generation takes long, compile // list of dates that have changes for torperf-stats and // only re-generate those } } } br.close(); } } logger.fine("Finished importing files in " + torperfDirectory + "/."); } if (rawObs.size() > 0) { logger.fine("Writing file " + rawFile.getAbsolutePath() + "..."); rawFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(rawFile)); bw.append("source,date,start,completemillis\n"); String tempSourceDate = null; Iterator<Map.Entry<String, String>> it = rawObs.entrySet().iterator(); List<Long> dlTimes = new ArrayList<Long>(); boolean haveWrittenFinalLine = false; while (it.hasNext() || !haveWrittenFinalLine) { Map.Entry<String, String> next = it.hasNext() ? it.next() : null; if (tempSourceDate != null && (next == null || !(next.getValue().split(",")[0] + "," + next.getValue().split(",")[1]).equals(tempSourceDate))) { if (dlTimes.size() > 4) { Collections.sort(dlTimes); long q1 = dlTimes.get(dlTimes.size() / 4 - 1); long md = dlTimes.get(dlTimes.size() / 2 - 1); long q3 = dlTimes.get(dlTimes.size() * 3 / 4 - 1); stats.put(tempSourceDate, tempSourceDate + "," + q1 + "," + md + "," + q3); } dlTimes.clear(); if (next == null) { haveWrittenFinalLine = true; } } if (next != null) { bw.append(next.getValue() + "\n"); String[] parts = next.getValue().split(","); tempSourceDate = parts[0] + "," + parts[1]; dlTimes.add(Long.parseLong(parts[3])); } } bw.close(); logger.fine("Finished writing file " + rawFile.getAbsolutePath() + "."); } if (stats.size() > 0) { logger.fine("Writing file " + statsFile.getAbsolutePath() + "..."); statsFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(statsFile)); bw.append("source,date,q1,md,q3\n"); // TODO should we handle missing days? for (String s : stats.values()) { bw.append(s + "\n"); } bw.close(); logger.fine("Finished writing file " + statsFile.getAbsolutePath() + "."); } } catch (IOException e) { logger.log(Level.WARNING, "Failed writing " + rawFile.getAbsolutePath() + " or " + statsFile.getAbsolutePath() + "!", e); } }
public TorperfProcessor(String torperfDirectory) { Logger logger = Logger.getLogger(TorperfProcessor.class.getName()); File rawFile = new File("stats/torperf-raw"); File statsFile = new File("stats/torperf-stats"); File torperfDir = new File(torperfDirectory); SortedMap<String, String> rawObs = new TreeMap<String, String>(); SortedMap<String, String> stats = new TreeMap<String, String>(); try { if (rawFile.exists()) { logger.fine("Reading file " + rawFile.getAbsolutePath() + "..."); BufferedReader br = new BufferedReader(new FileReader(rawFile)); String line = br.readLine(); // ignore header while ((line = br.readLine()) != null) { if (line.split(",").length != 4) { logger.warning("Corrupt line in " + rawFile.getAbsolutePath() + "!"); break; } String key = line.substring(0, line.lastIndexOf(",")); if (line.substring(line.lastIndexOf(",") + 1).startsWith("-")) { /* If completion time is negative, this is because we had an * integer overflow bug. Fix this. */ long newValue = Long.parseLong(line.substring( line.lastIndexOf(",") + 1)) + 100000000L; line = key + "," + newValue; } rawObs.put(key, line); } br.close(); logger.fine("Finished reading file " + rawFile.getAbsolutePath() + "."); } if (statsFile.exists()) { logger.fine("Reading file " + statsFile.getAbsolutePath() + "..."); BufferedReader br = new BufferedReader(new FileReader(statsFile)); String line = br.readLine(); // ignore header while ((line = br.readLine()) != null) { String key = line.split(",")[0] + "," + line.split(",")[1]; stats.put(key, line); } br.close(); logger.fine("Finished reading file " + statsFile.getAbsolutePath() + "."); } if (torperfDir.exists()) { logger.fine("Importing files in " + torperfDirectory + "/..."); Stack<File> filesInInputDir = new Stack<File>(); filesInInputDir.add(torperfDir); while (!filesInInputDir.isEmpty()) { File pop = filesInInputDir.pop(); if (pop.isDirectory()) { for (File f : pop.listFiles()) { filesInInputDir.add(f); } } else { String source = pop.getName().substring(0, pop.getName().indexOf(".")); BufferedReader br = new BufferedReader(new FileReader(pop)); String line = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); while ((line = br.readLine()) != null) { String[] parts = line.split(" "); // remove defective lines as they occurred on gabelmoo as well // as and incomplete downloads if (parts.length == 20 && parts[0].length() == 10 && !parts[16].equals("0")) { long startSec = Long.parseLong(parts[0]); String dateTime = formatter.format( new Date(startSec * 1000L)); long completeMillis = Long.parseLong(parts[16]) * 1000L + Long.parseLong(parts[17]) / 1000L - Long.parseLong(parts[0]) * 1000L + Long.parseLong(parts[1]) / 1000L; String key = source + "," + dateTime; String value = key + "," + completeMillis; if (!rawObs.containsKey(key)) { rawObs.put(key, value); // TODO if torperf-stats generation takes long, compile // list of dates that have changes for torperf-stats and // only re-generate those } } } br.close(); } } logger.fine("Finished importing files in " + torperfDirectory + "/."); } if (rawObs.size() > 0) { logger.fine("Writing file " + rawFile.getAbsolutePath() + "..."); rawFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(rawFile)); bw.append("source,date,start,completemillis\n"); String tempSourceDate = null; Iterator<Map.Entry<String, String>> it = rawObs.entrySet().iterator(); List<Long> dlTimes = new ArrayList<Long>(); boolean haveWrittenFinalLine = false; while (it.hasNext() || !haveWrittenFinalLine) { Map.Entry<String, String> next = it.hasNext() ? it.next() : null; if (tempSourceDate != null && (next == null || !(next.getValue().split(",")[0] + "," + next.getValue().split(",")[1]).equals(tempSourceDate))) { if (dlTimes.size() > 4) { Collections.sort(dlTimes); long q1 = dlTimes.get(dlTimes.size() / 4 - 1); long md = dlTimes.get(dlTimes.size() / 2 - 1); long q3 = dlTimes.get(dlTimes.size() * 3 / 4 - 1); stats.put(tempSourceDate, tempSourceDate + "," + q1 + "," + md + "," + q3); } dlTimes.clear(); if (next == null) { haveWrittenFinalLine = true; } } if (next != null) { bw.append(next.getValue() + "\n"); String[] parts = next.getValue().split(","); tempSourceDate = parts[0] + "," + parts[1]; dlTimes.add(Long.parseLong(parts[3])); } } bw.close(); logger.fine("Finished writing file " + rawFile.getAbsolutePath() + "."); } if (stats.size() > 0) { logger.fine("Writing file " + statsFile.getAbsolutePath() + "..."); statsFile.getParentFile().mkdirs(); BufferedWriter bw = new BufferedWriter(new FileWriter(statsFile)); bw.append("source,date,q1,md,q3\n"); // TODO should we handle missing days? for (String s : stats.values()) { bw.append(s + "\n"); } bw.close(); logger.fine("Finished writing file " + statsFile.getAbsolutePath() + "."); } } catch (IOException e) { logger.log(Level.WARNING, "Failed writing " + rawFile.getAbsolutePath() + " or " + statsFile.getAbsolutePath() + "!", e); } }
diff --git a/astrid/src/com/todoroo/astrid/activity/EditPreferences.java b/astrid/src/com/todoroo/astrid/activity/EditPreferences.java index 4f15ef673..a32386d0e 100644 --- a/astrid/src/com/todoroo/astrid/activity/EditPreferences.java +++ b/astrid/src/com/todoroo/astrid/activity/EditPreferences.java @@ -1,769 +1,769 @@ /** * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.activity; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import org.weloveastrid.rmilk.MilkPreferences; import org.weloveastrid.rmilk.MilkUtilities; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Resources; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceCategory; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.text.TextUtils; import android.widget.Toast; import com.crittercism.app.Crittercism; import com.timsu.astrid.R; import com.todoroo.andlib.service.Autowired; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.service.DependencyInjectionService; import com.todoroo.andlib.sql.Criterion; import com.todoroo.andlib.utility.AndroidUtilities; import com.todoroo.andlib.utility.DialogUtilities; import com.todoroo.andlib.utility.Preferences; import com.todoroo.andlib.utility.TodorooPreferenceActivity; import com.todoroo.astrid.actfm.ActFmLoginActivity; import com.todoroo.astrid.actfm.ActFmPreferences; import com.todoroo.astrid.actfm.sync.ActFmPreferenceService; import com.todoroo.astrid.api.AstridApiConstants; import com.todoroo.astrid.dao.Database; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.files.FileExplore; import com.todoroo.astrid.files.FileMetadata; import com.todoroo.astrid.gtasks.GtasksPreferences; import com.todoroo.astrid.helper.MetadataHelper; import com.todoroo.astrid.producteev.ProducteevPreferences; import com.todoroo.astrid.producteev.ProducteevUtilities; import com.todoroo.astrid.service.AddOnService; import com.todoroo.astrid.service.MarketStrategy.AmazonMarketStrategy; import com.todoroo.astrid.service.StartupService; import com.todoroo.astrid.service.StatisticsConstants; import com.todoroo.astrid.service.StatisticsService; import com.todoroo.astrid.service.TaskService; import com.todoroo.astrid.sync.SyncProviderPreferences; import com.todoroo.astrid.ui.ContactListAdapter; import com.todoroo.astrid.ui.TaskListFragmentPager; import com.todoroo.astrid.utility.Constants; import com.todoroo.astrid.utility.Flags; import com.todoroo.astrid.voice.VoiceInputAssistant; import com.todoroo.astrid.voice.VoiceOutputService; import com.todoroo.astrid.voice.VoiceRecognizer; import com.todoroo.astrid.welcome.tutorial.WelcomeWalkthrough; import com.todoroo.astrid.widget.TasksWidget; /** * Displays the preference screen for users to edit their preferences * * @author Tim Su <[email protected]> * */ public class EditPreferences extends TodorooPreferenceActivity { private static final String SUPPORT_URL = "http://blog.astrid.com/topics/support/android"; //$NON-NLS-1$ private static final int APPEARANCE_PREFERENCE = 4; private static final int REQUEST_CODE_SYNC = 0; private static final int REQUEST_CODE_FILES_DIR = 2; public static final int RESULT_CODE_THEME_CHANGED = 1; public static final int RESULT_CODE_PERFORMANCE_PREF_CHANGED = 3; // --- instance variables @Autowired private TaskService taskService; @Autowired private AddOnService addOnService; @Autowired private ActFmPreferenceService actFmPreferenceService; @Autowired private Database database; private VoiceInputAssistant voiceInputAssistant; public EditPreferences() { DependencyInjectionService.getInstance().inject(this); } private class SetResultOnPreferenceChangeListener implements OnPreferenceChangeListener { private final int resultCode; public SetResultOnPreferenceChangeListener(int resultCode) { this.resultCode = resultCode; } @Override public boolean onPreferenceChange(Preference p, Object newValue) { setResult(resultCode); updatePreferences(p, newValue); return true; } } @Override public int getPreferenceResource() { return R.xml.preferences; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new StartupService().onStartupApplication(this); ContextManager.setContext(this); PreferenceScreen screen = getPreferenceScreen(); voiceInputAssistant = new VoiceInputAssistant(this); addPluginPreferences(screen); addPreferencesFromResource(R.xml.preferences_misc); final Resources r = getResources(); // first-order preferences Preference preference = screen.findPreference(getString(R.string.p_about)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { showAbout(); return true; } }); preference = screen.findPreference(getString(R.string.p_tutorial)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { Intent showWelcomeLogin = new Intent(EditPreferences.this, WelcomeWalkthrough.class); showWelcomeLogin.putExtra(ActFmLoginActivity.SHOW_TOAST, false); showWelcomeLogin.putExtra(WelcomeWalkthrough.TOKEN_MANUAL_SHOW, true); startActivity(showWelcomeLogin); return true; } }); preference = screen.findPreference(getString(R.string.p_help)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showSupport(); return true; } }); preference = screen.findPreference(getString(R.string.p_account)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showAccountPrefs(); return true; } }); preference = screen.findPreference(getString(R.string.EPr_share_astrid)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showShareActivity(); return true; } }); PreferenceScreen appearance = (PreferenceScreen) screen.getPreference(APPEARANCE_PREFERENCE); Preference beastMode = appearance.getPreference(1); beastMode.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { showBeastMode(); return true; } }); preference = screen.findPreference(getString(R.string.p_files_dir)); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference p) { Intent filesDir = new Intent(EditPreferences.this, FileExplore.class); filesDir.putExtra(FileExplore.EXTRA_DIRECTORIES_SELECTABLE, true); startActivityForResult(filesDir, REQUEST_CODE_FILES_DIR); return true; } }); addDebugPreferences(); addPreferenceListeners(); disablePremiumPrefs(); if (!AndroidUtilities.isTabletSized(this)) { appearance.removePreference(screen.findPreference(getString(R.string.p_force_phone_layout))); } else { preference = screen.findPreference(getString(R.string.p_swipe_lists_enabled)); preference.setEnabled(Preferences.getBoolean(R.string.p_force_phone_layout, false)); } preference = screen.findPreference(getString(R.string.p_showNotes)); preference.setEnabled(!Preferences.getBoolean(R.string.p_taskRowStyle, false)); removeForbiddenPreferences(screen, r); } public static void removeForbiddenPreferences(PreferenceScreen screen, Resources r) { int[] forbiddenPrefs = Constants.MARKET_STRATEGY.excludedSettings(); if (forbiddenPrefs == null) return; for (int i : forbiddenPrefs) { searchForAndRemovePreference(screen, r.getString(i)); } } private static boolean searchForAndRemovePreference(PreferenceGroup group, String key) { int preferenceCount = group.getPreferenceCount(); for (int i = 0; i < preferenceCount; i++) { final Preference preference = group.getPreference(i); final String curKey = preference.getKey(); if (curKey != null && curKey.equals(key)) { group.removePreference(preference); return true; } if (preference instanceof PreferenceGroup) { if (searchForAndRemovePreference((PreferenceGroup) preference, key)) { return true; } } } return false; } private void disablePremiumPrefs() { boolean hasPowerPack = addOnService.hasPowerPack(); findPreference(getString(R.string.p_files_dir)).setEnabled(ActFmPreferenceService.isPremiumUser()); findPreference(getString(R.string.p_voiceRemindersEnabled)).setEnabled(hasPowerPack); findPreference(getString(R.string.p_statistics)).setEnabled(hasPowerPack); } /** Show about dialog */ private void showAbout () { String version = "unknown"; //$NON-NLS-1$ try { version = getPackageManager().getPackageInfo(Constants.PACKAGE, 0).versionName; } catch (NameNotFoundException e) { // sadness } About.showAbout(this, version); } private void showSupport() { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(SUPPORT_URL)); startActivity(intent); } private void showBeastMode() { Intent intent = new Intent(this, BeastModePreferences.class); intent.setAction(AstridApiConstants.ACTION_SETTINGS); startActivity(intent); } private void showAccountPrefs() { if (actFmPreferenceService.isLoggedIn()) { Intent intent = new Intent(this, ActFmPreferences.class); intent.setAction(AstridApiConstants.ACTION_SETTINGS); startActivityForResult(intent, REQUEST_CODE_SYNC); } else { Intent intent = new Intent(this, ActFmLoginActivity.class); startActivity(intent); } } private void showShareActivity() { Intent intent = new Intent(this, ShareActivity.class); startActivity(intent); } private static final HashMap<Class<?>, Integer> PREFERENCE_REQUEST_CODES = new HashMap<Class<?>, Integer>(); static { PREFERENCE_REQUEST_CODES.put(SyncProviderPreferences.class, REQUEST_CODE_SYNC); } private void addPluginPreferences(PreferenceScreen screen) { Intent queryIntent = new Intent(AstridApiConstants.ACTION_SETTINGS); PackageManager pm = getPackageManager(); List<ResolveInfo> resolveInfoList = pm.queryIntentActivities(queryIntent, PackageManager.GET_META_DATA); int length = resolveInfoList.size(); LinkedHashMap<String, ArrayList<Preference>> categoryPreferences = new LinkedHashMap<String, ArrayList<Preference>>(); // Loop through a list of all packages (including plugins, addons) // that have a settings action for(int i = 0; i < length; i++) { ResolveInfo resolveInfo = resolveInfoList.get(i); final Intent intent = new Intent(AstridApiConstants.ACTION_SETTINGS); intent.setClassName(resolveInfo.activityInfo.packageName, resolveInfo.activityInfo.name); if(MilkPreferences.class.getName().equals(resolveInfo.activityInfo.name) && !MilkUtilities.INSTANCE.isLoggedIn()) continue; if (GtasksPreferences.class.getName().equals(resolveInfo.activityInfo.name) && AmazonMarketStrategy.isKindleFire()) continue; if (ProducteevPreferences.class.getName().equals(resolveInfo.activityInfo.name) && !Preferences.getBoolean(R.string.p_third_party_addons, false) && !ProducteevUtilities.INSTANCE.isLoggedIn()) continue; Preference preference = new Preference(this); preference.setTitle(resolveInfo.activityInfo.loadLabel(pm)); Bundle metadata = resolveInfo.activityInfo.metaData; if (metadata != null) { int resource = metadata.getInt("summary", 0); //$NON-NLS-1$ if (resource > 0) preference.setSummary(resource); } try { Class<?> intentComponent = Class.forName(intent.getComponent().getClassName()); if (intentComponent.getSuperclass().equals(SyncProviderPreferences.class)) intentComponent = SyncProviderPreferences.class; if (PREFERENCE_REQUEST_CODES.containsKey(intentComponent)) { final int code = PREFERENCE_REQUEST_CODES.get(intentComponent); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference pref) { startActivityForResult(intent, code); return true; } }); } else { preference.setIntent(intent); } } catch (ClassNotFoundException e) { preference.setIntent(intent); } String category = MetadataHelper.resolveActivityCategoryName(resolveInfo, pm); if(!categoryPreferences.containsKey(category)) categoryPreferences.put(category, new ArrayList<Preference>()); ArrayList<Preference> arrayList = categoryPreferences.get(category); arrayList.add(preference); } for(Entry<String, ArrayList<Preference>> entry : categoryPreferences.entrySet()) { if (entry.getKey().equals(getString(R.string.app_name))) { for(Preference preference : entry.getValue()) screen.addPreference(preference); } else { PreferenceManager manager = getPreferenceManager(); PreferenceScreen header = manager.createPreferenceScreen(this); header.setTitle(entry.getKey()); if (entry.getKey().equals(getString(R.string.SyP_label))) header.setSummary(R.string.SyP_summary); screen.addPreference(header); for(Preference preference : entry.getValue()) header.addPreference(preference); } } } @SuppressWarnings("nls") private void addDebugPreferences() { if(!Constants.DEBUG) return; PreferenceCategory group = new PreferenceCategory(this); group.setTitle("DEBUG"); getPreferenceScreen().addPreference(group); Preference preference = new Preference(this); preference.setTitle("Flush detail cache"); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { database.openForWriting(); Toast.makeText(EditPreferences.this, "" + taskService.clearDetails(Criterion.all), Toast.LENGTH_LONG).show(); return false; } }); group.addPreference(preference); preference = new Preference(this); preference.setTitle("Make Lots of Tasks"); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { database.openForWriting(); Task task = new Task(); for(int i = 0; i < 100; i++) { task.clear(); task.setValue(Task.TITLE, Integer.toString(i)); taskService.save(task); } DialogUtilities.okDialog(EditPreferences.this, "done", null); return false; } }); group.addPreference(preference); preference = new Preference(this); preference.setTitle("Delete all tasks"); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { database.openForWriting(); taskService.deleteWhere(Criterion.all); DialogUtilities.okDialog(EditPreferences.this, "done", null); return false; } }); group.addPreference(preference); preference = new Preference(this); preference.setTitle("Make lots of contacts"); preference.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference p) { ContactListAdapter.makeLotsOfContacts(); DialogUtilities.okDialog(EditPreferences.this, "done", null); return false; } }); group.addPreference(preference); } @Override public void updatePreferences(final Preference preference, Object value) { final Resources r = getResources(); if (r.getString(R.string.p_account).equals(preference.getKey())) { int title; int summary; if (!actFmPreferenceService.isLoggedIn()) { title = R.string.account_type_title_not_logged_in; summary = R.string.account_type_summary_not_logged_in; } else { title = R.string.actfm_account_info; summary = R.string.actfm_account_info_summary; } preference.setTitle(title); preference.setSummary(summary); } else if (r.getString(R.string.p_taskRowStyle).equals(preference.getKey())) { if (value != null && !(Boolean)value) { preference.setTitle(R.string.EPr_task_row_style_title_legacy); preference.setSummary(R.string.EPr_task_row_style_summary_legacy); } else { preference.setTitle(R.string.EPr_task_row_style_title_simple); preference.setSummary(R.string.EPr_task_row_style_summary_simple); } preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { String valueString = newValue.toString(); StatisticsService.reportEvent(StatisticsConstants.PREF_CHANGED_PREFIX + "row-style", //$NON-NLS-1$ "changed-to", valueString); //$NON-NLS-1$ Preference notes = findPreference(getString(R.string.p_showNotes)); notes.setEnabled(!(Boolean) newValue); return super.onPreferenceChange(p, newValue); }; }); } else if (r.getString(R.string.p_showNotes).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_showNotes_desc_disabled); else preference.setSummary(R.string.EPr_showNotes_desc_enabled); if((Boolean)value != Preferences.getBoolean(preference.getKey(), false)) { taskService.clearDetails(Criterion.all); Flags.set(Flags.REFRESH); } } else if(r.getString(R.string.p_fullTaskTitle).equals(preference.getKey())) { if (value != null && (Boolean) value) preference.setSummary(R.string.EPr_fullTask_desc_enabled); else preference.setSummary(R.string.EPr_fullTask_desc_disabled); } else if (r.getString(R.string.p_theme).equals(preference.getKey())) { if(AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if(value instanceof String && !TextUtils.isEmpty((String)value)) index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_settings), (String)value); if (index < 0) index = 0; preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes)[index])); } } else if (r.getString(R.string.p_theme_widget).equals(preference.getKey())) { if(AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if(value instanceof String && !TextUtils.isEmpty((String)value)) index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_widget_settings), (String)value); if (index < 0) index = 0; preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes_widget)[index])); } } // pp preferences else if (r.getString(R.string.p_files_dir).equals(preference.getKey())) { String dir = Preferences.getStringValue(FileMetadata.FILES_DIRECTORY_PREF); if (TextUtils.isEmpty(dir)) { dir = r.getString(R.string.p_files_dir_desc_default); } preference.setSummary(r.getString(R.string.p_files_dir_desc, dir)); } else if (booleanPreference(preference, value, R.string.p_statistics, R.string.EPr_statistics_desc_disabled, R.string.EPr_statistics_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_autoIdea, R.string.EPr_ideaAuto_desc_disabled, R.string.EPr_ideaAuto_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_field_missed_calls, - R.string.MCA_missed_calls_pref_desc_enabled, R.string.MCA_missed_calls_pref_desc_disabled)); + R.string.MCA_missed_calls_pref_desc_disabled, R.string.MCA_missed_calls_pref_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_use_contact_picker, - R.string.EPr_use_contact_picker_desc_enabled, R.string.EPr_use_contact_picker_desc_disabled)); + R.string.EPr_use_contact_picker_desc_disabled, R.string.EPr_use_contact_picker_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_third_party_addons, R.string.EPr_third_party_addons_desc_enabled, R.string.EPr_third_party_addons_desc_disabled)); else if (booleanPreference(preference, value, R.string.p_end_at_deadline, - R.string.EPr_cal_start_at_due_time, R.string.EPr_cal_end_at_due_time)); + R.string.EPr_cal_end_at_due_time, R.string.EPr_cal_start_at_due_time)); else if (r.getString(R.string.p_swipe_lists_enabled).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { // If the user changes the setting themselves, no need to show the helper Preferences.setBoolean(TaskListFragmentPager.PREF_SHOWED_SWIPE_HELPER, true); return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_force_phone_layout).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { Preference swipe = findPreference(getString(R.string.p_swipe_lists_enabled)); swipe.setEnabled((Boolean) newValue); return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_show_featured_lists_labs).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { StatisticsService.reportEvent(StatisticsConstants.PREF_SHOW_FEATURED_LISTS, "enabled", newValue.toString()); //$NON-NLS-1$ return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled); onVoiceInputStatusChanged(preference, (Boolean)value); } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled); onVoiceReminderStatusChanged(preference, (Boolean)value); } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); } } protected boolean booleanPreference(Preference preference, Object value, int key, int disabledString, int enabledString) { if(getString(key).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(disabledString); else preference.setSummary(enabledString); return true; } return false; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_CODE_SYNC && resultCode == SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) { setResult(SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE); finish(); return; } else if (requestCode == REQUEST_CODE_FILES_DIR && resultCode == RESULT_OK) { if (data != null) { String dir = data.getStringExtra(FileExplore.RESULT_DIR_SELECTED); Preferences.setString(FileMetadata.FILES_DIRECTORY_PREF, dir); } return; } try { VoiceOutputService.getVoiceOutputInstance().handleActivityResult(requestCode, resultCode, data); } catch (VerifyError e) { // unavailable } super.onActivityResult(requestCode, resultCode, data); } public void addPreferenceListeners() { findPreference(getString(R.string.p_theme)).setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_THEME_CHANGED)); findPreference(getString(R.string.p_theme_widget)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { TasksWidget.updateWidgets(EditPreferences.this); updatePreferences(preference, newValue); return true; } }); findPreference(getString(R.string.p_statistics)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Boolean value = (Boolean) newValue; try { if (!value.booleanValue()) { Crittercism.setOptOutStatus(true); } else { Crittercism.setOptOutStatus(false); } } catch (NullPointerException e) { return false; } return true; } }); findPreference(getString(R.string.p_third_party_addons)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { StatisticsService.reportEvent(StatisticsConstants.PREF_THIRD_PARTY_ADDONS, "enabled", newValue.toString()); //$NON-NLS-1$ return true; } }); findPreference(getString(R.string.p_showNotes)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { StatisticsService.reportEvent(StatisticsConstants.PREF_SHOW_NOTES_IN_ROW, "enabled", newValue.toString()); //$NON-NLS-1$ return true; } }); findPreference(getString(R.string.p_fullTaskTitle)).setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { StatisticsService.reportEvent(StatisticsConstants.PREF_CHANGED_PREFIX + "full-title", "full-title", newValue.toString()); //$NON-NLS-1$ //$NON-NLS-2$ return true; } }); } private void onVoiceReminderStatusChanged(final Preference preference, boolean newValue) { try { VoiceOutputService.getVoiceOutputInstance(); if(newValue) VoiceOutputService.getVoiceOutputInstance().checkIsTTSInstalled(); } catch (VerifyError e) { // doesn't work :( preference.setEnabled(false); Preferences.setBoolean(preference.getKey(), false); } } private void onVoiceInputStatusChanged(final Preference preference, boolean newValue) { if(!newValue) return; final Resources r = getResources(); if (!VoiceRecognizer.voiceInputAvailable(this)) { if (AndroidUtilities.getSdkVersion() > 6) { DialogUtilities.okCancelDialog(this, r.getString(R.string.EPr_voiceInputInstall_dlg), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { voiceInputAssistant.showVoiceInputMarketSearch(new OnClickListener() { @Override public void onClick(DialogInterface dialog1, int which1) { ((CheckBoxPreference)preference).setChecked(false); } }); } }, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ((CheckBoxPreference)preference).setChecked(false); } }); } else { DialogUtilities.okDialog(this, r.getString(R.string.EPr_voiceInputUnavailable_dlg), new OnClickListener() { @Override public void onClick(DialogInterface dialog1, int which1) { ((CheckBoxPreference)preference).setChecked(false); } }); } } } @Override protected void onPause() { StatisticsService.sessionPause(); super.onPause(); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); StatisticsService.sessionStart(this); } @Override protected void onStop() { StatisticsService.sessionStop(this); super.onStop(); } }
false
true
public void updatePreferences(final Preference preference, Object value) { final Resources r = getResources(); if (r.getString(R.string.p_account).equals(preference.getKey())) { int title; int summary; if (!actFmPreferenceService.isLoggedIn()) { title = R.string.account_type_title_not_logged_in; summary = R.string.account_type_summary_not_logged_in; } else { title = R.string.actfm_account_info; summary = R.string.actfm_account_info_summary; } preference.setTitle(title); preference.setSummary(summary); } else if (r.getString(R.string.p_taskRowStyle).equals(preference.getKey())) { if (value != null && !(Boolean)value) { preference.setTitle(R.string.EPr_task_row_style_title_legacy); preference.setSummary(R.string.EPr_task_row_style_summary_legacy); } else { preference.setTitle(R.string.EPr_task_row_style_title_simple); preference.setSummary(R.string.EPr_task_row_style_summary_simple); } preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { String valueString = newValue.toString(); StatisticsService.reportEvent(StatisticsConstants.PREF_CHANGED_PREFIX + "row-style", //$NON-NLS-1$ "changed-to", valueString); //$NON-NLS-1$ Preference notes = findPreference(getString(R.string.p_showNotes)); notes.setEnabled(!(Boolean) newValue); return super.onPreferenceChange(p, newValue); }; }); } else if (r.getString(R.string.p_showNotes).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_showNotes_desc_disabled); else preference.setSummary(R.string.EPr_showNotes_desc_enabled); if((Boolean)value != Preferences.getBoolean(preference.getKey(), false)) { taskService.clearDetails(Criterion.all); Flags.set(Flags.REFRESH); } } else if(r.getString(R.string.p_fullTaskTitle).equals(preference.getKey())) { if (value != null && (Boolean) value) preference.setSummary(R.string.EPr_fullTask_desc_enabled); else preference.setSummary(R.string.EPr_fullTask_desc_disabled); } else if (r.getString(R.string.p_theme).equals(preference.getKey())) { if(AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if(value instanceof String && !TextUtils.isEmpty((String)value)) index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_settings), (String)value); if (index < 0) index = 0; preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes)[index])); } } else if (r.getString(R.string.p_theme_widget).equals(preference.getKey())) { if(AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if(value instanceof String && !TextUtils.isEmpty((String)value)) index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_widget_settings), (String)value); if (index < 0) index = 0; preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes_widget)[index])); } } // pp preferences else if (r.getString(R.string.p_files_dir).equals(preference.getKey())) { String dir = Preferences.getStringValue(FileMetadata.FILES_DIRECTORY_PREF); if (TextUtils.isEmpty(dir)) { dir = r.getString(R.string.p_files_dir_desc_default); } preference.setSummary(r.getString(R.string.p_files_dir_desc, dir)); } else if (booleanPreference(preference, value, R.string.p_statistics, R.string.EPr_statistics_desc_disabled, R.string.EPr_statistics_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_autoIdea, R.string.EPr_ideaAuto_desc_disabled, R.string.EPr_ideaAuto_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_field_missed_calls, R.string.MCA_missed_calls_pref_desc_enabled, R.string.MCA_missed_calls_pref_desc_disabled)); else if (booleanPreference(preference, value, R.string.p_use_contact_picker, R.string.EPr_use_contact_picker_desc_enabled, R.string.EPr_use_contact_picker_desc_disabled)); else if (booleanPreference(preference, value, R.string.p_third_party_addons, R.string.EPr_third_party_addons_desc_enabled, R.string.EPr_third_party_addons_desc_disabled)); else if (booleanPreference(preference, value, R.string.p_end_at_deadline, R.string.EPr_cal_start_at_due_time, R.string.EPr_cal_end_at_due_time)); else if (r.getString(R.string.p_swipe_lists_enabled).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { // If the user changes the setting themselves, no need to show the helper Preferences.setBoolean(TaskListFragmentPager.PREF_SHOWED_SWIPE_HELPER, true); return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_force_phone_layout).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { Preference swipe = findPreference(getString(R.string.p_swipe_lists_enabled)); swipe.setEnabled((Boolean) newValue); return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_show_featured_lists_labs).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { StatisticsService.reportEvent(StatisticsConstants.PREF_SHOW_FEATURED_LISTS, "enabled", newValue.toString()); //$NON-NLS-1$ return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled); onVoiceInputStatusChanged(preference, (Boolean)value); } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled); onVoiceReminderStatusChanged(preference, (Boolean)value); } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); } }
public void updatePreferences(final Preference preference, Object value) { final Resources r = getResources(); if (r.getString(R.string.p_account).equals(preference.getKey())) { int title; int summary; if (!actFmPreferenceService.isLoggedIn()) { title = R.string.account_type_title_not_logged_in; summary = R.string.account_type_summary_not_logged_in; } else { title = R.string.actfm_account_info; summary = R.string.actfm_account_info_summary; } preference.setTitle(title); preference.setSummary(summary); } else if (r.getString(R.string.p_taskRowStyle).equals(preference.getKey())) { if (value != null && !(Boolean)value) { preference.setTitle(R.string.EPr_task_row_style_title_legacy); preference.setSummary(R.string.EPr_task_row_style_summary_legacy); } else { preference.setTitle(R.string.EPr_task_row_style_title_simple); preference.setSummary(R.string.EPr_task_row_style_summary_simple); } preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { String valueString = newValue.toString(); StatisticsService.reportEvent(StatisticsConstants.PREF_CHANGED_PREFIX + "row-style", //$NON-NLS-1$ "changed-to", valueString); //$NON-NLS-1$ Preference notes = findPreference(getString(R.string.p_showNotes)); notes.setEnabled(!(Boolean) newValue); return super.onPreferenceChange(p, newValue); }; }); } else if (r.getString(R.string.p_showNotes).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_showNotes_desc_disabled); else preference.setSummary(R.string.EPr_showNotes_desc_enabled); if((Boolean)value != Preferences.getBoolean(preference.getKey(), false)) { taskService.clearDetails(Criterion.all); Flags.set(Flags.REFRESH); } } else if(r.getString(R.string.p_fullTaskTitle).equals(preference.getKey())) { if (value != null && (Boolean) value) preference.setSummary(R.string.EPr_fullTask_desc_enabled); else preference.setSummary(R.string.EPr_fullTask_desc_disabled); } else if (r.getString(R.string.p_theme).equals(preference.getKey())) { if(AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if(value instanceof String && !TextUtils.isEmpty((String)value)) index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_settings), (String)value); if (index < 0) index = 0; preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes)[index])); } } else if (r.getString(R.string.p_theme_widget).equals(preference.getKey())) { if(AndroidUtilities.getSdkVersion() < 5) { preference.setEnabled(false); preference.setSummary(R.string.EPr_theme_desc_unsupported); } else { int index = 0; if(value instanceof String && !TextUtils.isEmpty((String)value)) index = AndroidUtilities.indexOf(r.getStringArray(R.array.EPr_theme_widget_settings), (String)value); if (index < 0) index = 0; preference.setSummary(getString(R.string.EPr_theme_desc, r.getStringArray(R.array.EPr_themes_widget)[index])); } } // pp preferences else if (r.getString(R.string.p_files_dir).equals(preference.getKey())) { String dir = Preferences.getStringValue(FileMetadata.FILES_DIRECTORY_PREF); if (TextUtils.isEmpty(dir)) { dir = r.getString(R.string.p_files_dir_desc_default); } preference.setSummary(r.getString(R.string.p_files_dir_desc, dir)); } else if (booleanPreference(preference, value, R.string.p_statistics, R.string.EPr_statistics_desc_disabled, R.string.EPr_statistics_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_autoIdea, R.string.EPr_ideaAuto_desc_disabled, R.string.EPr_ideaAuto_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_field_missed_calls, R.string.MCA_missed_calls_pref_desc_disabled, R.string.MCA_missed_calls_pref_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_use_contact_picker, R.string.EPr_use_contact_picker_desc_disabled, R.string.EPr_use_contact_picker_desc_enabled)); else if (booleanPreference(preference, value, R.string.p_third_party_addons, R.string.EPr_third_party_addons_desc_enabled, R.string.EPr_third_party_addons_desc_disabled)); else if (booleanPreference(preference, value, R.string.p_end_at_deadline, R.string.EPr_cal_end_at_due_time, R.string.EPr_cal_start_at_due_time)); else if (r.getString(R.string.p_swipe_lists_enabled).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { // If the user changes the setting themselves, no need to show the helper Preferences.setBoolean(TaskListFragmentPager.PREF_SHOWED_SWIPE_HELPER, true); return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_force_phone_layout).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(RESULT_CODE_PERFORMANCE_PREF_CHANGED) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { Preference swipe = findPreference(getString(R.string.p_swipe_lists_enabled)); swipe.setEnabled((Boolean) newValue); return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_show_featured_lists_labs).equals(preference.getKey())) { preference.setOnPreferenceChangeListener(new SetResultOnPreferenceChangeListener(SyncProviderPreferences.RESULT_CODE_SYNCHRONIZE) { @Override public boolean onPreferenceChange(Preference p, Object newValue) { StatisticsService.reportEvent(StatisticsConstants.PREF_SHOW_FEATURED_LISTS, "enabled", newValue.toString()); //$NON-NLS-1$ return super.onPreferenceChange(p, newValue); } }); } else if (r.getString(R.string.p_voiceInputEnabled).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceInputEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputEnabled_desc_enabled); onVoiceInputStatusChanged(preference, (Boolean)value); } else if (r.getString(R.string.p_voiceRemindersEnabled).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_disabled); else preference.setSummary(R.string.EPr_voiceRemindersEnabled_desc_enabled); onVoiceReminderStatusChanged(preference, (Boolean)value); } else if (r.getString(R.string.p_voiceInputCreatesTask).equals(preference.getKey())) { if (value != null && !(Boolean)value) preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_disabled); else preference.setSummary(R.string.EPr_voiceInputCreatesTask_desc_enabled); } }
diff --git a/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java b/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java index 4d35ff3ab..4883edf01 100644 --- a/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java +++ b/activemq-core/src/test/java/org/apache/activemq/bugs/AMQ2149KahaDBTest.java @@ -1,30 +1,30 @@ /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.bugs; import org.apache.activemq.broker.BrokerService; import org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter; public class AMQ2149KahaDBTest extends AMQ2149Test { @Override protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { // nothing to do as kahaDB is now the default - //KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); - //kahaDB.setConcurrentStoreAndDispatchTopics(true); + KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); + kahaDB.setConcurrentStoreAndDispatchTopics(true); } }
true
true
protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { // nothing to do as kahaDB is now the default //KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); //kahaDB.setConcurrentStoreAndDispatchTopics(true); }
protected void configurePersistenceAdapter(BrokerService brokerService) throws Exception { // nothing to do as kahaDB is now the default KahaDBPersistenceAdapter kahaDB = (KahaDBPersistenceAdapter) brokerService.getPersistenceAdapter(); kahaDB.setConcurrentStoreAndDispatchTopics(true); }
diff --git a/Yamba/src/com/cisco/yamba/StatusProvider.java b/Yamba/src/com/cisco/yamba/StatusProvider.java index cd46c9a..9bad1e4 100644 --- a/Yamba/src/com/cisco/yamba/StatusProvider.java +++ b/Yamba/src/com/cisco/yamba/StatusProvider.java @@ -1,118 +1,117 @@ package com.cisco.yamba; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.text.TextUtils; import android.util.Log; public class StatusProvider extends ContentProvider { private static final String TAG = "StatusProvider"; private DbHelper dbHelper; /* * Status Table: All records: * content://com.cisco.yamba.provider.timeline/status One record: * content://com.cisco.yamba.provider.timeline/status/47 */ private static UriMatcher matcher; static { matcher = new UriMatcher(UriMatcher.NO_MATCH); matcher.addURI(StatusContract.AUTHORITY, StatusContract.TABLE, StatusContract.CONTENT_TYPE_DIR); matcher.addURI(StatusContract.AUTHORITY, StatusContract.TABLE + "/#", StatusContract.CONTENT_TYPE_ITEM); } @Override public boolean onCreate() { dbHelper = new DbHelper(getContext()); Log.d(TAG, "onCreated"); return (dbHelper != null) ? true : false; } @Override public String getType(Uri uri) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri uri, ContentValues values) { // Assert if (matcher.match(uri) != StatusContract.CONTENT_TYPE_DIR) { throw new IllegalArgumentException("Wrong uri: " + uri); } SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowId = db.insertWithOnConflict(StatusContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE); if (rowId == -1) { return null; } else { // We have new data getContext().getContentResolver().notifyChange(uri, null); int statusId = values.getAsInteger(StatusContract.Columns.ID); Uri retUri = ContentUris.withAppendedId(uri, statusId); Log.d(TAG, "insert with uri: " + retUri); // Send broadcast Intent intent = new Intent("com.cisco.yamba.action.NEW_DATA"); - intent.setData(retUri); getContext().sendBroadcast( intent ); return retUri; } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO Auto-generated method stub return 0; } // uri: content://com.cisco.yamba.provider.timeline/status/47 // selection: user="?" @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = dbHelper.getWritableDatabase(); if (matcher.match(uri) == StatusContract.CONTENT_TYPE_ITEM) { long id = ContentUris.parseId(uri); String where = StatusContract.Columns.ID + "=" + id; if (!TextUtils.isEmpty(selection)) selection = selection + " AND " + where; else selection = where; } int recs = db.delete(StatusContract.TABLE, selection, selectionArgs); if (recs > 0) getContext().getContentResolver().notifyChange(uri, null); Log.d(TAG, "delete records: " + recs); return recs; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(StatusContract.TABLE, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } }
true
true
public Uri insert(Uri uri, ContentValues values) { // Assert if (matcher.match(uri) != StatusContract.CONTENT_TYPE_DIR) { throw new IllegalArgumentException("Wrong uri: " + uri); } SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowId = db.insertWithOnConflict(StatusContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE); if (rowId == -1) { return null; } else { // We have new data getContext().getContentResolver().notifyChange(uri, null); int statusId = values.getAsInteger(StatusContract.Columns.ID); Uri retUri = ContentUris.withAppendedId(uri, statusId); Log.d(TAG, "insert with uri: " + retUri); // Send broadcast Intent intent = new Intent("com.cisco.yamba.action.NEW_DATA"); intent.setData(retUri); getContext().sendBroadcast( intent ); return retUri; } }
public Uri insert(Uri uri, ContentValues values) { // Assert if (matcher.match(uri) != StatusContract.CONTENT_TYPE_DIR) { throw new IllegalArgumentException("Wrong uri: " + uri); } SQLiteDatabase db = dbHelper.getWritableDatabase(); long rowId = db.insertWithOnConflict(StatusContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE); if (rowId == -1) { return null; } else { // We have new data getContext().getContentResolver().notifyChange(uri, null); int statusId = values.getAsInteger(StatusContract.Columns.ID); Uri retUri = ContentUris.withAppendedId(uri, statusId); Log.d(TAG, "insert with uri: " + retUri); // Send broadcast Intent intent = new Intent("com.cisco.yamba.action.NEW_DATA"); getContext().sendBroadcast( intent ); return retUri; } }
diff --git a/src/step1/Reducer1.java b/src/step1/Reducer1.java index 6a9cf9d..b3117a8 100644 --- a/src/step1/Reducer1.java +++ b/src/step1/Reducer1.java @@ -1,87 +1,87 @@ package step1; import java.io.IOException; import java.util.HashSet; import java.util.logging.Logger; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Reducer; import structures.DisjointSet; import structures.MatrixUtilities; import structures.Tuple; import base.PingingReducer; import constants.Constants; public class Reducer1 extends PingingReducer<IntWritable, IntWritable, IntWritable, Tuple> { DisjointSet set; HashSet<Integer> memory; final int height = Constants.M; private final static Logger LOGGER = Logger.getLogger(Reducer1.class .getName()); @Override protected void reduce( final IntWritable key, final Iterable<IntWritable> values, final Reducer<IntWritable, IntWritable, IntWritable, Tuple>.Context context) throws IOException, InterruptedException { if (Constants.DEBUG) LOGGER.info("Reducer1 - reduce called"); set = new DisjointSet(Constants.groupSize); memory = new HashSet<Integer>(Constants.groupSize); final int group = key.get(); // Pass 1 - Build a memory to "sort" the values for (final IntWritable value : values) { memory.add(value.get()); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 1 looped"); } final int minP = MatrixUtilities.minInGroup(group); final int maxP = MatrixUtilities.maxInGroup(group); // Pass 2 - Unions for (int p = minP; p <= maxP; p++) { if (!memory.contains(p)) continue; if ((p > height) && memory.contains(p - height)) set.union(p, p - height); if (Constants.COMPUTE_DIAGONAL) { - // Compute lower left diagonal + // Compute lower right diagonal if ((p > height) && (p % height != 1) && memory.contains(p - height - 1)) set.union(p, p - height - 1); // Compute upper right diagonal if ((p > height) && (p % height != 0) && memory.contains(p - height)) set.union(p, p - height + 1); } if (((p % height) != 1) && memory.contains(p - 1)) set.union(p, p - 1); ping(context); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 2 looped"); } // Pass 3 - Find and output for (int p = minP; p <= maxP; p++) { if (!memory.contains(p)) continue; context.write(key, new Tuple(p, set.find(p))); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 3 looped"); } memory.clear(); } }
true
true
protected void reduce( final IntWritable key, final Iterable<IntWritable> values, final Reducer<IntWritable, IntWritable, IntWritable, Tuple>.Context context) throws IOException, InterruptedException { if (Constants.DEBUG) LOGGER.info("Reducer1 - reduce called"); set = new DisjointSet(Constants.groupSize); memory = new HashSet<Integer>(Constants.groupSize); final int group = key.get(); // Pass 1 - Build a memory to "sort" the values for (final IntWritable value : values) { memory.add(value.get()); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 1 looped"); } final int minP = MatrixUtilities.minInGroup(group); final int maxP = MatrixUtilities.maxInGroup(group); // Pass 2 - Unions for (int p = minP; p <= maxP; p++) { if (!memory.contains(p)) continue; if ((p > height) && memory.contains(p - height)) set.union(p, p - height); if (Constants.COMPUTE_DIAGONAL) { // Compute lower left diagonal if ((p > height) && (p % height != 1) && memory.contains(p - height - 1)) set.union(p, p - height - 1); // Compute upper right diagonal if ((p > height) && (p % height != 0) && memory.contains(p - height)) set.union(p, p - height + 1); } if (((p % height) != 1) && memory.contains(p - 1)) set.union(p, p - 1); ping(context); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 2 looped"); } // Pass 3 - Find and output for (int p = minP; p <= maxP; p++) { if (!memory.contains(p)) continue; context.write(key, new Tuple(p, set.find(p))); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 3 looped"); } memory.clear(); }
protected void reduce( final IntWritable key, final Iterable<IntWritable> values, final Reducer<IntWritable, IntWritable, IntWritable, Tuple>.Context context) throws IOException, InterruptedException { if (Constants.DEBUG) LOGGER.info("Reducer1 - reduce called"); set = new DisjointSet(Constants.groupSize); memory = new HashSet<Integer>(Constants.groupSize); final int group = key.get(); // Pass 1 - Build a memory to "sort" the values for (final IntWritable value : values) { memory.add(value.get()); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 1 looped"); } final int minP = MatrixUtilities.minInGroup(group); final int maxP = MatrixUtilities.maxInGroup(group); // Pass 2 - Unions for (int p = minP; p <= maxP; p++) { if (!memory.contains(p)) continue; if ((p > height) && memory.contains(p - height)) set.union(p, p - height); if (Constants.COMPUTE_DIAGONAL) { // Compute lower right diagonal if ((p > height) && (p % height != 1) && memory.contains(p - height - 1)) set.union(p, p - height - 1); // Compute upper right diagonal if ((p > height) && (p % height != 0) && memory.contains(p - height)) set.union(p, p - height + 1); } if (((p % height) != 1) && memory.contains(p - 1)) set.union(p, p - 1); ping(context); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 2 looped"); } // Pass 3 - Find and output for (int p = minP; p <= maxP; p++) { if (!memory.contains(p)) continue; context.write(key, new Tuple(p, set.find(p))); if (Constants.DEBUG) LOGGER.info("Reducer1 - pass 3 looped"); } memory.clear(); }
diff --git a/src/com/deliciousdroid/authenticator/OauthUtilities.java b/src/com/deliciousdroid/authenticator/OauthUtilities.java index 17ca637..fe906aa 100644 --- a/src/com/deliciousdroid/authenticator/OauthUtilities.java +++ b/src/com/deliciousdroid/authenticator/OauthUtilities.java @@ -1,112 +1,112 @@ /* * DeliciousDroid - http://code.google.com/p/DeliciousDroid/ * * Copyright (C) 2010 Matt Schmidt * * DeliciousDroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation; either version 3 of the License, * or (at your option) any later version. * * DeliciousDroid is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DeliciousDroid; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package com.deliciousdroid.authenticator; import java.net.URI; import java.net.URLEncoder; import java.util.Date; import java.util.Random; import java.util.TreeMap; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.http.client.methods.HttpGet; import android.util.Log; import com.deliciousdroid.Constants; import com.deliciousdroid.util.Base64; public class OauthUtilities { public static HttpGet signRequest(HttpGet request, TreeMap<String, String> params, String authtoken, String tokenSecret){ Random r = new Random(); String nonce = Long.toString(Math.abs(r.nextLong()), 36); Date d = new Date(); String timestamp = Long.toString(d.getTime() / 1000); params.put(Constants.OAUTH_COMSUMER_KEY_PROPERTY, Constants.OAUTH_CONSUMER_KEY); params.put(Constants.OAUTH_NONCE_PROPERTY, nonce); params.put(Constants.OAUTH_SIGNATURE_METHOD_PROPERTY, Constants.OAUTH_SIGNATURE_METHOD_HMAC); params.put(Constants.OAUTH_TIMESTAMP_PROPERTY, timestamp); params.put(Constants.OAUTH_TOKEN_PROPERTY, authtoken); params.put(Constants.OAUTH_VERSION_PROPERTY, Constants.OAUTH_VERSION); URI u = request.getURI(); String url = u.getScheme() + "://" + u.getAuthority() + u.getPath(); StringBuilder sb = new StringBuilder(); sb.append("GET"); sb.append("&" + URLEncoder.encode(url)); for(String key : params.keySet()){ if(params.firstKey() == key){ sb.append("&"); } else { sb.append("%26"); } sb.append(URLEncoder.encode(key) + "%3D"); - sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B")); + sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B").replace("%7C", "%257C")); } Log.d("base string", sb.toString().replace("%23", "%2523")); String keystring = Constants.OAUTH_SHARED_SECRET + "&" + tokenSecret; SecretKeySpec sha1key = new SecretKeySpec(keystring.getBytes(), "HmacSHA1"); String signature = null; try{ Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1key); byte[] sigBytes = mac.doFinal(sb.toString().replace("%23", "%2523").getBytes()); signature = Base64.encodeBytes(sigBytes); } catch(Exception e){ Log.e("Oauth Sign Request", "Hash Error"); } StringBuilder authHeader = new StringBuilder(); authHeader.append("OAuth realm=\"yahooapis.com\""); authHeader.append("," + Constants.OAUTH_COMSUMER_KEY_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_CONSUMER_KEY + "\""); authHeader.append("," + Constants.OAUTH_NONCE_PROPERTY + "="); authHeader.append("\"" + nonce + "\""); authHeader.append("," + Constants.OAUTH_SIGNATURE_PROPERTY + "="); authHeader.append("\"" + signature + "\""); authHeader.append("," + Constants.OAUTH_SIGNATURE_METHOD_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_SIGNATURE_METHOD_HMAC + "\""); authHeader.append("," + Constants.OAUTH_TIMESTAMP_PROPERTY + "="); authHeader.append("\"" + timestamp + "\""); authHeader.append("," + Constants.OAUTH_TOKEN_PROPERTY + "="); authHeader.append("\"" + authtoken + "\""); authHeader.append("," + Constants.OAUTH_VERSION_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_VERSION + "\""); request.setHeader("Authorization", authHeader.toString()); return request; } }
true
true
public static HttpGet signRequest(HttpGet request, TreeMap<String, String> params, String authtoken, String tokenSecret){ Random r = new Random(); String nonce = Long.toString(Math.abs(r.nextLong()), 36); Date d = new Date(); String timestamp = Long.toString(d.getTime() / 1000); params.put(Constants.OAUTH_COMSUMER_KEY_PROPERTY, Constants.OAUTH_CONSUMER_KEY); params.put(Constants.OAUTH_NONCE_PROPERTY, nonce); params.put(Constants.OAUTH_SIGNATURE_METHOD_PROPERTY, Constants.OAUTH_SIGNATURE_METHOD_HMAC); params.put(Constants.OAUTH_TIMESTAMP_PROPERTY, timestamp); params.put(Constants.OAUTH_TOKEN_PROPERTY, authtoken); params.put(Constants.OAUTH_VERSION_PROPERTY, Constants.OAUTH_VERSION); URI u = request.getURI(); String url = u.getScheme() + "://" + u.getAuthority() + u.getPath(); StringBuilder sb = new StringBuilder(); sb.append("GET"); sb.append("&" + URLEncoder.encode(url)); for(String key : params.keySet()){ if(params.firstKey() == key){ sb.append("&"); } else { sb.append("%26"); } sb.append(URLEncoder.encode(key) + "%3D"); sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B")); } Log.d("base string", sb.toString().replace("%23", "%2523")); String keystring = Constants.OAUTH_SHARED_SECRET + "&" + tokenSecret; SecretKeySpec sha1key = new SecretKeySpec(keystring.getBytes(), "HmacSHA1"); String signature = null; try{ Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1key); byte[] sigBytes = mac.doFinal(sb.toString().replace("%23", "%2523").getBytes()); signature = Base64.encodeBytes(sigBytes); } catch(Exception e){ Log.e("Oauth Sign Request", "Hash Error"); } StringBuilder authHeader = new StringBuilder(); authHeader.append("OAuth realm=\"yahooapis.com\""); authHeader.append("," + Constants.OAUTH_COMSUMER_KEY_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_CONSUMER_KEY + "\""); authHeader.append("," + Constants.OAUTH_NONCE_PROPERTY + "="); authHeader.append("\"" + nonce + "\""); authHeader.append("," + Constants.OAUTH_SIGNATURE_PROPERTY + "="); authHeader.append("\"" + signature + "\""); authHeader.append("," + Constants.OAUTH_SIGNATURE_METHOD_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_SIGNATURE_METHOD_HMAC + "\""); authHeader.append("," + Constants.OAUTH_TIMESTAMP_PROPERTY + "="); authHeader.append("\"" + timestamp + "\""); authHeader.append("," + Constants.OAUTH_TOKEN_PROPERTY + "="); authHeader.append("\"" + authtoken + "\""); authHeader.append("," + Constants.OAUTH_VERSION_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_VERSION + "\""); request.setHeader("Authorization", authHeader.toString()); return request; }
public static HttpGet signRequest(HttpGet request, TreeMap<String, String> params, String authtoken, String tokenSecret){ Random r = new Random(); String nonce = Long.toString(Math.abs(r.nextLong()), 36); Date d = new Date(); String timestamp = Long.toString(d.getTime() / 1000); params.put(Constants.OAUTH_COMSUMER_KEY_PROPERTY, Constants.OAUTH_CONSUMER_KEY); params.put(Constants.OAUTH_NONCE_PROPERTY, nonce); params.put(Constants.OAUTH_SIGNATURE_METHOD_PROPERTY, Constants.OAUTH_SIGNATURE_METHOD_HMAC); params.put(Constants.OAUTH_TIMESTAMP_PROPERTY, timestamp); params.put(Constants.OAUTH_TOKEN_PROPERTY, authtoken); params.put(Constants.OAUTH_VERSION_PROPERTY, Constants.OAUTH_VERSION); URI u = request.getURI(); String url = u.getScheme() + "://" + u.getAuthority() + u.getPath(); StringBuilder sb = new StringBuilder(); sb.append("GET"); sb.append("&" + URLEncoder.encode(url)); for(String key : params.keySet()){ if(params.firstKey() == key){ sb.append("&"); } else { sb.append("%26"); } sb.append(URLEncoder.encode(key) + "%3D"); sb.append(URLEncoder.encode(params.get(key)).replace("+", "%2B").replace("%7C", "%257C")); } Log.d("base string", sb.toString().replace("%23", "%2523")); String keystring = Constants.OAUTH_SHARED_SECRET + "&" + tokenSecret; SecretKeySpec sha1key = new SecretKeySpec(keystring.getBytes(), "HmacSHA1"); String signature = null; try{ Mac mac = Mac.getInstance("HmacSHA1"); mac.init(sha1key); byte[] sigBytes = mac.doFinal(sb.toString().replace("%23", "%2523").getBytes()); signature = Base64.encodeBytes(sigBytes); } catch(Exception e){ Log.e("Oauth Sign Request", "Hash Error"); } StringBuilder authHeader = new StringBuilder(); authHeader.append("OAuth realm=\"yahooapis.com\""); authHeader.append("," + Constants.OAUTH_COMSUMER_KEY_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_CONSUMER_KEY + "\""); authHeader.append("," + Constants.OAUTH_NONCE_PROPERTY + "="); authHeader.append("\"" + nonce + "\""); authHeader.append("," + Constants.OAUTH_SIGNATURE_PROPERTY + "="); authHeader.append("\"" + signature + "\""); authHeader.append("," + Constants.OAUTH_SIGNATURE_METHOD_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_SIGNATURE_METHOD_HMAC + "\""); authHeader.append("," + Constants.OAUTH_TIMESTAMP_PROPERTY + "="); authHeader.append("\"" + timestamp + "\""); authHeader.append("," + Constants.OAUTH_TOKEN_PROPERTY + "="); authHeader.append("\"" + authtoken + "\""); authHeader.append("," + Constants.OAUTH_VERSION_PROPERTY + "="); authHeader.append("\"" + Constants.OAUTH_VERSION + "\""); request.setHeader("Authorization", authHeader.toString()); return request; }
diff --git a/src/editor/highlighter/LuaIdentifierHighlighterEditorComponent.java b/src/editor/highlighter/LuaIdentifierHighlighterEditorComponent.java index f3e0e953..d4905455 100644 --- a/src/editor/highlighter/LuaIdentifierHighlighterEditorComponent.java +++ b/src/editor/highlighter/LuaIdentifierHighlighterEditorComponent.java @@ -1,596 +1,599 @@ /* * Copyright 2010 Jon S Akhtar (Sylvanaar) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sylvanaar.idea.Lua.editor.highlighter; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.event.CaretEvent; import com.intellij.openapi.editor.event.CaretListener; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.event.DocumentListener; import com.intellij.openapi.editor.markup.HighlighterLayer; import com.intellij.openapi.editor.markup.HighlighterTargetArea; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.PsiSearchHelper; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.Query; import com.sylvanaar.idea.Lua.lang.parser.LuaElementTypes; import com.sylvanaar.idea.Lua.lang.psi.expressions.LuaIdentifier; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; public class LuaIdentifierHighlighterEditorComponent implements CaretListener, DocumentListener { static Logger log = Logger.getInstance("#LuaIdentifierHighlighterEditorComponent"); //protected enum ELEMENT_TYPE {CLASS,METHOD,FIELD,PARAMETER,LOCAL} protected LuaIdentifierHighlighterAppComponent _appComponent = null; protected Editor _editor = null; protected ArrayList<RangeHighlighter> _highlights = null; protected ArrayList<Boolean> _forWriting = null; protected String _currentIdentifier = null; // protected ELEMENT_TYPE _elemType = null; protected int _startElem = -1; protected int _currElem = -1; protected int _declareElem = -1; protected boolean _ignoreEvents; protected boolean _identifiersLocked = false; protected PsiReferenceComparator _psiRefComp = null; public LuaIdentifierHighlighterEditorComponent(LuaIdentifierHighlighterAppComponent appComponent, Editor editor) { _appComponent = appComponent; _ignoreEvents = false;//!_appComponent.is_pluginEnabled(); _editor = editor; _editor.getCaretModel().addCaretListener(this); _editor.getDocument().addDocumentListener(this); _psiRefComp = new PsiReferenceComparator(); } //CaretListener interface implementation public void caretPositionChanged(final CaretEvent ce) { //Execute later so we are not searching Psi model while updating it //Fixes Idea 7 exception SwingUtilities.invokeLater(new Runnable() { public void run() { handleCaretPositionChanged(ce); } }); } protected void handleCaretPositionChanged(CaretEvent ce) { // if(_ignoreEvents) // return; // if(_identifiersLocked) // return; if (_editor == null) return; if (_editor.getProject() == null) return; if (_editor.getDocument() == null) return; PsiFile pFile = PsiDocumentManager.getInstance(_editor.getProject()).getPsiFile(_editor.getDocument()); if (pFile == null) return; PsiElement pElem = pFile.findElementAt(_editor.getCaretModel().getOffset()); if (pElem == null || pElem.getParent() == null || !(pElem.getParent() instanceof LuaIdentifier)) pElem = null; if (pElem == null) { if (_highlights != null) clearState(); return; } //We have a pElem //Check if different identifier than before if (_highlights != null) { int foundElem = -1; TextRange pElemRange = pElem.getTextRange(); for (int i = 0; i < _highlights.size(); i++) { RangeHighlighter highlight = _highlights.get(i); if ((highlight.getStartOffset() == pElemRange.getStartOffset()) && (highlight.getEndOffset() == pElemRange.getEndOffset())) { foundElem = i; break; } } if (foundElem != -1) { if (foundElem != _currElem) { moveIdentifier(foundElem); _startElem = foundElem; } return; } else clearState(); } _currentIdentifier = pElem.getText(); - log.info("identifier "+pElem.getText()); + log.info("Caret on identifier "+pElem.getText()); ArrayList<PsiElement> elems = new ArrayList<PsiElement>(); PsiReference pRef = pFile.findReferenceAt(_editor.getCaretModel().getOffset()); if (pRef == null) { //See if I am a declaration so search for references to me PsiElement pElemCtx = pElem.getContext(); // if(pElemCtx instanceof PsiClass) // _elemType = ELEMENT_TYPE.CLASS; // else if(pElemCtx instanceof PsiMethod) // _elemType = ELEMENT_TYPE.METHOD; // else if(pElemCtx instanceof PsiField) // _elemType = ELEMENT_TYPE.FIELD; // else if(pElemCtx instanceof PsiParameter) // _elemType = ELEMENT_TYPE.PARAMETER; // else if(pElemCtx instanceof PsiLocalVariable) // _elemType = ELEMENT_TYPE.LOCAL; if (pElemCtx == LuaElementTypes.VARIABLE) log.info("Caret on VARIABLE:" + pElem); else if (pElemCtx == LuaElementTypes.PARAMETER) log.info("Caret on PARAMETER:" + pElem); Query<PsiReference> q = ReferencesSearch.search(pElemCtx, GlobalSearchScope.fileScope(pFile)); PsiReference qRefs[] = q.toArray(new PsiReference[0]); //Sort by text offset Arrays.sort(qRefs, _psiRefComp); for (PsiReference qRef : qRefs) { //Find child PsiIdentifier so highlight is just on it PsiElement qRefElem = qRef.getElement(); LuaIdentifier qRefElemIdent = findChildIdentifier(qRefElem, pElem.getText()); if (qRefElemIdent == null) continue; //Skip elements from other files if (!areSameFiles(pFile, qRefElemIdent.getContainingFile())) continue; //Check if I should be put in list first to keep it sorted by text offset if ((_declareElem == -1) && (pElem.getTextOffset() <= qRefElemIdent.getTextOffset())) { elems.add(pElem); _declareElem = elems.size() - 1; } elems.add(qRefElemIdent); } //If haven't put me in list yet, put me in last if (_declareElem == -1) { elems.add(pElem); _declareElem = elems.size() - 1; } } else { //Resolve to declaration + log.info("resolving "+pRef); PsiElement pRefElem; try { pRefElem = pRef.resolve(); } catch (Throwable t) { pRefElem = null; } if (pRefElem != null) { // if(pRefElem instanceof PsiClass) // _elemType = ELEMENT_TYPE.CLASS; // else if(pRefElem instanceof PsiMethod) // _elemType = ELEMENT_TYPE.METHOD; // else if(pRefElem instanceof PsiField) // _elemType = ELEMENT_TYPE.FIELD; // else if(pRefElem instanceof PsiParameter) // _elemType = ELEMENT_TYPE.PARAMETER; // else if(pRefElem instanceof PsiLocalVariable) // _elemType = ELEMENT_TYPE.LOCAL; if (pRefElem == LuaElementTypes.VARIABLE) log.info("Resolved to VARIABLE:" + pElem); else if (pRefElem == LuaElementTypes.PARAMETER) - log.info("Resolved to PARAMETER:" + pElem); + log.info("Resolved to PARAMETER:" + pElem); + else if (pRefElem == LuaElementTypes.LOCAL_NAME_DECL) + log.info("Resolved to LOCAL_NAME_DECL:" + pElem); } if (pRefElem != null) { LuaIdentifier pRefElemIdent = findChildIdentifier(pRefElem, pElem.getText()); if (pRefElemIdent != null) { //Search for references to my declaration - Query<PsiReference> q = ReferencesSearch.search(pRefElemIdent.getContext(), GlobalSearchScope.fileScope(pFile)); + Query<PsiReference> q = ReferencesSearch.search(pRefElemIdent, GlobalSearchScope.fileScope(pFile)); PsiReference qRefs[] = q.toArray(new PsiReference[0]); //Sort by text offset Arrays.sort(qRefs, _psiRefComp); for (PsiReference qRef : qRefs) { //Find child PsiIdentifier so highlight is just on it PsiElement qRefElem = qRef.getElement(); LuaIdentifier qRefElemIdent = findChildIdentifier(qRefElem, pElem.getText()); if (qRefElemIdent == null) continue; //Skip elements from other files if (!areSameFiles(pFile, qRefElemIdent.getContainingFile())) continue; //Check if I should be put in list first to keep it sorted by text offset if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1) && (pRefElemIdent.getTextOffset() <= qRefElemIdent.getTextOffset())) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } elems.add(qRefElemIdent); } if (elems.size() == 0) { //Should at least put the original found element at cursor in list //Check if I should be put in list first to keep it sorted by text offset if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1) && (pRefElemIdent.getTextOffset() <= pElem.getTextOffset())) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } elems.add(pElem); } //If haven't put me in list yet, put me in last if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1)) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } } } else { //No declaration found, so resort to simple string search PsiSearchHelper search = pElem.getManager().getSearchHelper(); PsiElement idents[] = search.findCommentsContainingIdentifier(pElem.getText(), GlobalSearchScope.fileScope(pFile)); for (PsiElement ident : idents) elems.add(ident); } } _highlights = new ArrayList<RangeHighlighter>(); _forWriting = new ArrayList<Boolean>(); for (int i = 0; i < elems.size(); i++) { PsiElement elem = elems.get(i); TextRange range = elem.getTextRange(); //Verify range is valid against current length of document if ((range.getStartOffset() >= _editor.getDocument().getTextLength()) || (range.getEndOffset() >= _editor.getDocument().getTextLength())) continue; boolean forWriting = isForWriting(elem); _forWriting.add(forWriting); RangeHighlighter rh; if (elem.getTextRange().equals(pElem.getTextRange())) { _startElem = i; _currElem = i; rh = _editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), getHighlightLayer(), getActiveHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getActiveHighlightColor(forWriting).getBackgroundColor()); } else { rh = _editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), getHighlightLayer(), getHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getHighlightColor(forWriting).getBackgroundColor()); } // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeTooltip(_currentIdentifier + " [" + i + "]"); _highlights.add(rh); } } protected boolean isForWriting(PsiElement elem) { PsiExpression parentExpression = PsiTreeUtil.getParentOfType(elem, PsiExpression.class); if (parentExpression != null) return (PsiUtil.isAccessedForWriting(parentExpression)); else { PsiVariable parentVariable = PsiTreeUtil.getParentOfType(elem, PsiVariable.class); if (parentVariable != null) { PsiExpression initializer = parentVariable.getInitializer(); return (initializer != null); } } return (false); } protected boolean areSameFiles(PsiFile editorFile, PsiFile candidateFile) { if ((editorFile == null) && (candidateFile == null)) return (true); if (editorFile == null) return (true); if (candidateFile == null) return (true); String editorFileName = editorFile.getName(); String candidateFileName = candidateFile.getName(); if ((editorFileName == null) && (candidateFileName == null)) return (true); if (editorFileName == null) return (true); if (candidateFileName == null) return (true); return (editorFileName.equals(candidateFileName)); } protected LuaIdentifier findChildIdentifier(PsiElement parent, String childText) { if ((parent instanceof LuaIdentifier) && (parent.getText().equals(childText))) return ((LuaIdentifier) parent); //Packages don't implement getChildren yet they don't throw an exception. It is caught internally so I can't catch it. // if(parent instanceof PsiPackage) // return(null); PsiElement children[] = parent.getChildren(); if (children.length == 0) return (null); for (PsiElement child : children) { LuaIdentifier foundElem = findChildIdentifier(child, childText); if (foundElem != null) return (foundElem); } return (null); } protected boolean isHighlightEnabled() { return _appComponent.isEnabled(); // if(_elemType == ELEMENT_TYPE.CLASS) // return(_appComponent.is_classHighlightEnabled()); // else if(_elemType == ELEMENT_TYPE.METHOD) // return(_appComponent.is_methodHighlightEnabled()); // else if(_elemType == ELEMENT_TYPE.FIELD) // return(_appComponent.is_fieldHighlightEnabled()); // else if(_elemType == ELEMENT_TYPE.PARAMETER) // return(_appComponent.is_paramHighlightEnabled()); // else if(_elemType == ELEMENT_TYPE.LOCAL) // return(_appComponent.is_localHighlightEnabled()); // else // return(_appComponent.is_otherHighlightEnabled()); } protected TextAttributes getActiveHighlightColor(boolean forWriting) { TextAttributes retVal = new TextAttributes(); if (!isHighlightEnabled()) return (retVal); // Color c; // if(_elemType == ELEMENT_TYPE.CLASS) // c = IdentifierHighlighterConfiguration.getColorFromString(_appComponent.get_classActiveHighlightColor()); // else if(_elemType == ELEMENT_TYPE.METHOD) // c = IdentifierHighlighterConfiguration.getColorFromString(_appComponent.get_methodActiveHighlightColor()); // else if(_elemType == ELEMENT_TYPE.FIELD) // c = IdentifierHighlighterConfiguration.getColorFromString(forWriting ? _appComponent.get_fieldWriteActiveHighlightColor() : _appComponent.get_fieldReadActiveHighlightColor()); // else if(_elemType == ELEMENT_TYPE.PARAMETER) // c = IdentifierHighlighterConfiguration.getColorFromString(forWriting ? _appComponent.get_paramWriteActiveHighlightColor() : _appComponent.get_paramReadActiveHighlightColor()); // else if(_elemType == ELEMENT_TYPE.LOCAL) // c = IdentifierHighlighterConfiguration.getColorFromString(forWriting ? _appComponent.get_localWriteActiveHighlightColor() : _appComponent.get_localReadActiveHighlightColor()); // else // c = IdentifierHighlighterConfiguration.getColorFromString(_appComponent.get_otherActiveHighlightColor()); retVal.setBackgroundColor(Color.GREEN); return (retVal); } protected TextAttributes getHighlightColor(boolean forWriting) { TextAttributes retVal = new TextAttributes(); if (!isHighlightEnabled()) return (retVal); // Color c; // if(_elemType == ELEMENT_TYPE.CLASS) // c = IdentifierHighlighterConfiguration.getColorFromString(_appComponent.get_classHighlightColor()); // else if(_elemType == ELEMENT_TYPE.METHOD) // c = IdentifierHighlighterConfiguration.getColorFromString(_appComponent.get_methodHighlightColor()); // else if(_elemType == ELEMENT_TYPE.FIELD) // c = IdentifierHighlighterConfiguration.getColorFromString(forWriting ? _appComponent.get_fieldWriteHighlightColor() : _appComponent.get_fieldReadHighlightColor()); // else if(_elemType == ELEMENT_TYPE.PARAMETER) // c = IdentifierHighlighterConfiguration.getColorFromString(forWriting ? _appComponent.get_paramWriteHighlightColor() : _appComponent.get_paramReadHighlightColor()); // else if(_elemType == ELEMENT_TYPE.LOCAL) // c = IdentifierHighlighterConfiguration.getColorFromString(forWriting ? _appComponent.get_localWriteHighlightColor() : _appComponent.get_localReadHighlightColor()); // else // c = IdentifierHighlighterConfiguration.getColorFromString(_appComponent.get_otherHighlightColor()); retVal.setBackgroundColor(Color.YELLOW); return (retVal); } protected int getHighlightLayer() { // String highlightLayer = _appComponent.get_highlightLayer(); // if(highlightLayer.equals("SELECTION")) // return(HighlighterLayer.SELECTION); // else if(highlightLayer.equals("ERROR")) // return(HighlighterLayer.ERROR); // else if(highlightLayer.equals("WARNING")) // return(HighlighterLayer.WARNING); // else if(highlightLayer.equals("GUARDED_BLOCKS")) // return(HighlighterLayer.GUARDED_BLOCKS); // else if(highlightLayer.equals("ADDITIONAL_SYNTAX")) // return(HighlighterLayer.ADDITIONAL_SYNTAX); // else if(highlightLayer.equals("SYNTAX")) // return(HighlighterLayer.SYNTAX); // else if(highlightLayer.equals("CARET_ROW")) // return(HighlighterLayer.CARET_ROW); return (HighlighterLayer.ADDITIONAL_SYNTAX); } //DocumentListener interface implementation public void beforeDocumentChange(DocumentEvent de) { } public void documentChanged(DocumentEvent de) { if (_ignoreEvents) return; caretPositionChanged(null); } protected void clearState() { if (_highlights != null) { for (RangeHighlighter highlight : _highlights) _editor.getMarkupModel().removeHighlighter(highlight); } _highlights = null; _forWriting = null; _currentIdentifier = null; // _elemType = null; _startElem = -1; _currElem = -1; _declareElem = -1; // unlockIdentifiers(); } public void dispose() { clearState(); _editor.getCaretModel().removeCaretListener(this); _editor.getDocument().removeDocumentListener(this); _editor = null; } public void repaint() { if(_highlights == null) return; for(int i = 0; i < _highlights.size(); i++) { RangeHighlighter rh = _highlights.get(i); boolean forWriting = _forWriting.get(i); int startOffset = rh.getStartOffset(); int endOffset = rh.getEndOffset(); _editor.getMarkupModel().removeHighlighter(rh); if(i == _currElem) { rh = _editor.getMarkupModel().addRangeHighlighter(startOffset,endOffset,getHighlightLayer(),getActiveHighlightColor(forWriting),HighlighterTargetArea.EXACT_RANGE); //// if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getActiveHighlightColor(forWriting).getBackgroundColor()); } else { rh = _editor.getMarkupModel().addRangeHighlighter(startOffset,endOffset,getHighlightLayer(),getHighlightColor(forWriting),HighlighterTargetArea.EXACT_RANGE); //// if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getHighlightColor(forWriting).getBackgroundColor()); } //// if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeTooltip(_currentIdentifier + " [" + i + "]"); _highlights.set(i,rh); } } // // public void enablePlugin(boolean enable) // { // clearState(); // _ignoreEvents = !enable; // } // // public void startIdentifier() // { // if(_highlights == null) // return; // moveIdentifier(_startElem); // int offset = _highlights.get(_currElem).getStartOffset(); // _editor.getCaretModel().moveToOffset(offset); // _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); // } // // public void declareIdentifier() // { // if(_highlights == null) // return; // if(_declareElem == -1) // return; // moveIdentifier(_declareElem); // int offset = _highlights.get(_currElem).getStartOffset(); // _editor.getCaretModel().moveToOffset(offset); // _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); // } // // public void nextIdentifier() // { // if(_highlights == null) // return; // int newIndex = _currElem + 1; // if(newIndex == _highlights.size()) // return; // moveIdentifier(newIndex); // int offset = _highlights.get(_currElem).getStartOffset(); // _editor.getCaretModel().moveToOffset(offset); // _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); // } // // public void previousIdentifier() // { // if(_highlights == null) // return; // int newIndex = _currElem - 1; // if(newIndex == -1) // return; // moveIdentifier(newIndex); // int offset = _highlights.get(_currElem).getStartOffset(); // _editor.getCaretModel().moveToOffset(offset); // _editor.getScrollingModel().scrollToCaret(ScrollType.CENTER); // } // // public String getCurrentIdentifier() // { // return(_currentIdentifier); // } // // public void renameIdentifier(String newIdentifier) // { // if(_highlights == null) // return; // _ignoreEvents = true; // try { // for(RangeHighlighter rh : _highlights) { // int startOffset = rh.getStartOffset(); // int endOffset = rh.getEndOffset(); // _editor.getDocument().replaceString(startOffset,endOffset,newIdentifier); // } // } catch(Throwable t) { // //Ignore // } finally { // _ignoreEvents = false; // } // //Simulate a caret position change so everything is up-to-date // unlockIdentifiers(); // caretPositionChanged(null); // } // // public void lockIdentifiers() // { // if(_identifiersLocked) // return; // _identifiersLocked = true; // } // // public void unlockIdentifiers() // { // if(!_identifiersLocked) // return; // _identifiersLocked = false; // //Simulate a caret position change so everything is up-to-date // caretPositionChanged(null); // } // // public boolean areIdentifiersLocked() // { // return(_identifiersLocked); // } // protected void moveIdentifier(int index) { try { if (_currElem != -1) { RangeHighlighter rh = _highlights.get(_currElem); boolean forWriting = _forWriting.get(_currElem); int startOffset = rh.getStartOffset(); int endOffset = rh.getEndOffset(); _editor.getMarkupModel().removeHighlighter(rh); rh = _editor.getMarkupModel().addRangeHighlighter(startOffset, endOffset, getHighlightLayer(), getHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) { rh.setErrorStripeMarkColor(getHighlightColor(forWriting).getBackgroundColor()); rh.setErrorStripeTooltip(_currentIdentifier + " [" + _currElem + "]"); // } _highlights.set(_currElem, rh); } _currElem = index; RangeHighlighter rh = _highlights.get(_currElem); boolean forWriting = _forWriting.get(_currElem); int startOffset = rh.getStartOffset(); int endOffset = rh.getEndOffset(); _editor.getMarkupModel().removeHighlighter(rh); rh = _editor.getMarkupModel().addRangeHighlighter(startOffset, endOffset, getHighlightLayer(), getActiveHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) { rh.setErrorStripeMarkColor(getActiveHighlightColor(forWriting).getBackgroundColor()); rh.setErrorStripeTooltip(_currentIdentifier + " [" + _currElem + "]"); // } _highlights.set(_currElem, rh); } catch (Throwable t) { //Ignore } } protected class PsiReferenceComparator implements Comparator<PsiReference> { public int compare(PsiReference ref1, PsiReference ref2) { int offset1 = ref1.getElement().getTextOffset(); int offset2 = ref2.getElement().getTextOffset(); return (offset1 - offset2); } } }
false
true
protected void handleCaretPositionChanged(CaretEvent ce) { // if(_ignoreEvents) // return; // if(_identifiersLocked) // return; if (_editor == null) return; if (_editor.getProject() == null) return; if (_editor.getDocument() == null) return; PsiFile pFile = PsiDocumentManager.getInstance(_editor.getProject()).getPsiFile(_editor.getDocument()); if (pFile == null) return; PsiElement pElem = pFile.findElementAt(_editor.getCaretModel().getOffset()); if (pElem == null || pElem.getParent() == null || !(pElem.getParent() instanceof LuaIdentifier)) pElem = null; if (pElem == null) { if (_highlights != null) clearState(); return; } //We have a pElem //Check if different identifier than before if (_highlights != null) { int foundElem = -1; TextRange pElemRange = pElem.getTextRange(); for (int i = 0; i < _highlights.size(); i++) { RangeHighlighter highlight = _highlights.get(i); if ((highlight.getStartOffset() == pElemRange.getStartOffset()) && (highlight.getEndOffset() == pElemRange.getEndOffset())) { foundElem = i; break; } } if (foundElem != -1) { if (foundElem != _currElem) { moveIdentifier(foundElem); _startElem = foundElem; } return; } else clearState(); } _currentIdentifier = pElem.getText(); log.info("identifier "+pElem.getText()); ArrayList<PsiElement> elems = new ArrayList<PsiElement>(); PsiReference pRef = pFile.findReferenceAt(_editor.getCaretModel().getOffset()); if (pRef == null) { //See if I am a declaration so search for references to me PsiElement pElemCtx = pElem.getContext(); // if(pElemCtx instanceof PsiClass) // _elemType = ELEMENT_TYPE.CLASS; // else if(pElemCtx instanceof PsiMethod) // _elemType = ELEMENT_TYPE.METHOD; // else if(pElemCtx instanceof PsiField) // _elemType = ELEMENT_TYPE.FIELD; // else if(pElemCtx instanceof PsiParameter) // _elemType = ELEMENT_TYPE.PARAMETER; // else if(pElemCtx instanceof PsiLocalVariable) // _elemType = ELEMENT_TYPE.LOCAL; if (pElemCtx == LuaElementTypes.VARIABLE) log.info("Caret on VARIABLE:" + pElem); else if (pElemCtx == LuaElementTypes.PARAMETER) log.info("Caret on PARAMETER:" + pElem); Query<PsiReference> q = ReferencesSearch.search(pElemCtx, GlobalSearchScope.fileScope(pFile)); PsiReference qRefs[] = q.toArray(new PsiReference[0]); //Sort by text offset Arrays.sort(qRefs, _psiRefComp); for (PsiReference qRef : qRefs) { //Find child PsiIdentifier so highlight is just on it PsiElement qRefElem = qRef.getElement(); LuaIdentifier qRefElemIdent = findChildIdentifier(qRefElem, pElem.getText()); if (qRefElemIdent == null) continue; //Skip elements from other files if (!areSameFiles(pFile, qRefElemIdent.getContainingFile())) continue; //Check if I should be put in list first to keep it sorted by text offset if ((_declareElem == -1) && (pElem.getTextOffset() <= qRefElemIdent.getTextOffset())) { elems.add(pElem); _declareElem = elems.size() - 1; } elems.add(qRefElemIdent); } //If haven't put me in list yet, put me in last if (_declareElem == -1) { elems.add(pElem); _declareElem = elems.size() - 1; } } else { //Resolve to declaration PsiElement pRefElem; try { pRefElem = pRef.resolve(); } catch (Throwable t) { pRefElem = null; } if (pRefElem != null) { // if(pRefElem instanceof PsiClass) // _elemType = ELEMENT_TYPE.CLASS; // else if(pRefElem instanceof PsiMethod) // _elemType = ELEMENT_TYPE.METHOD; // else if(pRefElem instanceof PsiField) // _elemType = ELEMENT_TYPE.FIELD; // else if(pRefElem instanceof PsiParameter) // _elemType = ELEMENT_TYPE.PARAMETER; // else if(pRefElem instanceof PsiLocalVariable) // _elemType = ELEMENT_TYPE.LOCAL; if (pRefElem == LuaElementTypes.VARIABLE) log.info("Resolved to VARIABLE:" + pElem); else if (pRefElem == LuaElementTypes.PARAMETER) log.info("Resolved to PARAMETER:" + pElem); } if (pRefElem != null) { LuaIdentifier pRefElemIdent = findChildIdentifier(pRefElem, pElem.getText()); if (pRefElemIdent != null) { //Search for references to my declaration Query<PsiReference> q = ReferencesSearch.search(pRefElemIdent.getContext(), GlobalSearchScope.fileScope(pFile)); PsiReference qRefs[] = q.toArray(new PsiReference[0]); //Sort by text offset Arrays.sort(qRefs, _psiRefComp); for (PsiReference qRef : qRefs) { //Find child PsiIdentifier so highlight is just on it PsiElement qRefElem = qRef.getElement(); LuaIdentifier qRefElemIdent = findChildIdentifier(qRefElem, pElem.getText()); if (qRefElemIdent == null) continue; //Skip elements from other files if (!areSameFiles(pFile, qRefElemIdent.getContainingFile())) continue; //Check if I should be put in list first to keep it sorted by text offset if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1) && (pRefElemIdent.getTextOffset() <= qRefElemIdent.getTextOffset())) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } elems.add(qRefElemIdent); } if (elems.size() == 0) { //Should at least put the original found element at cursor in list //Check if I should be put in list first to keep it sorted by text offset if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1) && (pRefElemIdent.getTextOffset() <= pElem.getTextOffset())) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } elems.add(pElem); } //If haven't put me in list yet, put me in last if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1)) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } } } else { //No declaration found, so resort to simple string search PsiSearchHelper search = pElem.getManager().getSearchHelper(); PsiElement idents[] = search.findCommentsContainingIdentifier(pElem.getText(), GlobalSearchScope.fileScope(pFile)); for (PsiElement ident : idents) elems.add(ident); } } _highlights = new ArrayList<RangeHighlighter>(); _forWriting = new ArrayList<Boolean>(); for (int i = 0; i < elems.size(); i++) { PsiElement elem = elems.get(i); TextRange range = elem.getTextRange(); //Verify range is valid against current length of document if ((range.getStartOffset() >= _editor.getDocument().getTextLength()) || (range.getEndOffset() >= _editor.getDocument().getTextLength())) continue; boolean forWriting = isForWriting(elem); _forWriting.add(forWriting); RangeHighlighter rh; if (elem.getTextRange().equals(pElem.getTextRange())) { _startElem = i; _currElem = i; rh = _editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), getHighlightLayer(), getActiveHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getActiveHighlightColor(forWriting).getBackgroundColor()); } else { rh = _editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), getHighlightLayer(), getHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getHighlightColor(forWriting).getBackgroundColor()); } // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeTooltip(_currentIdentifier + " [" + i + "]"); _highlights.add(rh); } }
protected void handleCaretPositionChanged(CaretEvent ce) { // if(_ignoreEvents) // return; // if(_identifiersLocked) // return; if (_editor == null) return; if (_editor.getProject() == null) return; if (_editor.getDocument() == null) return; PsiFile pFile = PsiDocumentManager.getInstance(_editor.getProject()).getPsiFile(_editor.getDocument()); if (pFile == null) return; PsiElement pElem = pFile.findElementAt(_editor.getCaretModel().getOffset()); if (pElem == null || pElem.getParent() == null || !(pElem.getParent() instanceof LuaIdentifier)) pElem = null; if (pElem == null) { if (_highlights != null) clearState(); return; } //We have a pElem //Check if different identifier than before if (_highlights != null) { int foundElem = -1; TextRange pElemRange = pElem.getTextRange(); for (int i = 0; i < _highlights.size(); i++) { RangeHighlighter highlight = _highlights.get(i); if ((highlight.getStartOffset() == pElemRange.getStartOffset()) && (highlight.getEndOffset() == pElemRange.getEndOffset())) { foundElem = i; break; } } if (foundElem != -1) { if (foundElem != _currElem) { moveIdentifier(foundElem); _startElem = foundElem; } return; } else clearState(); } _currentIdentifier = pElem.getText(); log.info("Caret on identifier "+pElem.getText()); ArrayList<PsiElement> elems = new ArrayList<PsiElement>(); PsiReference pRef = pFile.findReferenceAt(_editor.getCaretModel().getOffset()); if (pRef == null) { //See if I am a declaration so search for references to me PsiElement pElemCtx = pElem.getContext(); // if(pElemCtx instanceof PsiClass) // _elemType = ELEMENT_TYPE.CLASS; // else if(pElemCtx instanceof PsiMethod) // _elemType = ELEMENT_TYPE.METHOD; // else if(pElemCtx instanceof PsiField) // _elemType = ELEMENT_TYPE.FIELD; // else if(pElemCtx instanceof PsiParameter) // _elemType = ELEMENT_TYPE.PARAMETER; // else if(pElemCtx instanceof PsiLocalVariable) // _elemType = ELEMENT_TYPE.LOCAL; if (pElemCtx == LuaElementTypes.VARIABLE) log.info("Caret on VARIABLE:" + pElem); else if (pElemCtx == LuaElementTypes.PARAMETER) log.info("Caret on PARAMETER:" + pElem); Query<PsiReference> q = ReferencesSearch.search(pElemCtx, GlobalSearchScope.fileScope(pFile)); PsiReference qRefs[] = q.toArray(new PsiReference[0]); //Sort by text offset Arrays.sort(qRefs, _psiRefComp); for (PsiReference qRef : qRefs) { //Find child PsiIdentifier so highlight is just on it PsiElement qRefElem = qRef.getElement(); LuaIdentifier qRefElemIdent = findChildIdentifier(qRefElem, pElem.getText()); if (qRefElemIdent == null) continue; //Skip elements from other files if (!areSameFiles(pFile, qRefElemIdent.getContainingFile())) continue; //Check if I should be put in list first to keep it sorted by text offset if ((_declareElem == -1) && (pElem.getTextOffset() <= qRefElemIdent.getTextOffset())) { elems.add(pElem); _declareElem = elems.size() - 1; } elems.add(qRefElemIdent); } //If haven't put me in list yet, put me in last if (_declareElem == -1) { elems.add(pElem); _declareElem = elems.size() - 1; } } else { //Resolve to declaration log.info("resolving "+pRef); PsiElement pRefElem; try { pRefElem = pRef.resolve(); } catch (Throwable t) { pRefElem = null; } if (pRefElem != null) { // if(pRefElem instanceof PsiClass) // _elemType = ELEMENT_TYPE.CLASS; // else if(pRefElem instanceof PsiMethod) // _elemType = ELEMENT_TYPE.METHOD; // else if(pRefElem instanceof PsiField) // _elemType = ELEMENT_TYPE.FIELD; // else if(pRefElem instanceof PsiParameter) // _elemType = ELEMENT_TYPE.PARAMETER; // else if(pRefElem instanceof PsiLocalVariable) // _elemType = ELEMENT_TYPE.LOCAL; if (pRefElem == LuaElementTypes.VARIABLE) log.info("Resolved to VARIABLE:" + pElem); else if (pRefElem == LuaElementTypes.PARAMETER) log.info("Resolved to PARAMETER:" + pElem); else if (pRefElem == LuaElementTypes.LOCAL_NAME_DECL) log.info("Resolved to LOCAL_NAME_DECL:" + pElem); } if (pRefElem != null) { LuaIdentifier pRefElemIdent = findChildIdentifier(pRefElem, pElem.getText()); if (pRefElemIdent != null) { //Search for references to my declaration Query<PsiReference> q = ReferencesSearch.search(pRefElemIdent, GlobalSearchScope.fileScope(pFile)); PsiReference qRefs[] = q.toArray(new PsiReference[0]); //Sort by text offset Arrays.sort(qRefs, _psiRefComp); for (PsiReference qRef : qRefs) { //Find child PsiIdentifier so highlight is just on it PsiElement qRefElem = qRef.getElement(); LuaIdentifier qRefElemIdent = findChildIdentifier(qRefElem, pElem.getText()); if (qRefElemIdent == null) continue; //Skip elements from other files if (!areSameFiles(pFile, qRefElemIdent.getContainingFile())) continue; //Check if I should be put in list first to keep it sorted by text offset if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1) && (pRefElemIdent.getTextOffset() <= qRefElemIdent.getTextOffset())) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } elems.add(qRefElemIdent); } if (elems.size() == 0) { //Should at least put the original found element at cursor in list //Check if I should be put in list first to keep it sorted by text offset if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1) && (pRefElemIdent.getTextOffset() <= pElem.getTextOffset())) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } elems.add(pElem); } //If haven't put me in list yet, put me in last if ((areSameFiles(pFile, pRefElemIdent.getContainingFile())) && (_declareElem == -1)) { elems.add(pRefElemIdent); _declareElem = elems.size() - 1; } } } else { //No declaration found, so resort to simple string search PsiSearchHelper search = pElem.getManager().getSearchHelper(); PsiElement idents[] = search.findCommentsContainingIdentifier(pElem.getText(), GlobalSearchScope.fileScope(pFile)); for (PsiElement ident : idents) elems.add(ident); } } _highlights = new ArrayList<RangeHighlighter>(); _forWriting = new ArrayList<Boolean>(); for (int i = 0; i < elems.size(); i++) { PsiElement elem = elems.get(i); TextRange range = elem.getTextRange(); //Verify range is valid against current length of document if ((range.getStartOffset() >= _editor.getDocument().getTextLength()) || (range.getEndOffset() >= _editor.getDocument().getTextLength())) continue; boolean forWriting = isForWriting(elem); _forWriting.add(forWriting); RangeHighlighter rh; if (elem.getTextRange().equals(pElem.getTextRange())) { _startElem = i; _currElem = i; rh = _editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), getHighlightLayer(), getActiveHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getActiveHighlightColor(forWriting).getBackgroundColor()); } else { rh = _editor.getMarkupModel().addRangeHighlighter(range.getStartOffset(), range.getEndOffset(), getHighlightLayer(), getHighlightColor(forWriting), HighlighterTargetArea.EXACT_RANGE); // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeMarkColor(getHighlightColor(forWriting).getBackgroundColor()); } // if(_appComponent.is_showInMarkerBar()) rh.setErrorStripeTooltip(_currentIdentifier + " [" + i + "]"); _highlights.add(rh); } }
diff --git a/src/devflow/hoseotable/Chapel.java b/src/devflow/hoseotable/Chapel.java index ff4a415..1f96a0d 100644 --- a/src/devflow/hoseotable/Chapel.java +++ b/src/devflow/hoseotable/Chapel.java @@ -1,64 +1,64 @@ package devflow.hoseotable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * <p>ä�� �¼��� ���ϱ����� Class</p> * @author �Ȱ輺 */ public class Chapel { private JSONArray seatData ; public Chapel() { try { seatData = new JSONArray("[{S:1,C:8,L:'A',LS:1},{S:17,C:8,L:'A',LS:9},{S:49,C:8,L:'A',LS:17},{S:83,C:9,L:'A',LS:25},{S:119,C:9,L:'A',LS:34},{S:155,C:9,L:'A',LS:43},{S:191,C:10,L:'A',LS:52},{S:231,C:10,L:'A',LS:62},{S:271,C:10,L:'A',LS:72},{S:311,C:11,L:'A',LS:82},{S:355,C:11,L:'A',LS:93},{S:399,C:11,L:'A',LS:104},{S:443,C:11,L:'A',LS:115},{S:487,C:12,L:'A',LS:126},{S:25,C:8,L:'B',LS:1},{S:57,C:9,L:'B',LS:9},{S:92,C:9,L:'B',LS:18},{S:128,C:9,L:'B',LS:27},{S:164,C:9,L:'B',LS:36},{S:201,C:10,L:'B',LS:45},{S:241,C:10,L:'B',LS:55},{S:281,C:10,L:'B',LS:65},{S:322,C:11,L:'B',LS:75},{S:366,C:11,L:'B',LS:86},{S:410,C:11,L:'B',LS:97},{S:454,C:11,L:'B',LS:108},{S:499,C:12,L:'B',LS:119},{S:33,C:8,L:'C',LS:1},{S:66,C:9,L:'C',LS:9},{S:101,C:9,L:'C',LS:18},{S:137,C:9,L:'C',LS:27},{S:173,C:9,L:'C',LS:36},{S:211,C:10,L:'C',LS:45},{S:251,C:10,L:'C',LS:55},{S:291,C:10,L:'C',LS:65},{S:333,C:11,L:'C',LS:75},{S:377,C:11,L:'C',LS:86},{S:421,C:11,L:'C',LS:97},{S:465,C:11,L:'C',LS:108},{S:511,C:12,L:'C',LS:119},{S:9,C:8,L:'D',LS:1},{S:41,C:8,L:'D',LS:9},{S:75,C:8,L:'D',LS:17},{S:110,C:9,L:'D',LS:25},{S:146,C:9,L:'D',LS:34},{S:182,C:9,L:'D',LS:43},{S:221,C:10,L:'D',LS:52},{S:261,C:10,L:'D',LS:62},{S:301,C:10,L:'D',LS:72},{S:344,C:11,L:'D',LS:82},{S:388,C:11,L:'D',LS:93},{S:432,C:11,L:'D',LS:104},{S:476,C:11,L:'D',LS:115},{S:523,C:12,L:'D',LS:126},{S:535,C:7,L:'E',LS:1},{S:581,C:8,L:'E',LS:8},{S:629,C:8,L:'E',LS:16},{S:677,C:8,L:'E',LS:24},{S:725,C:8,L:'E',LS:32},{S:773,C:9,L:'E',LS:40},{S:827,C:9,L:'E',LS:49},{S:881,C:9,L:'E',LS:58},{S:935,C:9,L:'E',LS:67},{S:989,C:9,L:'E',LS:76},{S:1043,C:10,L:'E',LS:85},{S:1103,C:10,L:'E',LS:95},{S:1163,C:10,L:'E',LS:105},{S:1223,C:9,L:'E',LS:115},{S:542,C:8,L:'F',LS:1},{S:589,C:8,L:'F',LS:9},{S:637,C:8,L:'F',LS:17},{S:685,C:8,L:'F',LS:25},{S:733,C:8,L:'F',LS:33},{S:782,C:9,L:'F',LS:41},{S:836,C:9,L:'F',LS:50},{S:890,C:9,L:'F',LS:59},{S:944,C:9,L:'F',LS:68},{S:998,C:9,L:'F',LS:77},{S:1053,C:10,L:'F',LS:86},{S:1113,C:10,L:'F',LS:96},{S:1173,C:10,L:'F',LS:106},{S:1232,C:8,L:'F',LS:116},{S:550,C:8,L:'G',LS:1},{S:597,C:8,L:'G',LS:9},{S:645,C:8,L:'G',LS:17},{S:693,C:8,L:'G',LS:25},{S:741,C:8,L:'G',LS:33},{S:791,C:9,L:'G',LS:41},{S:845,C:9,L:'G',LS:50},{S:899,C:9,L:'G',LS:59},{S:953,C:9,L:'G',LS:68},{S:1007,C:9,L:'G',LS:77},{S:1063,C:10,L:'G',LS:86},{S:1123,C:10,L:'G',LS:96},{S:1183,C:10,L:'G',LS:106},{S:1240,C:7,L:'G',LS:116},{S:558,C:8,L:'H',LS:1},{S:605,C:8,L:'H',LS:9},{S:653,C:8,L:'H',LS:17},{S:701,C:8,L:'H',LS:25},{S:749,C:8,L:'H',LS:33},{S:800,C:9,L:'H',LS:41},{S:854,C:9,L:'H',LS:50},{S:908,C:9,L:'H',LS:59},{S:962,C:9,L:'H',LS:68},{S:1016,C:9,L:'H',LS:77},{S:1073,C:10,L:'H',LS:86},{S:1133,C:10,L:'H',LS:96},{S:1193,C:10,L:'H',LS:106},{S:1247,C:7,L:'H',LS:116},{S:566,C:8,L:'I',LS:1},{S:613,C:8,L:'I',LS:9},{S:661,C:8,L:'I',LS:17},{S:709,C:8,L:'I',LS:25},{S:757,C:8,L:'I',LS:33},{S:809,C:9,L:'I',LS:41},{S:863,C:9,L:'I',LS:50},{S:917,C:9,L:'I',LS:59},{S:971,C:9,L:'I',LS:68},{S:1025,C:9,L:'I',LS:77},{S:1083,C:10,L:'I',LS:86},{S:1143,C:10,L:'I',LS:96},{S:1203,C:10,L:'I',LS:106},{S:1254,C:8,L:'I',LS:116},{S:574,C:7,L:'J',LS:1},{S:621,C:8,L:'J',LS:8},{S:669,C:8,L:'J',LS:16},{S:717,C:8,L:'J',LS:24},{S:765,C:8,L:'J',LS:32},{S:818,C:9,L:'J',LS:40},{S:872,C:9,L:'J',LS:49},{S:926,C:9,L:'J',LS:58},{S:980,C:9,L:'J',LS:67},{S:1034,C:9,L:'J',LS:76},{S:1093,C:10,L:'J',LS:85},{S:1153,C:10,L:'J',LS:95},{S:1213,C:10,L:'J',LS:105},{S:1262,C:9,L:'J',LS:115},]"); // �� ������ ä�ð��� �¼�ǥ�� �������� JSON �������� �ۼ��� /* * S : ���� ��ȣ * C : Ⱦ �¼� ���� * L : �����¼��� ���� * LS : �����¼��� ���� ��ȣ */ }catch (JSONException e) { e.printStackTrace(); } } /** * <p>������ �¼��� ������ �¼����� ��ȯ. </p> * @author �Ȱ輺 * @return ����+������ �¼� String * @throws ã�� �� ���ų�, ������ �״�� �������� ǥ�� */ public String getSeat(int numbericSeat) { try { for(int i = 0; i <= seatData.length(); i++ ){ JSONObject lData = seatData.getJSONObject(i); int StartNumber = lData.getInt("S"); int LineCount = lData.getInt("C"); - if( StartNumber <= numbericSeat && StartNumber+LineCount > numbericSeat ) { + if( StartNumber <= numbericSeat && StartNumber+LineCount >= numbericSeat ) { String SeatLetter = lData.getString("L"); int LetterStart = lData.getInt("LS"); int offset = numbericSeat - StartNumber; offset = (LetterStart + offset); return SeatLetter + offset; } } return "ã�� �� ����"; }catch (JSONException e) { return "�����߻�"; } } }
true
true
public String getSeat(int numbericSeat) { try { for(int i = 0; i <= seatData.length(); i++ ){ JSONObject lData = seatData.getJSONObject(i); int StartNumber = lData.getInt("S"); int LineCount = lData.getInt("C"); if( StartNumber <= numbericSeat && StartNumber+LineCount > numbericSeat ) { String SeatLetter = lData.getString("L"); int LetterStart = lData.getInt("LS"); int offset = numbericSeat - StartNumber; offset = (LetterStart + offset); return SeatLetter + offset; } } return "ã�� �� ����"; }catch (JSONException e) { return "�����߻�"; } }
public String getSeat(int numbericSeat) { try { for(int i = 0; i <= seatData.length(); i++ ){ JSONObject lData = seatData.getJSONObject(i); int StartNumber = lData.getInt("S"); int LineCount = lData.getInt("C"); if( StartNumber <= numbericSeat && StartNumber+LineCount >= numbericSeat ) { String SeatLetter = lData.getString("L"); int LetterStart = lData.getInt("LS"); int offset = numbericSeat - StartNumber; offset = (LetterStart + offset); return SeatLetter + offset; } } return "ã�� �� ����"; }catch (JSONException e) { return "�����߻�"; } }
diff --git a/src/com/android/volley/RequestQueue.java b/src/com/android/volley/RequestQueue.java index bfcd7d4..5c0e7af 100644 --- a/src/com/android/volley/RequestQueue.java +++ b/src/com/android/volley/RequestQueue.java @@ -1,286 +1,286 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley; import android.os.Handler; import android.os.Looper; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.atomic.AtomicInteger; /** * A request dispatch queue with a thread pool of dispatchers. * * Calling {@link #add(Request)} will enqueue the given Request for dispatch, * resolving from either cache or network on a worker thread, and then delivering * a parsed response on the main thread. */ public class RequestQueue { /** Used for generating monotonically-increasing sequence numbers for requests. */ private AtomicInteger mSequenceGenerator = new AtomicInteger(); /** * Staging area for requests that already have a duplicate request in flight. * * <ul> * <li>containsKey(cacheKey) indicates that there is a request in flight for the given cache * key.</li> * <li>get(cacheKey) returns waiting requests for the given cache key. The in flight request * is <em>not</em> contained in that list. Is null if no requests are staged.</li> * </ul> */ private final Map<String, Queue<Request<?>>> mWaitingRequests = new HashMap<String, Queue<Request<?>>>(); /** * The set of all requests currently being processed by this RequestQueue. A Request * will be in this set if it is waiting in any queue or currently being processed by * any dispatcher. */ private final Set<Request<?>> mCurrentRequests = new HashSet<Request<?>>(); /** The cache triage queue. */ private final PriorityBlockingQueue<Request<?>> mCacheQueue = new PriorityBlockingQueue<Request<?>>(); /** The queue of requests that are actually going out to the network. */ private final PriorityBlockingQueue<Request<?>> mNetworkQueue = new PriorityBlockingQueue<Request<?>>(); /** Number of network request dispatcher threads to start. */ private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4; /** Cache interface for retrieving and storing responses. */ private final Cache mCache; /** Network interface for performing requests. */ private final Network mNetwork; /** Response delivery mechanism. */ private final ResponseDelivery mDelivery; /** The network dispatchers. */ private NetworkDispatcher[] mDispatchers; /** The cache dispatcher. */ private CacheDispatcher mCacheDispatcher; /** * Creates the worker pool. Processing will not begin until {@link #start()} is called. * * @param cache A Cache to use for persisting responses to disk * @param network A Network interface for performing HTTP requests * @param threadPoolSize Number of network dispatcher threads to create * @param delivery A ResponseDelivery interface for posting responses and errors */ public RequestQueue(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { mCache = cache; mNetwork = network; mDispatchers = new NetworkDispatcher[threadPoolSize]; mDelivery = delivery; } /** * Creates the worker pool. Processing will not begin until {@link #start()} is called. * * @param cache A Cache to use for persisting responses to disk * @param network A Network interface for performing HTTP requests * @param threadPoolSize Number of network dispatcher threads to create */ public RequestQueue(Cache cache, Network network, int threadPoolSize) { this(cache, network, threadPoolSize, new ExecutorDelivery(new Handler(Looper.getMainLooper()))); } /** * Creates the worker pool. Processing will not begin until {@link #start()} is called. * * @param cache A Cache to use for persisting responses to disk * @param network A Network interface for performing HTTP requests */ public RequestQueue(Cache cache, Network network) { this(cache, network, DEFAULT_NETWORK_THREAD_POOL_SIZE); } /** * Starts the dispatchers in this queue. */ public void start() { stop(); // Make sure any currently running dispatchers are stopped. // Create the cache dispatcher and start it. mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery); mCacheDispatcher.start(); // Create network dispatchers (and corresponding threads) up to the pool size. for (int i = 0; i < mDispatchers.length; i++) { NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork, mCache, mDelivery); mDispatchers[i] = networkDispatcher; networkDispatcher.start(); } } /** * Stops the cache and network dispatchers. */ public void stop() { if (mCacheDispatcher != null) { mCacheDispatcher.quit(); } for (int i = 0; i < mDispatchers.length; i++) { if (mDispatchers[i] != null) { mDispatchers[i].quit(); } } } /** * Gets a sequence number. */ public int getSequenceNumber() { return mSequenceGenerator.incrementAndGet(); } /** * Gets the {@link Cache} instance being used. */ public Cache getCache() { return mCache; } /** * A simple predicate or filter interface for Requests, for use by * {@link RequestQueue#cancelAll(RequestFilter)}. */ public interface RequestFilter { public boolean apply(Request<?> request); } /** * Cancels all requests in this queue for which the given filter applies. * @param filter The filtering function to use */ public void cancelAll(RequestFilter filter) { synchronized (mCurrentRequests) { for (Request<?> request : mCurrentRequests) { if (filter.apply(request)) { request.cancel(); } } } } /** * Cancels all requests in this queue with the given tag. Tag must be non-null * and equality is by identity. */ public void cancelAll(final Object tag) { if (tag == null) { throw new IllegalArgumentException("Cannot cancelAll with a null tag"); } cancelAll(new RequestFilter() { @Override public boolean apply(Request<?> request) { return request.getTag() == tag; } }); } /** * Adds a Request to the dispatch queue. * @param request The request to service * @return The passed-in request */ - public Request<?> add(Request<?> request) { + public <T> Request<T> add(Request<T> request) { // Tag the request as belonging to this queue and add it to the set of current requests. request.setRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } // Process requests in the order they are added. request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); // If the request is uncacheable, skip the cache queue and go straight to the network. if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } // Insert request into stage if there's already a request with the same cache key in flight. synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); if (mWaitingRequests.containsKey(cacheKey)) { // There is already a request in flight. Queue up. Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey); if (stagedRequests == null) { stagedRequests = new LinkedList<Request<?>>(); } stagedRequests.add(request); mWaitingRequests.put(cacheKey, stagedRequests); if (VolleyLog.DEBUG) { VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey); } } else { // Insert 'null' queue for this cacheKey, indicating there is now a request in // flight. mWaitingRequests.put(cacheKey, null); mCacheQueue.add(request); } return request; } } /** * Called from {@link Request#finish(String)}, indicating that processing of the given request * has finished. * * <p>Releases waiting requests for <code>request.getCacheKey()</code> if * <code>request.shouldCache()</code>.</p> */ void finish(Request<?> request) { // Remove from the set of requests currently being processed. synchronized (mCurrentRequests) { mCurrentRequests.remove(request); } if (request.shouldCache()) { synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); Queue<Request<?>> waitingRequests = mWaitingRequests.remove(cacheKey); if (waitingRequests != null) { if (VolleyLog.DEBUG) { VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.", waitingRequests.size(), cacheKey); } // Process all queued up requests. They won't be considered as in flight, but // that's not a problem as the cache has been primed by 'request'. mCacheQueue.addAll(waitingRequests); } } } } }
true
true
public Request<?> add(Request<?> request) { // Tag the request as belonging to this queue and add it to the set of current requests. request.setRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } // Process requests in the order they are added. request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); // If the request is uncacheable, skip the cache queue and go straight to the network. if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } // Insert request into stage if there's already a request with the same cache key in flight. synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); if (mWaitingRequests.containsKey(cacheKey)) { // There is already a request in flight. Queue up. Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey); if (stagedRequests == null) { stagedRequests = new LinkedList<Request<?>>(); } stagedRequests.add(request); mWaitingRequests.put(cacheKey, stagedRequests); if (VolleyLog.DEBUG) { VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey); } } else { // Insert 'null' queue for this cacheKey, indicating there is now a request in // flight. mWaitingRequests.put(cacheKey, null); mCacheQueue.add(request); } return request; } }
public <T> Request<T> add(Request<T> request) { // Tag the request as belonging to this queue and add it to the set of current requests. request.setRequestQueue(this); synchronized (mCurrentRequests) { mCurrentRequests.add(request); } // Process requests in the order they are added. request.setSequence(getSequenceNumber()); request.addMarker("add-to-queue"); // If the request is uncacheable, skip the cache queue and go straight to the network. if (!request.shouldCache()) { mNetworkQueue.add(request); return request; } // Insert request into stage if there's already a request with the same cache key in flight. synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); if (mWaitingRequests.containsKey(cacheKey)) { // There is already a request in flight. Queue up. Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey); if (stagedRequests == null) { stagedRequests = new LinkedList<Request<?>>(); } stagedRequests.add(request); mWaitingRequests.put(cacheKey, stagedRequests); if (VolleyLog.DEBUG) { VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey); } } else { // Insert 'null' queue for this cacheKey, indicating there is now a request in // flight. mWaitingRequests.put(cacheKey, null); mCacheQueue.add(request); } return request; } }
diff --git a/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java b/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java index c48dd219..2f46e262 100644 --- a/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java +++ b/asm/test/conform/org/objectweb/asm/ClassWriterComputeFramesTest.java @@ -1,271 +1,271 @@ /*** * ASM tests * Copyright (c) 2002-2005 France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package org.objectweb.asm; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.instrument.Instrumentation; import java.security.ProtectionDomain; import junit.framework.TestSuite; import org.objectweb.asm.util.TraceClassVisitor; /** * ClassWriter tests. * * @author Eric Bruneton */ public class ClassWriterComputeFramesTest extends AbstractTest { public static void premain( final String agentArgs, final Instrumentation inst) { inst.addTransformer(new ClassFileTransformer() { public byte[] transform( final ClassLoader loader, final String className, final Class<?> classBeingRedefined, final ProtectionDomain domain, final byte[] classFileBuffer) throws IllegalClassFormatException { String n = className.replace('/', '.'); if (n.indexOf("junit") != -1) { return null; } if (agentArgs.length() == 0 || n.indexOf(agentArgs) != -1) { return transformClass(n, classFileBuffer); } else { return null; } } }); } static byte[] transformClass(final String n, final byte[] clazz) { ClassReader cr = new ClassReader(clazz); ClassWriter cw = new ComputeClassWriter(ClassWriter.COMPUTE_FRAMES); cr.accept(new ClassVisitor(Opcodes.ASM4, cw) { @Override public void visit( final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { super.visit((version & 0xFFFF) < Opcodes.V1_6 ? Opcodes.V1_6 : version, access, name, signature, superName, interfaces); } }, ClassReader.SKIP_FRAMES); return cw.toByteArray(); } public static TestSuite suite() throws Exception { return new ClassWriterComputeFramesTest().getSuite(); } @Override public void test() throws Exception { try { Class.forName(n, true, getClass().getClassLoader()); } catch (NoClassDefFoundError ncdfe) { // ignored } catch (UnsatisfiedLinkError ule) { // ignored } catch (ClassFormatError cfe) { fail(cfe.getMessage()); } catch (VerifyError ve) { String s = n.replace('.', '/') + ".class"; InputStream is = getClass().getClassLoader().getResourceAsStream(s); ClassReader cr = new ClassReader(is); byte[] b = transformClass("", cr.b); StringWriter sw1 = new StringWriter(); StringWriter sw2 = new StringWriter(); sw2.write(ve.toString() + "\n"); ClassVisitor cv1 = new TraceClassVisitor(new PrintWriter(sw1)); ClassVisitor cv2 = new TraceClassVisitor(new PrintWriter(sw2)); cr.accept(cv1, 0); new ClassReader(b).accept(cv2, 0); String s1 = sw1.toString(); String s2 = sw2.toString(); assertEquals("different data", s1, s2); } } } /** * A ClassWriter that computes the common super class of two classes without * actually loading them with a ClassLoader. * * @author Eric Bruneton */ class ComputeClassWriter extends ClassWriter { private ClassLoader l = getClass().getClassLoader(); public ComputeClassWriter(final int flags) { super(flags); } @Override protected String getCommonSuperClass(final String type1, final String type2) { try { ClassReader info1 = typeInfo(type1); ClassReader info2 = typeInfo(type2); if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type2, info2, type1)) { return type1; } else { return "java/lang/Object"; } } if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type1, info1, type2)) { return type2; } else { return "java/lang/Object"; } } StringBuilder b1 = typeAncestors(type1, info1); StringBuilder b2 = typeAncestors(type2, info2); String result = "java/lang/Object"; int end1 = b1.length(); int end2 = b2.length(); while (true) { int start1 = b1.lastIndexOf(";", end1 - 1); int start2 = b2.lastIndexOf(";", end2 - 1); if (start1 != -1 && start2 != -1 - && end1 - start1 == end1 - start1) + && end1 - start1 == end2 - start2) { String p1 = b1.substring(start1 + 1, end1); String p2 = b2.substring(start2 + 1, end2); if (p1.equals(p2)) { result = p1; end1 = start1; end2 = start2; } else { return result; } } else { return result; } } } catch (IOException e) { throw new RuntimeException(e.toString()); } } /** * Returns the internal names of the ancestor classes of the given type. * * @param type the internal name of a class or interface. * @param info the ClassReader corresponding to 'type'. * @return a StringBuilder containing the ancestor classes of 'type', * separated by ';'. The returned string has the following format: * ";type1;type2 ... ;typeN", where type1 is 'type', and typeN is a * direct subclass of Object. If 'type' is Object, the returned * string is empty. * @throws IOException if the bytecode of 'type' or of some of its ancestor * class cannot be loaded. */ private StringBuilder typeAncestors(String type, ClassReader info) throws IOException { StringBuilder b = new StringBuilder(); while (!"java/lang/Object".equals(type)) { b.append(';').append(type); type = info.getSuperName(); info = typeInfo(type); } return b; } /** * Returns true if the given type implements the given interface. * * @param type the internal name of a class or interface. * @param info the ClassReader corresponding to 'type'. * @param itf the internal name of a interface. * @return true if 'type' implements directly or indirectly 'itf' * @throws IOException if the bytecode of 'type' or of some of its ancestor * class cannot be loaded. */ private boolean typeImplements(String type, ClassReader info, String itf) throws IOException { while (!"java/lang/Object".equals(type)) { String[] itfs = info.getInterfaces(); for (int i = 0; i < itfs.length; ++i) { if (itfs[i].equals(itf)) { return true; } } for (int i = 0; i < itfs.length; ++i) { if (typeImplements(itfs[i], typeInfo(itfs[i]), itf)) { return true; } } type = info.getSuperName(); info = typeInfo(type); } return false; } /** * Returns a ClassReader corresponding to the given class or interface. * * @param type the internal name of a class or interface. * @return the ClassReader corresponding to 'type'. * @throws IOException if the bytecode of 'type' cannot be loaded. */ private ClassReader typeInfo(final String type) throws IOException { InputStream is = l.getResourceAsStream(type + ".class"); try { return new ClassReader(is); } finally { is.close(); } } }
true
true
protected String getCommonSuperClass(final String type1, final String type2) { try { ClassReader info1 = typeInfo(type1); ClassReader info2 = typeInfo(type2); if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type2, info2, type1)) { return type1; } else { return "java/lang/Object"; } } if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type1, info1, type2)) { return type2; } else { return "java/lang/Object"; } } StringBuilder b1 = typeAncestors(type1, info1); StringBuilder b2 = typeAncestors(type2, info2); String result = "java/lang/Object"; int end1 = b1.length(); int end2 = b2.length(); while (true) { int start1 = b1.lastIndexOf(";", end1 - 1); int start2 = b2.lastIndexOf(";", end2 - 1); if (start1 != -1 && start2 != -1 && end1 - start1 == end1 - start1) { String p1 = b1.substring(start1 + 1, end1); String p2 = b2.substring(start2 + 1, end2); if (p1.equals(p2)) { result = p1; end1 = start1; end2 = start2; } else { return result; } } else { return result; } } } catch (IOException e) { throw new RuntimeException(e.toString()); } }
protected String getCommonSuperClass(final String type1, final String type2) { try { ClassReader info1 = typeInfo(type1); ClassReader info2 = typeInfo(type2); if ((info1.getAccess() & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type2, info2, type1)) { return type1; } else { return "java/lang/Object"; } } if ((info2.getAccess() & Opcodes.ACC_INTERFACE) != 0) { if (typeImplements(type1, info1, type2)) { return type2; } else { return "java/lang/Object"; } } StringBuilder b1 = typeAncestors(type1, info1); StringBuilder b2 = typeAncestors(type2, info2); String result = "java/lang/Object"; int end1 = b1.length(); int end2 = b2.length(); while (true) { int start1 = b1.lastIndexOf(";", end1 - 1); int start2 = b2.lastIndexOf(";", end2 - 1); if (start1 != -1 && start2 != -1 && end1 - start1 == end2 - start2) { String p1 = b1.substring(start1 + 1, end1); String p2 = b2.substring(start2 + 1, end2); if (p1.equals(p2)) { result = p1; end1 = start1; end2 = start2; } else { return result; } } else { return result; } } } catch (IOException e) { throw new RuntimeException(e.toString()); } }
diff --git a/src/org/apache/xalan/serialize/SerializerToXML.java b/src/org/apache/xalan/serialize/SerializerToXML.java index 9bd45668..148586b9 100644 --- a/src/org/apache/xalan/serialize/SerializerToXML.java +++ b/src/org/apache/xalan/serialize/SerializerToXML.java @@ -1,2476 +1,2478 @@ /* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, Lotus * Development Corporation., http://www.lotus.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.xalan.serialize; import java.io.Writer; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.IOException; import java.util.Enumeration; import java.util.Stack; import java.util.Vector; import java.util.Hashtable; import java.util.Properties; import java.util.BitSet; import org.xml.sax.*; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.ext.DeclHandler; import org.w3c.dom.Node; import org.apache.xalan.serialize.Serializer; import org.apache.xalan.serialize.DOMSerializer; import org.apache.xml.utils.QName; import org.apache.xalan.templates.OutputProperties; import org.apache.xml.utils.BoolStack; import org.apache.xml.utils.TreeWalker; import org.apache.xml.utils.WrappedRuntimeException; import org.apache.xml.utils.SystemIDResolver; import org.apache.xalan.res.XSLTErrorResources; import org.apache.xalan.res.XSLMessages; import org.apache.xpath.res.XPATHErrorResources; import javax.xml.transform.Result; import javax.xml.transform.OutputKeys; /** * <meta name="usage" content="general"/> * SerializerToXML formats SAX-style events into XML. */ public class SerializerToXML implements ContentHandler, LexicalHandler, DeclHandler, Serializer, DOMSerializer { /** * The writer where the XML will be written. */ protected Writer m_writer = null; /** True if we control the buffer, and we should flush the output on endDocument. */ boolean m_shouldFlush = true; // /** The output stream where the result stream is written. */ // protected OutputStream m_outputStream = System.out; /** * The character encoding. Must match the encoding used for the printWriter. */ protected String m_encoding = null; /** * Assume java encoding names are the same as the ISO encoding names if this is true. */ static boolean javaEncodingIsISO = false; /** * Tells if we should write the XML declaration. */ public boolean m_shouldNotWriteXMLHeader = false; /** * Tells the XML version, for writing out to the XML decl. */ public String m_version = null; /** * A stack of Boolean objects that tell if the given element * has children. */ protected BoolStack m_elemStack = new BoolStack(); /** Stack to keep track of disabling output escaping. */ protected BoolStack m_disableOutputEscapingStates = new BoolStack(); /** True will be pushed, if characters should be in CDATA section blocks. */ protected BoolStack m_cdataSectionStates = new BoolStack(); /** List of QNames obtained from the xsl:output properties. */ protected Vector m_cdataSectionNames = null; /** True if the current characters should be in CDATA blocks. */ protected boolean m_inCData = false; /** * Tell if the character escaping should be disabled for the current state. * * @return true if the character escaping should be disabled. */ protected boolean isEscapingDisabled() { return m_disableOutputEscapingStates.peekOrFalse(); } /** * Tell if the characters in the current state should be put in * cdata section blocks. * * @return true if the characters in the current state should be put in * cdata section blocks. */ protected boolean isCDataSection() { return m_inCData || m_cdataSectionStates.peekOrFalse(); } /** * Use the system line seperator to write line breaks. */ protected final char[] m_lineSep = System.getProperty("line.separator").toCharArray(); /** * The length of the line seperator, since the write is done * one character at a time. */ protected final int m_lineSepLen = m_lineSep.length; /** * Output a system-dependent line break. * * @throws org.xml.sax.SAXException */ protected final void outputLineSep() throws org.xml.sax.SAXException { try { m_writer.write(m_lineSep, 0, m_lineSepLen); } catch (IOException ioe) { throw new SAXException(ioe); } } /** * State flag to tell if preservation of whitespace * is important. */ protected boolean m_ispreserve = false; /** * Stack to keep track of whether or not we need to * preserve whitespace. */ protected BoolStack m_preserves = new BoolStack(); /** * State flag that tells if the previous node processed * was text, so we can tell if we should preserve whitespace. */ protected boolean m_isprevtext = false; /** * Flag to tell if indenting (pretty-printing) is on. */ protected boolean m_doIndent = false; /** * Flag to keep track of the indent amount. */ protected int m_currentIndent = 0; /** * Amount to indent. */ public int m_indentAmount = 0; /** * Current level of indent. */ protected int level = 0; /** * Flag to signal that a newline should be added. */ boolean m_startNewLine; /** * Flag to tell that we need to add the doctype decl, * which we can't do until the first element is * encountered. */ boolean m_needToOutputDocTypeDecl = true; /** * The System ID for the doc type. */ String m_doctypeSystem; /** * The public ID for the doc type. */ String m_doctypePublic; /** * The standalone value for the doctype. */ boolean m_standalone = false; /** * True if standalone was specified. */ boolean m_standaloneWasSpecified = false; /** * The mediatype. Not used right now. */ String m_mediatype; /** * Tells if we're in an EntityRef event. */ protected boolean m_inEntityRef = false; /** * Tells if we're in an internal document type subset. */ private boolean m_inDoctype = false; /** * Map that tells which XML characters should have special treatment, and it * provides character to entity name lookup. */ protected static CharInfo m_xmlcharInfo = new CharInfo(CharInfo.XML_ENTITIES_RESOURCE); /** * Map that tells which characters should have special treatment, and it * provides character to entity name lookup. */ protected CharInfo m_charInfo; /** Table of user-specified char infos. */ private static Hashtable m_charInfos = null; /** * Flag to quickly tell if the encoding is UTF8. */ boolean m_isUTF8; /** * The maximum character size before we have to resort * to escaping. */ int m_maxCharacter = Encodings.getLastPrintable(); /** * Add space before '/>' for XHTML. */ public boolean m_spaceBeforeClose = false; /** The xsl:output properties. */ protected Properties m_format; /** Indicate whether running in Debug mode */ private static final boolean DEBUG = false; /** * Default constructor. */ public SerializerToXML() { m_charInfo = m_xmlcharInfo; } /** * Copy properties from another SerializerToXML. * * @param xmlListener non-null reference to a SerializerToXML object. */ public void CopyFrom(SerializerToXML xmlListener) { m_writer = xmlListener.m_writer; // m_outputStream = xmlListener.m_outputStream; m_encoding = xmlListener.m_encoding; javaEncodingIsISO = xmlListener.javaEncodingIsISO; m_shouldNotWriteXMLHeader = xmlListener.m_shouldNotWriteXMLHeader; // m_shouldNotWriteXMLHeader = xmlListener.m_shouldNotWriteXMLHeader; m_elemStack = xmlListener.m_elemStack; // m_lineSep = xmlListener.m_lineSep; // m_lineSepLen = xmlListener.m_lineSepLen; m_ispreserve = xmlListener.m_ispreserve; m_preserves = xmlListener.m_preserves; m_isprevtext = xmlListener.m_isprevtext; m_doIndent = xmlListener.m_doIndent; m_currentIndent = xmlListener.m_currentIndent; m_indentAmount = xmlListener.m_indentAmount; level = xmlListener.level; m_startNewLine = xmlListener.m_startNewLine; m_needToOutputDocTypeDecl = xmlListener.m_needToOutputDocTypeDecl; m_doctypeSystem = xmlListener.m_doctypeSystem; m_doctypePublic = xmlListener.m_doctypePublic; m_standalone = xmlListener.m_standalone; m_mediatype = xmlListener.m_mediatype; m_maxCharacter = xmlListener.m_maxCharacter; m_spaceBeforeClose = xmlListener.m_spaceBeforeClose; m_inCData = xmlListener.m_inCData; // m_pos = xmlListener.m_pos; m_pos = 0; } /** * Initialize the serializer with the specified writer and output format. * Must be called before calling any of the serialize methods. * * @param writer The writer to use * @param format The output format */ public synchronized void init(Writer writer, Properties format) { init(writer, format, false); } /** * Initialize the serializer with the specified writer and output format. * Must be called before calling any of the serialize methods. * * @param writer The writer to use * @param format The output format * @param shouldFlush True if the writer should be flushed at EndDocument. */ private synchronized void init(Writer writer, Properties format, boolean shouldFlush) { m_shouldFlush = shouldFlush; m_writer = writer; m_format = format; m_cdataSectionNames = OutputProperties.getQNameProperties(OutputKeys.CDATA_SECTION_ELEMENTS, format); m_indentAmount = OutputProperties.getIntProperty(OutputProperties.S_KEY_INDENT_AMOUNT, format); m_doIndent = OutputProperties.getBooleanProperty(OutputKeys.INDENT, format); m_shouldNotWriteXMLHeader = OutputProperties.getBooleanProperty(OutputKeys.OMIT_XML_DECLARATION, format); m_doctypeSystem = format.getProperty(OutputKeys.DOCTYPE_SYSTEM); m_doctypePublic = format.getProperty(OutputKeys.DOCTYPE_PUBLIC); m_standaloneWasSpecified = (null != format.get(OutputKeys.STANDALONE)); m_standalone = OutputProperties.getBooleanProperty(OutputKeys.STANDALONE, format); m_mediatype = format.getProperty(OutputKeys.MEDIA_TYPE); if (null != m_doctypePublic) { if (m_doctypePublic.startsWith("-//W3C//DTD XHTML")) m_spaceBeforeClose = true; } // initCharsMap(); if (null == m_encoding) m_encoding = Encodings.getMimeEncoding(format.getProperty(OutputKeys.ENCODING)); m_isUTF8 = m_encoding.equals(Encodings.DEFAULT_MIME_ENCODING); m_maxCharacter = Encodings.getLastPrintable(m_encoding); // Access this only from the Hashtable level... we don't want to // get default properties. String entitiesFileName = (String) format.get(OutputProperties.S_KEY_ENTITIES); if (null != entitiesFileName) { try { m_charInfo = null; if (null == m_charInfos) { synchronized (m_xmlcharInfo) { if (null == m_charInfos) // secondary check m_charInfos = new Hashtable(); } } else { m_charInfo = (CharInfo) m_charInfos.get(entitiesFileName); } if (null == m_charInfo) { String absoluteEntitiesFileName; if (entitiesFileName.indexOf(':') < 0) { absoluteEntitiesFileName = SystemIDResolver.getAbsoluteURIFromRelative(entitiesFileName); } else { absoluteEntitiesFileName = SystemIDResolver.getAbsoluteURI(entitiesFileName, null); } m_charInfo = new CharInfo(absoluteEntitiesFileName); m_charInfos.put(entitiesFileName, m_charInfo); } } catch (javax.xml.transform.TransformerException te) { throw new org.apache.xml.utils.WrappedRuntimeException(te); } } } /** * Initialize the serializer with the specified output stream and output format. * Must be called before calling any of the serialize methods. * * @param output The output stream to use * @param format The output format * @throws UnsupportedEncodingException The encoding specified * in the output format is not supported */ public synchronized void init(OutputStream output, Properties format) throws UnsupportedEncodingException { if (null == format) { OutputProperties op = new OutputProperties(Method.XML); format = op.getProperties(); } m_encoding = Encodings.getMimeEncoding(format.getProperty(OutputKeys.ENCODING)); if (m_encoding.equalsIgnoreCase("UTF-8")) { if(output instanceof java.io.BufferedOutputStream) { init(new WriterToUTF8(output), format, true); } else if(output instanceof java.io.FileOutputStream) { init(new WriterToUTF8Buffered(output), format, true); } else { // Not sure what to do in this case. I'm going to be conservative // and not buffer. init(new WriterToUTF8(output), format, true); } } else if (m_encoding.equals("WINDOWS-1250") || m_encoding.equals("US-ASCII") || m_encoding.equals("ASCII")) { init(new WriterToASCI(output), format, true); } else { Writer osw; try { osw = Encodings.getWriter(output, m_encoding); } catch (UnsupportedEncodingException uee) { System.out.println("Warning: encoding \"" + m_encoding + "\" not supported" + ", using " + Encodings.DEFAULT_MIME_ENCODING); m_encoding = Encodings.DEFAULT_MIME_ENCODING; osw = Encodings.getWriter(output, m_encoding); } m_maxCharacter = Encodings.getLastPrintable(m_encoding); init(osw, format, true); } } /** * Receive an object for locating the origin of SAX document events. * * @param locator An object that can return the location of * any SAX document event. * @see org.xml.sax.Locator */ public void setDocumentLocator(Locator locator) { // I don't do anything with this yet. } /** * Output the doc type declaration. * * @param name non-null reference to document type name. * NEEDSDOC @param closeDecl * * @throws org.xml.sax.SAXException */ void outputDocTypeDecl(String name, boolean closeDecl) throws org.xml.sax.SAXException { try { final Writer writer = m_writer; writer.write("<!DOCTYPE "); writer.write(name); if (null != m_doctypePublic) { writer.write(" PUBLIC \""); writer.write(m_doctypePublic); writer.write('\"'); } if (null != m_doctypeSystem) { if (null == m_doctypePublic) writer.write(" SYSTEM \""); else writer.write(" \""); writer.write(m_doctypeSystem); if (closeDecl) { writer.write("\">"); writer.write(m_lineSep, 0, m_lineSepLen);; } else writer.write('\"'); } } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Output the doc type declaration. * * @param name non-null reference to document type name. * NEEDSDOC @param value * * @throws org.xml.sax.SAXException */ void outputEntityDecl(String name, String value) throws org.xml.sax.SAXException { try { final Writer writer = m_writer; writer.write("<!ENTITY "); writer.write(name); writer.write(" \""); writer.write(value); writer.write("\">"); writer.write(m_lineSep, 0, m_lineSepLen); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Receive notification of the beginning of a document. * * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * * @throws org.xml.sax.SAXException */ public void startDocument() throws org.xml.sax.SAXException { if (m_inEntityRef) return; m_needToOutputDocTypeDecl = true; m_startNewLine = false; if (m_shouldNotWriteXMLHeader == false) { String encoding = Encodings.getMimeEncoding(m_encoding); String version = (null == m_version) ? "1.0" : m_version; String standalone; if (m_standaloneWasSpecified) { standalone = " standalone=\"" + (m_standalone ? "yes" : "no") + "\""; } else { standalone = ""; } try { final Writer writer = m_writer; writer.write("<?xml version=\""); writer.write(version); writer.write("\" encoding=\""); writer.write(encoding); writer.write('\"'); writer.write(standalone); writer.write("?>"); writer.write(m_lineSep, 0, m_lineSepLen); } catch(IOException ioe) { throw new SAXException(ioe); } } } /** * Receive notification of the end of a document. * * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * * @throws org.xml.sax.SAXException */ public void endDocument() throws org.xml.sax.SAXException { if (m_doIndent &&!m_isprevtext) { outputLineSep(); } flushWriter(); } /** * Report the start of DTD declarations, if any. * * Any declarations are assumed to be in the internal subset * unless otherwise indicated. * * @param name The document type name. * @param publicId The declared public identifier for the * external DTD subset, or null if none was declared. * @param systemId The declared system identifier for the * external DTD subset, or null if none was declared. * @throws org.xml.sax.SAXException The application may raise an * exception. * @see #endDTD * @see #startEntity */ public void startDTD(String name, String publicId, String systemId) throws org.xml.sax.SAXException { m_doctypeSystem = systemId; m_doctypePublic = publicId; if ((true == m_needToOutputDocTypeDecl)) // && (null != m_doctypeSystem)) { outputDocTypeDecl(name, false); } m_needToOutputDocTypeDecl = false; m_inDoctype = true; } /** * Report the end of DTD declarations. * * @throws org.xml.sax.SAXException The application may raise an exception. * @see #startDTD */ public void endDTD() throws org.xml.sax.SAXException { try { if (!m_inDoctype) m_writer.write("]>"); else { m_writer.write('>'); } m_writer.write(m_lineSep, 0, m_lineSepLen); } catch(IOException ioe) { throw new SAXException(ioe); } // Do nothing for now. } /** * Begin the scope of a prefix-URI Namespace mapping. * @see org.xml.sax.ContentHandler#startPrefixMapping * * @param prefix The Namespace prefix being declared. * @param uri The Namespace URI the prefix is mapped to. * @throws org.xml.sax.SAXException The client may throw * an exception during processing. */ public void startPrefixMapping(String prefix, String uri) throws org.xml.sax.SAXException{} /** * End the scope of a prefix-URI Namespace mapping. * @see org.xml.sax.ContentHandler#endPrefixMapping * * @param prefix The prefix that was being mapping. * @throws org.xml.sax.SAXException The client may throw * an exception during processing. */ public void endPrefixMapping(String prefix) throws org.xml.sax.SAXException{} /** * Tell if two strings are equal, without worry if the first string is null. * * @param p String reference, which may be null. * @param t String reference, which may be null. * * @return true if strings are equal. */ protected static final boolean subPartMatch(String p, String t) { return (p == t) || ((null != p) && (p.equals(t))); } /** * Push a boolean state based on if the name of the element * is found in the list of qnames. A state is always pushed, * one way or the other. * * @param namespaceURI Should be a non-null reference to the namespace URL * of the element that owns the state, or empty string. * @param localName Should be a non-null reference to the local name * of the element that owns the state. * @param qnames Vector of qualified names of elements, or null. * @param state The stack where the state should be pushed. */ protected void pushState(String namespaceURI, String localName, Vector qnames, BoolStack state) { boolean b; if (null != qnames) { b = false; if ((null != namespaceURI) && namespaceURI.length() == 0) namespaceURI = null; int nElems = qnames.size(); for (int i = 0; i < nElems; i++) { QName q = (QName) qnames.elementAt(i); if (q.getLocalName().equals(localName) && subPartMatch(namespaceURI, q.getNamespaceURI())) { b = true; break; } } } else { b = state.peekOrFalse(); } state.push(b); } /** * Receive notification of the beginning of an element. * * * @param namespaceURI The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param name The element type name. * @param atts The attributes attached to the element, if any. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see org.xml.sax.ContentHandler#startElement * @see org.xml.sax.ContentHandler#endElement * @see org.xml.sax.AttributeList * * @throws org.xml.sax.SAXException */ public void startElement( String namespaceURI, String localName, String name, Attributes atts) throws org.xml.sax.SAXException { if (DEBUG) { System.out.println("SerializerToXML - startElement: " + namespaceURI + ", " + localName); int n = atts.getLength(); for (int i = 0; i < n; i++) { System.out.println("atts[" + i + "]: " + atts.getQName(i) + " = " + atts.getValue(i)); } if (null == namespaceURI) { (new RuntimeException(localName + " has a null namespace!")).printStackTrace(); } } if (m_inEntityRef) return; if ((true == m_needToOutputDocTypeDecl) && (null != m_doctypeSystem)) { outputDocTypeDecl(name, true); } m_needToOutputDocTypeDecl = false; writeParentTagEnd(); pushState(namespaceURI, localName, m_cdataSectionNames, m_cdataSectionStates); // pushState(namespaceURI, localName, m_format.getNonEscapingElements(), // m_disableOutputEscapingStates); m_ispreserve = false; // System.out.println(name+": m_doIndent = "+m_doIndent+", m_ispreserve = "+m_ispreserve+", m_isprevtext = "+m_isprevtext); if (shouldIndent() && m_startNewLine) { indent(m_currentIndent); } m_startNewLine = true; try { m_writer.write('<'); m_writer.write(name); } catch(IOException ioe) { throw new SAXException(ioe); } int nAttrs = atts.getLength(); for (int i = 0; i < nAttrs; i++) { processAttribute(atts.getQName(i), atts.getValue(i)); } // Flag the current element as not yet having any children. openElementForChildren(); m_currentIndent += m_indentAmount; m_isprevtext = false; } /** * Check to see if a parent's ">" has been written, and, if * it has not, write it. * * @throws org.xml.sax.SAXException */ protected void writeParentTagEnd() throws org.xml.sax.SAXException { // See if the parent element has already been flagged as having children. if (!m_elemStack.peekOrTrue()) { try { m_writer.write('>'); } catch(IOException ioe) { throw new SAXException(ioe); } m_isprevtext = false; m_elemStack.setTop(true); m_preserves.push(m_ispreserve); } } /** * Flag the current element as not yet having any * children. */ protected void openElementForChildren() { // Flag the current element as not yet having any children. m_elemStack.push(false); } /** * Tell if child nodes have been added to the current * element. Must be called in balance with openElementForChildren(). * * @return true if child nodes were added. */ protected boolean childNodesWereAdded() { return m_elemStack.isEmpty() ? false : m_elemStack.pop(); } /** * Receive notification of the end of an element. * * * @param namespaceURI The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace * processing is not being performed. * @param localName The local name (without prefix), or the * empty string if Namespace processing is not being * performed. * @param name The element type name * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * * @throws org.xml.sax.SAXException */ public void endElement(String namespaceURI, String localName, String name) throws org.xml.sax.SAXException { if (m_inEntityRef) return; m_currentIndent -= m_indentAmount; boolean hasChildNodes = childNodesWereAdded(); try { final Writer writer = m_writer; if (hasChildNodes) { if (shouldIndent()) indent(m_currentIndent); writer.write('<'); writer.write('/'); writer.write(name); writer.write('>'); } else { if (m_spaceBeforeClose) writer.write(" />"); else writer.write("/>"); } } catch(IOException ioe) { throw new SAXException(ioe); } if (hasChildNodes) { m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop(); } m_isprevtext = false; // m_disableOutputEscapingStates.pop(); m_cdataSectionStates.pop(); } /** * Process an attribute. * @param name The name of the attribute. * @param value The value of the attribute. * * @throws org.xml.sax.SAXException */ protected void processAttribute(String name, String value) throws org.xml.sax.SAXException { try { final Writer writer = m_writer; writer.write(' '); writer.write(name); writer.write("=\""); writeAttrString(value, m_encoding); writer.write('\"'); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Starts an un-escaping section. All characters printed within an * un-escaping section are printed as is, without escaping special * characters into entity references. Only XML and HTML serializers * need to support this method. * <p> * The contents of the un-escaping section will be delivered through * the regular <tt>characters</tt> event. * * @throws org.xml.sax.SAXException */ public void startNonEscaping() throws org.xml.sax.SAXException { m_disableOutputEscapingStates.push(true); } /** * Ends an un-escaping section. * * @see #startNonEscaping * * @throws org.xml.sax.SAXException */ public void endNonEscaping() throws org.xml.sax.SAXException { m_disableOutputEscapingStates.pop(); } /** * Starts a whitespace preserving section. All characters printed * within a preserving section are printed without indentation and * without consolidating multiple spaces. This is equivalent to * the <tt>xml:space=&quot;preserve&quot;</tt> attribute. Only XML * and HTML serializers need to support this method. * <p> * The contents of the whitespace preserving section will be delivered * through the regular <tt>characters</tt> event. * * @throws org.xml.sax.SAXException */ public void startPreserving() throws org.xml.sax.SAXException { // Not sure this is really what we want. -sb m_preserves.push(true); m_ispreserve = true; } /** * Ends a whitespace preserving section. * * @see #startPreserving * * @throws org.xml.sax.SAXException */ public void endPreserving() throws org.xml.sax.SAXException { // Not sure this is really what we want. -sb m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop(); } /** * Receive notification of a processing instruction. * * @param target The processing instruction target. * @param data The processing instruction data, or null if * none was supplied. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * * @throws org.xml.sax.SAXException */ public void processingInstruction(String target, String data) throws org.xml.sax.SAXException { if (m_inEntityRef) return; if (target.equals(Result.PI_DISABLE_OUTPUT_ESCAPING)) { startNonEscaping(); } else if (target.equals(Result.PI_ENABLE_OUTPUT_ESCAPING)) { endNonEscaping(); } else { try { final Writer writer = m_writer; writeParentTagEnd(); if (shouldIndent()) indent(m_currentIndent); writer.write('<'); writer.write('?'); writer.write(target); if (data.length() > 0 &&!Character.isSpaceChar(data.charAt(0))) writer.write(' '); int indexOfQLT = data.indexOf("?>"); if (indexOfQLT >= 0) { // See XSLT spec on error recovery of "?>" in PIs. if (indexOfQLT > 0) { writer.write(data.substring(0, indexOfQLT)); } writer.write("? >"); // add space between. if ((indexOfQLT + 2) < data.length()) { writer.write(data.substring(indexOfQLT + 2)); } } else { writer.write(data); } writer.write('?'); writer.write('>'); // Always output a newline char if not inside of an // element. The whitespace is not significant in that // case. if (m_elemStack.isEmpty()) writer.write(m_lineSep, 0, m_lineSepLen); m_startNewLine = true; } catch(IOException ioe) { throw new SAXException(ioe); } } } /** * Report an XML comment anywhere in the document. * * This callback will be used for comments inside or outside the * document element, including comments in the external DTD * subset (if read). * * @param ch An array holding the characters in the comment. * @param start The starting position in the array. * @param length The number of characters to use from the array. * @throws org.xml.sax.SAXException The application may raise an exception. */ public void comment(char ch[], int start, int length) throws org.xml.sax.SAXException { if (m_inEntityRef) return; writeParentTagEnd(); if (shouldIndent()) indent(m_currentIndent); try { final Writer writer = m_writer; writer.write("<!--"); writer.write(ch, start, length); writer.write("-->"); } catch(IOException ioe) { throw new SAXException(ioe); } m_startNewLine = true; } /** * Report the start of a CDATA section. * * @throws org.xml.sax.SAXException The application may raise an exception. * @see #endCDATA */ public void startCDATA() throws org.xml.sax.SAXException { m_inCData = true; } /** * Report the end of a CDATA section. * * @throws org.xml.sax.SAXException The application may raise an exception. * @see #startCDATA */ public void endCDATA() throws org.xml.sax.SAXException { m_inCData = false; } /** * Receive notification of cdata. * * <p>The Parser will call this method to report each chunk of * character data. SAX parsers may return all contiguous character * data in a single chunk, or they may split it into several * chunks; however, all of the characters in any single event * must come from the same external entity, so that the Locator * provides useful information.</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Note that some parsers will report whitespace using the * ignorableWhitespace() method rather than this one (validating * parsers must do so).</p> * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see #ignorableWhitespace * @see org.xml.sax.Locator * * @throws org.xml.sax.SAXException */ public void cdata(char ch[], int start, int length) throws org.xml.sax.SAXException { try { writeParentTagEnd(); m_ispreserve = true; if (shouldIndent()) indent(m_currentIndent); boolean writeCDataBrackets = (((length >= 1) && (ch[start] <= m_maxCharacter))); if (writeCDataBrackets) { m_writer.write("<![CDATA["); } // m_writer.write(ch, start, length); if (isEscapingDisabled()) { charactersRaw(ch, start, length); } else writeNormalizedChars(ch, start, length, true); if (writeCDataBrackets) { m_writer.write("]]>"); } } catch (IOException ioe) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage(XPATHErrorResources.ER_OIERROR, null), ioe); //"IO error", ioe); } } /** The current position in the m_charBuf or m_byteBuf. */ protected int m_pos = 0; /** * Append a character to the buffer. * * @param b byte to be written to result stream. * * @throws org.xml.sax.SAXException */ protected final void accum(char b) throws org.xml.sax.SAXException { try { m_writer.write(b); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Append a character to the buffer. * * @param chars non-null reference to character array. * @param start Start of characters to be written. * @param length Number of characters to be written. * * @throws org.xml.sax.SAXException */ protected final void accum(char chars[], int start, int length) throws org.xml.sax.SAXException { try { m_writer.write(chars, start, length); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Append a character to the buffer. * * @param s non-null reference to string to be written to the character buffer. * * @throws org.xml.sax.SAXException */ protected final void accum(String s) throws org.xml.sax.SAXException { try { m_writer.write(s); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Flush the formatter's result stream. * * @throws org.xml.sax.SAXException */ public final void flushWriter() throws org.xml.sax.SAXException { if (null != m_writer) { try { if (m_writer instanceof WriterToUTF8Buffered) { if(m_shouldFlush) ((WriterToUTF8Buffered) m_writer).flush(); else ((WriterToUTF8Buffered) m_writer).flushBuffer(); } if (m_writer instanceof WriterToUTF8) { if(m_shouldFlush) m_writer.flush(); } else if (m_writer instanceof WriterToASCI) { if(m_shouldFlush) m_writer.flush(); } else { // Flush always. // Not a great thing if the writer was created // by this class, but don't have a choice. m_writer.flush(); } } catch (IOException ioe) { throw new org.xml.sax.SAXException(ioe); } } } /** * Receive notification of character data. * * <p>The Parser will call this method to report each chunk of * character data. SAX parsers may return all contiguous character * data in a single chunk, or they may split it into several * chunks; however, all of the characters in any single event * must come from the same external entity, so that the Locator * provides useful information.</p> * * <p>The application must not attempt to read from the array * outside of the specified range.</p> * * <p>Note that some parsers will report whitespace using the * ignorableWhitespace() method rather than this one (validating * parsers must do so).</p> * * @param chars The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see #ignorableWhitespace * @see org.xml.sax.Locator * * @throws org.xml.sax.SAXException */ public void characters(char chars[], int start, int length) throws org.xml.sax.SAXException { + if(0 == length) + return; // if (m_inEntityRef) // return; // else if (m_inCData || m_cdataSectionStates.peekOrFalse()) { cdata(chars, start, length); return; } try { if (m_disableOutputEscapingStates.peekOrFalse()) { charactersRaw(chars, start, length); return; } final Writer writer = m_writer; if (!m_elemStack.peekOrTrue()) { writer.write('>'); m_isprevtext = false; m_elemStack.setTop(true); m_preserves.push(m_ispreserve); } int startClean = start; int lengthClean = 0; // int pos = 0; int end = start + length; boolean checkWhite = true; final int maxCharacter = m_maxCharacter; final BitSet specialsMap = m_charInfo.m_specialsMap; for (int i = start; i < end; i++) { char ch = chars[i]; if (checkWhite && ((ch > 0x20) ||!((ch == 0x20) || (ch == 0x09) || (ch == 0xD) || (ch == 0xA)))) { m_ispreserve = true; checkWhite = false; } if (((ch < maxCharacter) && (!specialsMap.get(ch))) || ('"' == ch)) { lengthClean++; } else { if (lengthClean > 0) { writer.write(chars, startClean, lengthClean); lengthClean = 0; } if (CharInfo.S_LINEFEED == ch) { writer.write(m_lineSep, 0, m_lineSepLen); startClean = i + 1; } else { startClean = accumDefaultEscape(ch, i, chars, end, false); i = startClean - 1; } } } if (lengthClean > 0) { writer.write(chars, startClean, lengthClean); } } catch(IOException ioe) { throw new SAXException(ioe); } m_isprevtext = true; } /** * If available, when the disable-output-escaping attribute is used, * output raw text without escaping. * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * * @throws org.xml.sax.SAXException */ public void charactersRaw(char ch[], int start, int length) throws org.xml.sax.SAXException { try { if (m_inEntityRef) return; writeParentTagEnd(); m_ispreserve = true; m_writer.write(ch, start, length); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Return true if the character is the high member of a surrogate pair. * * NEEDSDOC @param c * * NEEDSDOC ($objectName$) @return */ static final boolean isUTF16Surrogate(char c) { return (c & 0xFC00) == 0xD800; } /** * Once a surrogate has been detected, get the pair as a single * integer value. * * @param c the first part of the surrogate. * @param ch Character array. * @param i position Where the surrogate was detected. * @param end The end index of the significant characters. * @return i+1. * @throws org.xml.sax.SAXException if invalid UTF-16 surrogate detected. */ int getURF16SurrogateValue(char c, char ch[], int i, int end) throws org.xml.sax.SAXException { int next; if (i + 1 >= end) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_INVALID_UTF16_SURROGATE, new Object[]{ Integer.toHexString((int) c) })); //"Invalid UTF-16 surrogate detected: " //+Integer.toHexString((int)c)+ " ?"); } else { next = ch[++i]; if (!(0xdc00 <= next && next < 0xe000)) throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_INVALID_UTF16_SURROGATE, new Object[]{ Integer.toHexString((int) c) + " " + Integer.toHexString(next) })); //"Invalid UTF-16 surrogate detected: " //+Integer.toHexString((int)c)+" "+Integer.toHexString(next)); next = ((c - 0xd800) << 10) + next - 0xdc00 + 0x00010000; } return next; } /** * Once a surrogate has been detected, write the pair as a single * character reference. * * @param c the first part of the surrogate. * @param ch Character array. * @param i position Where the surrogate was detected. * @param end The end index of the significant characters. * @return i+1. * @throws IOException * @throws org.xml.sax.SAXException if invalid UTF-16 surrogate detected. */ protected int writeUTF16Surrogate(char c, char ch[], int i, int end) throws IOException, org.xml.sax.SAXException { // UTF-16 surrogate int surrogateValue = getURF16SurrogateValue(c, ch, i, end); i++; m_writer.write('&'); m_writer.write('#'); // m_writer.write('x'); m_writer.write(Integer.toString(surrogateValue)); m_writer.write(';'); return i; } /** * Normalize the characters, but don't escape. * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @param isCData true if a CDATA block should be built around the characters. * * @throws IOException * @throws org.xml.sax.SAXException */ void writeNormalizedChars(char ch[], int start, int length, boolean isCData) throws IOException, org.xml.sax.SAXException { int end = start + length; for (int i = start; i < end; i++) { char c = ch[i]; if (CharInfo.S_LINEFEED == c) { m_writer.write(m_lineSep, 0, m_lineSepLen); } else if (isCData && (c > m_maxCharacter)) { if (i != 0) m_writer.write("]]>"); // This needs to go into a function... if (isUTF16Surrogate(c)) { i = writeUTF16Surrogate(c, ch, i, end); } else { m_writer.write("&#"); String intStr = Integer.toString((int) c); m_writer.write(intStr); m_writer.write(';'); } if ((i != 0) && (i < (end - 1))) m_writer.write("<![CDATA["); } else if (isCData && ((i < (end - 2)) && (']' == c) && (']' == ch[i + 1]) && ('>' == ch[i + 2]))) { m_writer.write("]]]]><![CDATA[>"); i += 2; } else { if (c <= m_maxCharacter) { m_writer.write(c); } // This needs to go into a function... else if (isUTF16Surrogate(c)) { i = writeUTF16Surrogate(c, ch, i, end); } else { m_writer.write("&#"); String intStr = Integer.toString((int) c); m_writer.write(intStr); m_writer.write(';'); } } } } /** * Receive notification of ignorable whitespace in element content. * * Not sure how to get this invoked quite yet. * * @param ch The characters from the XML document. * @param start The start position in the array. * @param length The number of characters to read from the array. * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. * @see #characters * * @throws org.xml.sax.SAXException */ public void ignorableWhitespace(char ch[], int start, int length) throws org.xml.sax.SAXException { if (0 == length) return; characters(ch, start, length); } /** * Receive notification of a skipped entity. * @see org.xml.sax.ContentHandler#skippedEntity * * @param name The name of the skipped entity. If it is a * parameter entity, the name will begin with '%', and if * it is the external DTD subset, it will be the string * "[dtd]". * @throws org.xml.sax.SAXException Any SAX exception, possibly * wrapping another exception. */ public void skippedEntity(String name) throws org.xml.sax.SAXException { // TODO: Should handle } /** * Report the beginning of an entity. * * The start and end of the document entity are not reported. * The start and end of the external DTD subset are reported * using the pseudo-name "[dtd]". All other events must be * properly nested within start/end entity events. * * @param name The name of the entity. If it is a parameter * entity, the name will begin with '%'. * @throws org.xml.sax.SAXException The application may raise an exception. * @see #endEntity * @see org.xml.sax.ext.DeclHandler#internalEntityDecl * @see org.xml.sax.ext.DeclHandler#externalEntityDecl */ public void startEntity(String name) throws org.xml.sax.SAXException { m_inEntityRef = true; } /** * Report the end of an entity. * * @param name The name of the entity that is ending. * @throws org.xml.sax.SAXException The application may raise an exception. * @see #startEntity */ public void endEntity(String name) throws org.xml.sax.SAXException { m_inEntityRef = false; } /** * Receive notivication of a entityReference. * * @param name The name of the entity. * * @throws org.xml.sax.SAXException */ public void entityReference(String name) throws org.xml.sax.SAXException { writeParentTagEnd(); if (shouldIndent()) indent(m_currentIndent); try { final Writer writer = m_writer; writer.write("&"); writer.write(name); writer.write(";"); } catch(IOException ioe) { throw new SAXException(ioe); } } // Implement DeclHandler /** * Report an element type declaration. * * <p>The content model will consist of the string "EMPTY", the * string "ANY", or a parenthesised group, optionally followed * by an occurrence indicator. The model will be normalized so * that all whitespace is removed,and will include the enclosing * parentheses.</p> * * @param name The element type name. * @param model The content model as a normalized string. * @exception SAXException The application may raise an exception. */ public void elementDecl(String name, String model) throws SAXException { try { final Writer writer = m_writer; if (m_inDoctype) { writer.write(" ["); writer.write(m_lineSep, 0, m_lineSepLen); m_inDoctype = false; } writer.write("<!ELEMENT "); writer.write(name); writer.write(' '); writer.write(model); writer.write('>'); writer.write(m_lineSep, 0, m_lineSepLen); } catch(IOException ioe) { throw new SAXException(ioe); } } /** NEEDSDOC Field m_elemName */ private String m_elemName = ""; /** * Report an attribute type declaration. * * <p>Only the effective (first) declaration for an attribute will * be reported. The type will be one of the strings "CDATA", * "ID", "IDREF", "IDREFS", "NMTOKEN", "NMTOKENS", "ENTITY", * "ENTITIES", or "NOTATION", or a parenthesized token group with * the separator "|" and all whitespace removed.</p> * * @param eName The name of the associated element. * @param aName The name of the attribute. * @param type A string representing the attribute type. * @param valueDefault A string representing the attribute default * ("#IMPLIED", "#REQUIRED", or "#FIXED") or null if * none of these applies. * @param value A string representing the attribute's default value, * or null if there is none. * @exception SAXException The application may raise an exception. */ public void attributeDecl( String eName, String aName, String type, String valueDefault, String value) throws SAXException { try { final Writer writer = m_writer; if (m_inDoctype) { writer.write(" ["); writer.write(m_lineSep, 0, m_lineSepLen); m_inDoctype = false; } if (!eName.equals(m_elemName)) { writer.write("<!ATTLIST "); writer.write(eName); writer.write(" "); m_elemName = eName; } else { m_pos -= 3; writer.write(m_lineSep, 0, m_lineSepLen); } writer.write(aName); writer.write(" "); writer.write(type); writer.write(" "); writer.write(valueDefault); //m_writer.write(" "); //m_writer.write(value); writer.write(">"); writer.write(m_lineSep, 0, m_lineSepLen); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Report an internal entity declaration. * * <p>Only the effective (first) declaration for each entity * will be reported.</p> * * @param name The name of the entity. If it is a parameter * entity, the name will begin with '%'. * @param value The replacement text of the entity. * @exception SAXException The application may raise an exception. * @see #externalEntityDecl * @see org.xml.sax.DTDHandler#unparsedEntityDecl */ public void internalEntityDecl(String name, String value) throws SAXException { try { if (m_inDoctype) { m_writer.write(" ["); m_writer.write(m_lineSep, 0, m_lineSepLen); m_inDoctype = false; } outputEntityDecl(name, value); } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Report a parsed external entity declaration. * * <p>Only the effective (first) declaration for each entity * will be reported.</p> * * @param name The name of the entity. If it is a parameter * entity, the name will begin with '%'. * @param publicId The declared public identifier of the entity, or * null if none was declared. * @param systemId The declared system identifier of the entity. * @exception SAXException The application may raise an exception. * @see #internalEntityDecl * @see org.xml.sax.DTDHandler#unparsedEntityDecl */ public void externalEntityDecl( String name, String publicId, String systemId) throws SAXException{} /** * Handle one of the default entities, return false if it * is not a default entity. * * @param ch character to be escaped. * @param i index into character array. * @param chars non-null reference to character array. * @param len length of chars. * @param escLF true if the linefeed should be escaped. * * @return i+1 if the character was written, else i. * * @throws org.xml.sax.SAXException */ final int accumDefaultEntity( char ch, int i, char[] chars, int len, boolean escLF) throws org.xml.sax.SAXException { try { if (!escLF && CharInfo.S_LINEFEED == ch) { m_writer.write(m_lineSep, 0, m_lineSepLen); } else { if (m_charInfo.isSpecial(ch)) { String entityRef = m_charInfo.getEntityNameForChar(ch); if (null != entityRef) { final Writer writer = m_writer; writer.write('&'); writer.write(entityRef); writer.write(';'); } else return i; } else return i; } return i + 1; } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Escape and m_writer.write a character. * * @param ch character to be escaped. * @param i index into character array. * @param chars non-null reference to character array. * @param len length of chars. * @param escLF true if the linefeed should be escaped. * * @return i+1 if the character was written, else i. * * @throws org.xml.sax.SAXException */ final int accumDefaultEscape( char ch, int i, char[] chars, int len, boolean escLF) throws org.xml.sax.SAXException { int pos = accumDefaultEntity(ch, i, chars, len, escLF); if (i == pos) { pos++; try { if (0xd800 <= ch && ch < 0xdc00) { // UTF-16 surrogate int next; if (i + 1 >= len) { throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_INVALID_UTF16_SURROGATE, new Object[]{ Integer.toHexString(ch) })); //"Invalid UTF-16 surrogate detected: " //+Integer.toHexString(ch)+ " ?"); } else { next = chars[++i]; if (!(0xdc00 <= next && next < 0xe000)) throw new org.xml.sax.SAXException( XSLMessages.createXPATHMessage( XPATHErrorResources.ER_INVALID_UTF16_SURROGATE, new Object[]{ Integer.toHexString(ch) + " " + Integer.toHexString(next) })); //"Invalid UTF-16 surrogate detected: " //+Integer.toHexString(ch)+" "+Integer.toHexString(next)); next = ((ch - 0xd800) << 10) + next - 0xdc00 + 0x00010000; } m_writer.write("&#"); m_writer.write(Integer.toString(next)); m_writer.write(";"); /*} else if (null != ctbc && !ctbc.canConvert(ch)) { sb.append("&#x"); sb.append(Integer.toString((int)ch, 16)); sb.append(";");*/ } else { if (ch > m_maxCharacter || (m_charInfo.isSpecial(ch))) { m_writer.write("&#"); m_writer.write(Integer.toString(ch)); m_writer.write(";"); } else { m_writer.write(ch); } } } catch(IOException ioe) { throw new SAXException(ioe); } } return pos; } /** * Returns the specified <var>string</var> after substituting <VAR>specials</VAR>, * and UTF-16 surrogates for chracter references <CODE>&amp;#xnn</CODE>. * * @param string String to convert to XML format. * @param encoding CURRENTLY NOT IMPLEMENTED. * * @throws org.xml.sax.SAXException */ public void writeAttrString(String string, String encoding) throws org.xml.sax.SAXException { try { final char[] stringChars = string.toCharArray(); final int len = stringChars.length; final Writer writer = m_writer; for (int i = 0; i < len; i++) { char ch = stringChars[i]; if ((ch < m_maxCharacter) && (!m_charInfo.isSpecial(ch))) { writer.write(ch); } else { // I guess the parser doesn't normalize cr/lf in attributes. -sb if ((CharInfo.S_CARRIAGERETURN == ch) && ((i + 1) < len) && (CharInfo.S_LINEFEED == stringChars[i + 1])) { i++; ch = CharInfo.S_LINEFEED; } accumDefaultEscape(ch, i, stringChars, len, true); } } } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Tell if, based on space preservation constraints and the doIndent property, * if an indent should occur. * * @return True if an indent should occur. */ protected boolean shouldIndent() { return m_doIndent && (!m_ispreserve &&!m_isprevtext); } /** * Prints <var>n</var> spaces. * @param pw The character output stream to use. * @param n Number of spaces to print. * * @throws org.xml.sax.SAXException if an error occurs when writing. */ public void printSpace(int n) throws org.xml.sax.SAXException { try { for (int i = 0; i < n; i++) { m_writer.write(' '); } } catch(IOException ioe) { throw new SAXException(ioe); } } /** * Prints a newline character and <var>n</var> spaces. * @param pw The character output stream to use. * @param n Number of spaces to print. * * @throws org.xml.sax.SAXException if an error occurs during writing. */ public void indent(int n) throws org.xml.sax.SAXException { if (m_startNewLine) outputLineSep(); if (m_doIndent) { printSpace(n); } } /** * Specifies an output stream to which the document should be * serialized. This method should not be called while the * serializer is in the process of serializing a document. * <p> * The encoding specified in the output properties is used, or * if no encoding was specified, the default for the selected * output method. * * @param output The output stream */ public void setOutputStream(OutputStream output) { try { init(output, m_format); } catch (UnsupportedEncodingException uee) { // Should have been warned in init, I guess... } } /** * Get the output stream where the events will be serialized to. * * @return reference to the result stream, or null of only a writer was * set. */ public OutputStream getOutputStream() { if (m_writer instanceof WriterToUTF8Buffered) return ((WriterToUTF8Buffered) m_writer).getOutputStream(); if (m_writer instanceof WriterToUTF8) return ((WriterToUTF8) m_writer).getOutputStream(); else if (m_writer instanceof WriterToASCI) return ((WriterToASCI) m_writer).getOutputStream(); else return null; } /** * Specifies a writer to which the document should be serialized. * This method should not be called while the serializer is in * the process of serializing a document. * * @param writer The output writer stream */ public void setWriter(Writer writer) { m_writer = writer; } /** * Get the character stream where the events will be serialized to. * * @return Reference to the result Writer, or null. */ public Writer getWriter() { return m_writer; } /** * Specifies an output format for this serializer. It the * serializer has already been associated with an output format, * it will switch to the new format. This method should not be * called while the serializer is in the process of serializing * a document. * * @param format The output format to use */ public void setOutputFormat(Properties format) { boolean shouldFlush = m_shouldFlush; init(m_writer, format, false); m_shouldFlush = shouldFlush; } /** * Returns the output format for this serializer. * * @return The output format in use */ public Properties getOutputFormat() { return m_format; } /** * Return a {@link ContentHandler} interface into this serializer. * If the serializer does not support the {@link ContentHandler} * interface, it should return null. * * @return A {@link ContentHandler} interface into this serializer, * or null if the serializer is not SAX 2 capable * @throws IOException An I/O exception occured */ public ContentHandler asContentHandler() throws IOException { return this; } /** * Return a {@link DOMSerializer} interface into this serializer. * If the serializer does not support the {@link DOMSerializer} * interface, it should return null. * * @return A {@link DOMSerializer} interface into this serializer, * or null if the serializer is not DOM capable * @throws IOException An I/O exception occured */ public DOMSerializer asDOMSerializer() throws IOException { return this; // for now } /** * Resets the serializer. If this method returns true, the * serializer may be used for subsequent serialization of new * documents. It is possible to change the output format and * output stream prior to serializing, or to use the existing * output format and output stream. * * @return True if serializer has been reset and can be reused */ public boolean reset() { return false; } /** * Serializes the DOM node. Throws an exception only if an I/O * exception occured while serializing. * * @param elem The element to serialize * * @param node Node to serialize. * @throws IOException An I/O exception occured while serializing */ public void serialize(Node node) throws IOException { try { TreeWalker walker = new TreeWalker(this, new org.apache.xpath.DOM2Helper()); walker.traverse(node); } catch (org.xml.sax.SAXException se) { throw new WrappedRuntimeException(se); } } } //ToXMLStringVisitor
true
true
public void characters(char chars[], int start, int length) throws org.xml.sax.SAXException { // if (m_inEntityRef) // return; // else if (m_inCData || m_cdataSectionStates.peekOrFalse()) { cdata(chars, start, length); return; } try { if (m_disableOutputEscapingStates.peekOrFalse()) { charactersRaw(chars, start, length); return; } final Writer writer = m_writer; if (!m_elemStack.peekOrTrue()) { writer.write('>'); m_isprevtext = false; m_elemStack.setTop(true); m_preserves.push(m_ispreserve); } int startClean = start; int lengthClean = 0; // int pos = 0; int end = start + length; boolean checkWhite = true; final int maxCharacter = m_maxCharacter; final BitSet specialsMap = m_charInfo.m_specialsMap; for (int i = start; i < end; i++) { char ch = chars[i]; if (checkWhite && ((ch > 0x20) ||!((ch == 0x20) || (ch == 0x09) || (ch == 0xD) || (ch == 0xA)))) { m_ispreserve = true; checkWhite = false; } if (((ch < maxCharacter) && (!specialsMap.get(ch))) || ('"' == ch)) { lengthClean++; } else { if (lengthClean > 0) { writer.write(chars, startClean, lengthClean); lengthClean = 0; } if (CharInfo.S_LINEFEED == ch) { writer.write(m_lineSep, 0, m_lineSepLen); startClean = i + 1; } else { startClean = accumDefaultEscape(ch, i, chars, end, false); i = startClean - 1; } } } if (lengthClean > 0) { writer.write(chars, startClean, lengthClean); } } catch(IOException ioe) { throw new SAXException(ioe); } m_isprevtext = true; }
public void characters(char chars[], int start, int length) throws org.xml.sax.SAXException { if(0 == length) return; // if (m_inEntityRef) // return; // else if (m_inCData || m_cdataSectionStates.peekOrFalse()) { cdata(chars, start, length); return; } try { if (m_disableOutputEscapingStates.peekOrFalse()) { charactersRaw(chars, start, length); return; } final Writer writer = m_writer; if (!m_elemStack.peekOrTrue()) { writer.write('>'); m_isprevtext = false; m_elemStack.setTop(true); m_preserves.push(m_ispreserve); } int startClean = start; int lengthClean = 0; // int pos = 0; int end = start + length; boolean checkWhite = true; final int maxCharacter = m_maxCharacter; final BitSet specialsMap = m_charInfo.m_specialsMap; for (int i = start; i < end; i++) { char ch = chars[i]; if (checkWhite && ((ch > 0x20) ||!((ch == 0x20) || (ch == 0x09) || (ch == 0xD) || (ch == 0xA)))) { m_ispreserve = true; checkWhite = false; } if (((ch < maxCharacter) && (!specialsMap.get(ch))) || ('"' == ch)) { lengthClean++; } else { if (lengthClean > 0) { writer.write(chars, startClean, lengthClean); lengthClean = 0; } if (CharInfo.S_LINEFEED == ch) { writer.write(m_lineSep, 0, m_lineSepLen); startClean = i + 1; } else { startClean = accumDefaultEscape(ch, i, chars, end, false); i = startClean - 1; } } } if (lengthClean > 0) { writer.write(chars, startClean, lengthClean); } } catch(IOException ioe) { throw new SAXException(ioe); } m_isprevtext = true; }
diff --git a/gcm-client/src/com/google/android/gcm/GCMBroadcastReceiver.java b/gcm-client/src/com/google/android/gcm/GCMBroadcastReceiver.java index 86f0bb4..1020610 100644 --- a/gcm-client/src/com/google/android/gcm/GCMBroadcastReceiver.java +++ b/gcm-client/src/com/google/android/gcm/GCMBroadcastReceiver.java @@ -1,75 +1,72 @@ /* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. */ public class GCMBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "GCMBroadcastReceiver"; private static boolean mReceiverSet = false; @Override public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; - String myClass = getClass().getName(); - if (!myClass.equals(GCMBroadcastReceiver.class.getName())) { - GCMRegistrar.setRetryReceiverClassName(myClass); - } + GCMRegistrar.setRetryReceiverClassName(getClass().getName()); } String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
true
true
public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; String myClass = getClass().getName(); if (!myClass.equals(GCMBroadcastReceiver.class.getName())) { GCMRegistrar.setRetryReceiverClassName(myClass); } } String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); }
public final void onReceive(Context context, Intent intent) { Log.v(TAG, "onReceive: " + intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(getClass().getName()); } String className = getGCMIntentServiceClassName(context); Log.v(TAG, "GCM IntentService class: " + className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); }
diff --git a/src/classes/com/sun/opengl/impl/x11/DRIHack.java b/src/classes/com/sun/opengl/impl/x11/DRIHack.java index 4dda1305f..35a1c8fc7 100644 --- a/src/classes/com/sun/opengl/impl/x11/DRIHack.java +++ b/src/classes/com/sun/opengl/impl/x11/DRIHack.java @@ -1,133 +1,128 @@ /* * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package com.sun.opengl.impl.x11; import java.io.*; import java.security.*; import com.sun.gluegen.runtime.*; import com.sun.opengl.impl.*; /** * Helper class for working around problems with open-source DRI * drivers. In the current DRI implementation it is required that the * symbols in libGL.so.1.2 be globally visible to be accessible from * other libraries that are dynamically loaded by the implementation. * Applications may typically satisfy this need either by linking * against libGL.so on the command line (-lGL) or by dlopen'ing * libGL.so.1.2 with the RTLD_GLOBAL flag. The JOGL implementation * links against libGL on all platforms rather than forcing all OpenGL * entry points to be called through a function pointer. This allows * the JOGL library to link directly to core 1.1 OpenGL entry points * like glVertex3f, while calling through function pointers for entry * points from later OpenGL versions as well as from * extensions. However, because libjogl.so (which links against * libGL.so) is loaded by the JVM, and because the JVM implicitly uses * RTLD_LOCAL in the implementation of System.loadLibrary(), this * means via transitivity that the symbols for libGL.so have only * RTLD_LOCAL visibility to the rest of the application, so the DRI * drivers can not find the symbols required. <P> * * There are at least two possible solutions. One would be to change * the JOGL implementation to call through function pointers uniformly * so that it does not need to link against libGL.so. This is * possible, but requires changes to GlueGen and also is not really * necessary in any other situation than with the DRI drivers. Another * solution is to force the first load of libGL.so.1.2 to be done * dynamically with RTLD_GLOBAL before libjogl.so is loaded and causes * libGL.so.1.2 to be loaded again. The NativeLibrary class in the * GlueGen runtime has this property, and we use it to implement this * workaround. */ public class DRIHack { private static final boolean DEBUG = Debug.debug("DRIHack"); private static boolean driHackNeeded; private static NativeLibrary oglLib; public static void begin() { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String os = System.getProperty("os.name").toLowerCase(); // Do DRI hack on all Linux distributions for best robustness driHackNeeded = (os.startsWith("linux") || new File("/usr/lib/dri").exists() || new File("/usr/X11R6/lib/modules/dri").exists()); // Allow manual overriding for now as a workaround for // problems seen in some situations -- needs more investigation if (System.getProperty("jogl.drihack.disable") != null) { driHackNeeded = false; } return null; } }); if (driHackNeeded) { if (DEBUG) { System.err.println("Beginning DRI hack"); } // Try a few different variants for best robustness // In theory probably only the first is necessary - oglLib = NativeLibrary.open("GL", null); - if (DEBUG && oglLib != null) System.err.println(" Found libGL.so"); - // Allow ATI's fglrx to supersede version in /usr/lib - if (oglLib == null) { - oglLib = NativeLibrary.open("/usr/lib/ati-fglrx/libGL.so.1.2", null); - if (DEBUG && oglLib != null) System.err.println(" Found /usr/lib/ati-fglrx/libGL.so.1.2"); - } + oglLib = NativeLibrary.open("libGL.so.1", null); + if (DEBUG && oglLib != null) System.err.println(" Found libGL.so.1"); if (oglLib == null) { oglLib = NativeLibrary.open("/usr/lib/libGL.so.1", null); if (DEBUG && oglLib != null) System.err.println(" Found /usr/lib/libGL.so.1"); } } } public static void end() { if (oglLib != null) { if (DEBUG) { System.err.println("Ending DRI hack"); } oglLib.close(); oglLib = null; } } }
true
true
public static void begin() { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String os = System.getProperty("os.name").toLowerCase(); // Do DRI hack on all Linux distributions for best robustness driHackNeeded = (os.startsWith("linux") || new File("/usr/lib/dri").exists() || new File("/usr/X11R6/lib/modules/dri").exists()); // Allow manual overriding for now as a workaround for // problems seen in some situations -- needs more investigation if (System.getProperty("jogl.drihack.disable") != null) { driHackNeeded = false; } return null; } }); if (driHackNeeded) { if (DEBUG) { System.err.println("Beginning DRI hack"); } // Try a few different variants for best robustness // In theory probably only the first is necessary oglLib = NativeLibrary.open("GL", null); if (DEBUG && oglLib != null) System.err.println(" Found libGL.so"); // Allow ATI's fglrx to supersede version in /usr/lib if (oglLib == null) { oglLib = NativeLibrary.open("/usr/lib/ati-fglrx/libGL.so.1.2", null); if (DEBUG && oglLib != null) System.err.println(" Found /usr/lib/ati-fglrx/libGL.so.1.2"); } if (oglLib == null) { oglLib = NativeLibrary.open("/usr/lib/libGL.so.1", null); if (DEBUG && oglLib != null) System.err.println(" Found /usr/lib/libGL.so.1"); } } }
public static void begin() { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { String os = System.getProperty("os.name").toLowerCase(); // Do DRI hack on all Linux distributions for best robustness driHackNeeded = (os.startsWith("linux") || new File("/usr/lib/dri").exists() || new File("/usr/X11R6/lib/modules/dri").exists()); // Allow manual overriding for now as a workaround for // problems seen in some situations -- needs more investigation if (System.getProperty("jogl.drihack.disable") != null) { driHackNeeded = false; } return null; } }); if (driHackNeeded) { if (DEBUG) { System.err.println("Beginning DRI hack"); } // Try a few different variants for best robustness // In theory probably only the first is necessary oglLib = NativeLibrary.open("libGL.so.1", null); if (DEBUG && oglLib != null) System.err.println(" Found libGL.so.1"); if (oglLib == null) { oglLib = NativeLibrary.open("/usr/lib/libGL.so.1", null); if (DEBUG && oglLib != null) System.err.println(" Found /usr/lib/libGL.so.1"); } } }
diff --git a/blocks/sublima-query/src/main/java/com/computas/sublima/query/service/SearchService.java b/blocks/sublima-query/src/main/java/com/computas/sublima/query/service/SearchService.java index 274f0a0d..59a67f66 100644 --- a/blocks/sublima-query/src/main/java/com/computas/sublima/query/service/SearchService.java +++ b/blocks/sublima-query/src/main/java/com/computas/sublima/query/service/SearchService.java @@ -1,156 +1,156 @@ package com.computas.sublima.query.service; import com.ibm.icu.text.Normalizer; import org.apache.log4j.Logger; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A service class with methods to support advanced and free text search * * @author mha * @version 1.0 */ public class SearchService { private static Logger logger = Logger.getLogger(SearchService.class); private String defaultBooleanOperator; private MappingService mapping = new MappingService(); public SearchService() { } public SearchService(String booleanOperator) { setDefaultBooleanOperator(booleanOperator); } /** * Takes the search string and transform it using the default boolean operator AND/OR * This is done programmaticly since LARQ does not support setting another default boolean operator than OR * * @param searchstring The given search string * @return A transformed search string, using AND/OR based on the configuration */ //todo More advanced check on search string. Ie. - + NOT OR AND if defined in the search term by the user public String buildSearchString(String searchstring, boolean truncate, boolean advancedsearch) { /* try { searchstring = new String(searchstring.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } */ if (!advancedsearch) { searchstring = mapping.charactermapping(searchstring); } // Lucene gives certain characters a meaning, which may cause malformed queries, so remove them if (advancedsearch) { - searchstring = searchstring.replaceAll("[:(){}\\[\\]~\\^\\+\\-\\!\\|\\?\\\\]", ""); + searchstring = searchstring.replaceAll("[&:(){}\\[\\]~\\^\\+\\-\\!\\|\\?\\\\]", ""); } else { // normal freetext search - searchstring = searchstring.replaceAll("[:(){}\\[\\]~\\*\\^\\+\\-\\!\\|\\?\\\\]", ""); + searchstring = searchstring.replaceAll("[&:(){}\\[\\]~\\*\\^\\+\\-\\!\\|\\?\\\\]", ""); } searchstring = searchstring.replace("&&", ""); Pattern p = Pattern.compile("(\\S+)|(\\\"[^\\\"]+\\\")"); Matcher m = p.matcher(searchstring); List<String> terms = new ArrayList<String>(); while (m.find()) { terms.add(m.group()); } String actual = ""; for (String term : terms) { actual += ("".equals(actual) ? "" : " " + defaultBooleanOperator + " ") + term; } // Split the search string, and add * after each word that isn't a part of a phrase boolean partOfPhrase = false; StringBuilder querystring = new StringBuilder(); String[] partialSearchString = actual.split(" "); for (String aPartialSearchString : partialSearchString) { if(!advancedsearch) { aPartialSearchString = mapping.charactermapping(aPartialSearchString); } if (aPartialSearchString.startsWith("\"")) { partOfPhrase = true; querystring.append("'"); } if ("AND".equalsIgnoreCase(aPartialSearchString) || "OR".equalsIgnoreCase(aPartialSearchString)) { if (!partOfPhrase) { querystring.append(aPartialSearchString + " "); } } else { if (partOfPhrase) { if (aPartialSearchString.endsWith("\"")) { querystring.append(aPartialSearchString + "' "); } else { querystring.append(aPartialSearchString + " "); } } else if (!truncate || aPartialSearchString.length() <= 3) { querystring.append("'" + aPartialSearchString + "' "); } else { querystring.append("'" + aPartialSearchString + "*' "); } if (aPartialSearchString.endsWith("\"")) { partOfPhrase = false; } } } actual = querystring.toString().trim(); if (actual.endsWith("\"")) { // since it would cause four double quotes actual = actual + " "; } return actual; } /** * Method to escape characters \ and " in a String * * @param raw * @return String with characters escaped */ public String escapeString(String raw) { raw = raw.replace("\\", "\\\\"); raw = raw.replace("\"", "\\\""); return raw; } public String sanitizeStringForURI(String raw) { // Normalizer normalizer = new String out = Normalizer.normalize(raw, Normalizer.NFD); out = out.replaceAll("[^\\p{ASCII}]", ""); // Removes all fluff on chars out = out.toLowerCase(); out = out.replaceAll("\\s+", "-"); // All spaces become one - out = out.replaceAll("[^\\w-]", ""); // Remove all now not a alphanumeric or - return out; } public void setDefaultBooleanOperator(String defaultBooleanOperator) { this.defaultBooleanOperator = defaultBooleanOperator; } public String getDefaultBooleanOperator() { return this.defaultBooleanOperator; } }
false
true
public String buildSearchString(String searchstring, boolean truncate, boolean advancedsearch) { /* try { searchstring = new String(searchstring.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } */ if (!advancedsearch) { searchstring = mapping.charactermapping(searchstring); } // Lucene gives certain characters a meaning, which may cause malformed queries, so remove them if (advancedsearch) { searchstring = searchstring.replaceAll("[:(){}\\[\\]~\\^\\+\\-\\!\\|\\?\\\\]", ""); } else { // normal freetext search searchstring = searchstring.replaceAll("[:(){}\\[\\]~\\*\\^\\+\\-\\!\\|\\?\\\\]", ""); } searchstring = searchstring.replace("&&", ""); Pattern p = Pattern.compile("(\\S+)|(\\\"[^\\\"]+\\\")"); Matcher m = p.matcher(searchstring); List<String> terms = new ArrayList<String>(); while (m.find()) { terms.add(m.group()); } String actual = ""; for (String term : terms) { actual += ("".equals(actual) ? "" : " " + defaultBooleanOperator + " ") + term; } // Split the search string, and add * after each word that isn't a part of a phrase boolean partOfPhrase = false; StringBuilder querystring = new StringBuilder(); String[] partialSearchString = actual.split(" "); for (String aPartialSearchString : partialSearchString) { if(!advancedsearch) { aPartialSearchString = mapping.charactermapping(aPartialSearchString); } if (aPartialSearchString.startsWith("\"")) { partOfPhrase = true; querystring.append("'"); } if ("AND".equalsIgnoreCase(aPartialSearchString) || "OR".equalsIgnoreCase(aPartialSearchString)) { if (!partOfPhrase) { querystring.append(aPartialSearchString + " "); } } else { if (partOfPhrase) { if (aPartialSearchString.endsWith("\"")) { querystring.append(aPartialSearchString + "' "); } else { querystring.append(aPartialSearchString + " "); } } else if (!truncate || aPartialSearchString.length() <= 3) { querystring.append("'" + aPartialSearchString + "' "); } else { querystring.append("'" + aPartialSearchString + "*' "); } if (aPartialSearchString.endsWith("\"")) { partOfPhrase = false; } } } actual = querystring.toString().trim(); if (actual.endsWith("\"")) { // since it would cause four double quotes actual = actual + " "; } return actual; }
public String buildSearchString(String searchstring, boolean truncate, boolean advancedsearch) { /* try { searchstring = new String(searchstring.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } */ if (!advancedsearch) { searchstring = mapping.charactermapping(searchstring); } // Lucene gives certain characters a meaning, which may cause malformed queries, so remove them if (advancedsearch) { searchstring = searchstring.replaceAll("[&:(){}\\[\\]~\\^\\+\\-\\!\\|\\?\\\\]", ""); } else { // normal freetext search searchstring = searchstring.replaceAll("[&:(){}\\[\\]~\\*\\^\\+\\-\\!\\|\\?\\\\]", ""); } searchstring = searchstring.replace("&&", ""); Pattern p = Pattern.compile("(\\S+)|(\\\"[^\\\"]+\\\")"); Matcher m = p.matcher(searchstring); List<String> terms = new ArrayList<String>(); while (m.find()) { terms.add(m.group()); } String actual = ""; for (String term : terms) { actual += ("".equals(actual) ? "" : " " + defaultBooleanOperator + " ") + term; } // Split the search string, and add * after each word that isn't a part of a phrase boolean partOfPhrase = false; StringBuilder querystring = new StringBuilder(); String[] partialSearchString = actual.split(" "); for (String aPartialSearchString : partialSearchString) { if(!advancedsearch) { aPartialSearchString = mapping.charactermapping(aPartialSearchString); } if (aPartialSearchString.startsWith("\"")) { partOfPhrase = true; querystring.append("'"); } if ("AND".equalsIgnoreCase(aPartialSearchString) || "OR".equalsIgnoreCase(aPartialSearchString)) { if (!partOfPhrase) { querystring.append(aPartialSearchString + " "); } } else { if (partOfPhrase) { if (aPartialSearchString.endsWith("\"")) { querystring.append(aPartialSearchString + "' "); } else { querystring.append(aPartialSearchString + " "); } } else if (!truncate || aPartialSearchString.length() <= 3) { querystring.append("'" + aPartialSearchString + "' "); } else { querystring.append("'" + aPartialSearchString + "*' "); } if (aPartialSearchString.endsWith("\"")) { partOfPhrase = false; } } } actual = querystring.toString().trim(); if (actual.endsWith("\"")) { // since it would cause four double quotes actual = actual + " "; } return actual; }
diff --git a/src/music/Note.java b/src/music/Note.java index 941efef..3bcf731 100644 --- a/src/music/Note.java +++ b/src/music/Note.java @@ -1,98 +1,98 @@ package music; /** * Note represents a note played by an instrument. */ public class Note implements Music { private final double duration; private final Pitch pitch; private final Instrument instrument; private void checkRep() { assert duration >= 0; assert instrument != null; } /** * Make a Note. * @requires duration >= 0, pitch != null, instrument != null * @return note played by instrument for duration beats */ public Note(double duration, Pitch pitch, Instrument instrument) { this.duration = duration; this.pitch = pitch; this.instrument = instrument; checkRep(); } /** * @return duration of this note */ public double duration() { return duration; } /** * @return pitch of this note */ public Pitch pitch() { return pitch; } /** * @return instrument that should play this note */ public Instrument instrument() { return instrument; } /** * @requires v != null */ public <T> T accept(Visitor<T> v) { return v.on(this); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(duration); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((instrument == null) ? 0 : instrument.hashCode()); result = prime * result + ((pitch == null) ? 0 : pitch.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) - return true; + return false; if (getClass() != obj.getClass()) return false; final Note other = (Note) obj; if (duration != other.duration) return false; if (!instrument.equals(other.instrument)) return false; if (!pitch.equals(other.pitch)) return false; return true; } @Override public String toString() { return pitch.toString() + duration; } public static void testNote() { Note n = new Note(10, new Pitch('C'), Instrument.PIANO); System.out.println("Note is: " + n); Note n = new Note(10, new Pitch('C').transpose(1), Instrument.PIANO); System.out.println("Note is: " + n); } }
true
true
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return true; if (getClass() != obj.getClass()) return false; final Note other = (Note) obj; if (duration != other.duration) return false; if (!instrument.equals(other.instrument)) return false; if (!pitch.equals(other.pitch)) return false; return true; }
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Note other = (Note) obj; if (duration != other.duration) return false; if (!instrument.equals(other.instrument)) return false; if (!pitch.equals(other.pitch)) return false; return true; }
diff --git a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java index ea2f23ee7b..b0b54947df 100644 --- a/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java +++ b/sonar-batch/src/main/java/org/sonar/batch/components/PastSnapshotFinderByPreviousVersion.java @@ -1,61 +1,61 @@ /* * Sonar, open source software quality management tool. * Copyright (C) 2008-2012 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.batch.components; import org.sonar.api.BatchExtension; import org.sonar.api.CoreProperties; import org.sonar.api.database.DatabaseSession; import org.sonar.api.database.model.Snapshot; import org.sonar.api.resources.Qualifiers; import java.util.Date; import java.util.List; public class PastSnapshotFinderByPreviousVersion implements BatchExtension { private final DatabaseSession session; public PastSnapshotFinderByPreviousVersion(DatabaseSession session) { this.session = session; } PastSnapshot findByPreviousVersion(Snapshot projectSnapshot) { String hql = "from " + Snapshot.class.getSimpleName() + - " where version!=:version AND version!='' AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt desc"; + " where version<>:version AND version IS NOT NULL AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt desc"; List<Snapshot> snapshots = session.createQuery(hql) .setParameter("version", projectSnapshot.getVersion()) .setParameter("resourceId", projectSnapshot.getResourceId()) .setParameter("status", Snapshot.STATUS_PROCESSED) .setParameter("lib", Qualifiers.LIBRARY) .setMaxResults(1) .getResultList(); PastSnapshot result; if (snapshots.isEmpty()) { result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION); } else { Snapshot snapshot = snapshots.get(0); Date targetDate = snapshot.getCreatedAt(); result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION, targetDate, snapshot).setModeParameter(snapshot.getVersion()); } return result; } }
true
true
PastSnapshot findByPreviousVersion(Snapshot projectSnapshot) { String hql = "from " + Snapshot.class.getSimpleName() + " where version!=:version AND version!='' AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt desc"; List<Snapshot> snapshots = session.createQuery(hql) .setParameter("version", projectSnapshot.getVersion()) .setParameter("resourceId", projectSnapshot.getResourceId()) .setParameter("status", Snapshot.STATUS_PROCESSED) .setParameter("lib", Qualifiers.LIBRARY) .setMaxResults(1) .getResultList(); PastSnapshot result; if (snapshots.isEmpty()) { result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION); } else { Snapshot snapshot = snapshots.get(0); Date targetDate = snapshot.getCreatedAt(); result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION, targetDate, snapshot).setModeParameter(snapshot.getVersion()); } return result; }
PastSnapshot findByPreviousVersion(Snapshot projectSnapshot) { String hql = "from " + Snapshot.class.getSimpleName() + " where version<>:version AND version IS NOT NULL AND resourceId=:resourceId AND status=:status AND qualifier<>:lib order by createdAt desc"; List<Snapshot> snapshots = session.createQuery(hql) .setParameter("version", projectSnapshot.getVersion()) .setParameter("resourceId", projectSnapshot.getResourceId()) .setParameter("status", Snapshot.STATUS_PROCESSED) .setParameter("lib", Qualifiers.LIBRARY) .setMaxResults(1) .getResultList(); PastSnapshot result; if (snapshots.isEmpty()) { result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION); } else { Snapshot snapshot = snapshots.get(0); Date targetDate = snapshot.getCreatedAt(); result = new PastSnapshot(CoreProperties.TIMEMACHINE_MODE_PREVIOUS_VERSION, targetDate, snapshot).setModeParameter(snapshot.getVersion()); } return result; }
diff --git a/src/org/ethelred/mymailtool/ApplyMessageRulesTask.java b/src/org/ethelred/mymailtool/ApplyMessageRulesTask.java index 43c1529..bc2da56 100644 --- a/src/org/ethelred/mymailtool/ApplyMessageRulesTask.java +++ b/src/org/ethelred/mymailtool/ApplyMessageRulesTask.java @@ -1,182 +1,182 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ethelred.mymailtool; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import javax.mail.Address; import javax.mail.Flags.Flag; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Store; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; /** * * @author edward */ class ApplyMessageRulesTask extends MessageOpTask { private final static String RULE_PREFIX = "rule."; private List<RuleConfig> rules; protected ApplyMessageRulesTask(Properties p) { super(p); rules = new ArrayList<RuleConfig>(); } @Override protected void init(Store store) { super.init(store); for (int i = 1; props.containsKey(RULE_PREFIX + i + ".type"); i++) { initRule(i, store); } } private void initRule(int i, Store store) { try { RuleType type = RuleType.valueOf(props.getProperty(RULE_PREFIX + i + ".type")); String fromAddressList = props.getProperty(RULE_PREFIX + i + ".match"); if(fromAddressList == null) { fromAddressList = props.getProperty(RULE_PREFIX + i + ".from"); } String moveTo = props.getProperty(RULE_PREFIX + i + ".folder"); String toAddressList = props.getProperty(RULE_PREFIX + i + ".to"); RuleConfig newRule = new RuleConfig(); newRule.type = type; if (fromAddressList != null && "*".equals(fromAddressList.trim())) { newRule.any = true; - } else { + } else if (fromAddressList != null) { newRule.fromAddresses = InternetAddress.parse(fromAddressList); } if(toAddressList != null) { newRule.toAddresses = InternetAddress.parse(toAddressList); } if (type == RuleType.move) { newRule.moveTo = getFolder(store, moveTo); if (newRule.moveTo == null) { return; // don't add } } rules.add(newRule); System.out.println("Added rule " + newRule); } catch (AddressException ex) { Logger.getLogger(ApplyMessageRulesTask.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { Logger.getLogger(FromCountTask.class.getName()).log(Level.SEVERE, null, ex); } } @Override protected boolean processMessage(Message m, Store store, Folder folder) { for (RuleConfig rule : rules) { if (rule.matches(m)) { rule.apply(m, store, folder); return true; } } return false; } @Override protected String getPrefix() { return RULE_PREFIX; } static enum RuleType { move, delete } static class RuleConfig { @Override public String toString() { return String.format("Message Rule: %s %s to %s", type, any ? "*" : Arrays.toString(fromAddresses), moveTo); } Address[] fromAddresses; Address[] toAddresses; Folder moveTo; RuleType type; boolean any = false; private boolean matches(Message m) { return fromMatches(m) && toMatches(m); } private boolean toMatches(Message m) { if(toAddresses == null || toAddresses.length == 0) { return true; } try { Address[] to = m.getAllRecipients(); for (Address a : toAddresses) { for(Address b: to) { if(a != null && a.equals(b)) { return true; } } } } catch (MessagingException ex) { Logger.getLogger(ApplyMessageRulesTask.class.getName()).log(Level.SEVERE, null, ex); } return false; } private boolean fromMatches(Message m) { if (any || fromAddresses == null || fromAddresses.length == 0) { return true; } try { Address[] from = m.getFrom(); if (from.length != 1) { return false; } for (Address a : fromAddresses) { if (from[0].equals(a)) { return true; } } } catch (MessagingException ex) { Logger.getLogger(ApplyMessageRulesTask.class.getName()).log(Level.SEVERE, null, ex); } return false; } private void apply(Message m, Store store, Folder current) { try { if (type == RuleType.move) { current.copyMessages(new Message[]{m}, moveTo); System.out.printf("Moving message %s to %s%n", m, moveTo); } if (type == RuleType.move || type == RuleType.delete) { m.setFlag(Flag.DELETED, true); if (type == RuleType.delete) { System.out.printf("Deleting message %s %n", m); } } } catch (MessagingException ex) { Logger.getLogger(ApplyMessageRulesTask.class.getName()).log(Level.SEVERE, null, ex); } } } }
true
true
private void initRule(int i, Store store) { try { RuleType type = RuleType.valueOf(props.getProperty(RULE_PREFIX + i + ".type")); String fromAddressList = props.getProperty(RULE_PREFIX + i + ".match"); if(fromAddressList == null) { fromAddressList = props.getProperty(RULE_PREFIX + i + ".from"); } String moveTo = props.getProperty(RULE_PREFIX + i + ".folder"); String toAddressList = props.getProperty(RULE_PREFIX + i + ".to"); RuleConfig newRule = new RuleConfig(); newRule.type = type; if (fromAddressList != null && "*".equals(fromAddressList.trim())) { newRule.any = true; } else { newRule.fromAddresses = InternetAddress.parse(fromAddressList); } if(toAddressList != null) { newRule.toAddresses = InternetAddress.parse(toAddressList); } if (type == RuleType.move) { newRule.moveTo = getFolder(store, moveTo); if (newRule.moveTo == null) { return; // don't add } } rules.add(newRule); System.out.println("Added rule " + newRule); } catch (AddressException ex) { Logger.getLogger(ApplyMessageRulesTask.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { Logger.getLogger(FromCountTask.class.getName()).log(Level.SEVERE, null, ex); } }
private void initRule(int i, Store store) { try { RuleType type = RuleType.valueOf(props.getProperty(RULE_PREFIX + i + ".type")); String fromAddressList = props.getProperty(RULE_PREFIX + i + ".match"); if(fromAddressList == null) { fromAddressList = props.getProperty(RULE_PREFIX + i + ".from"); } String moveTo = props.getProperty(RULE_PREFIX + i + ".folder"); String toAddressList = props.getProperty(RULE_PREFIX + i + ".to"); RuleConfig newRule = new RuleConfig(); newRule.type = type; if (fromAddressList != null && "*".equals(fromAddressList.trim())) { newRule.any = true; } else if (fromAddressList != null) { newRule.fromAddresses = InternetAddress.parse(fromAddressList); } if(toAddressList != null) { newRule.toAddresses = InternetAddress.parse(toAddressList); } if (type == RuleType.move) { newRule.moveTo = getFolder(store, moveTo); if (newRule.moveTo == null) { return; // don't add } } rules.add(newRule); System.out.println("Added rule " + newRule); } catch (AddressException ex) { Logger.getLogger(ApplyMessageRulesTask.class.getName()).log(Level.SEVERE, null, ex); } catch (MessagingException ex) { Logger.getLogger(FromCountTask.class.getName()).log(Level.SEVERE, null, ex); } }
diff --git a/src/graph-editor/src/com/trendmicro/tme/grapheditor/GraphEditorMain.java b/src/graph-editor/src/com/trendmicro/tme/grapheditor/GraphEditorMain.java index 33cc302..42e9474 100644 --- a/src/graph-editor/src/com/trendmicro/tme/grapheditor/GraphEditorMain.java +++ b/src/graph-editor/src/com/trendmicro/tme/grapheditor/GraphEditorMain.java @@ -1,93 +1,93 @@ package com.trendmicro.tme.grapheditor; import java.io.FileInputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.apache.jasper.servlet.JspServlet; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.servlet.DefaultServlet; import org.eclipse.jetty.servlet.FilterHolder; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.trendmicro.codi.ZKSessionManager; import com.trendmicro.tme.mfr.ExchangeFarm; public class GraphEditorMain { private static final String CONFIG_PATH = System.getProperty("com.trendmicro.tme.grapheditor.conf", "/opt/trend/tme/conf/graph-editor/graph-editor.properties"); private static final Logger logger = LoggerFactory.getLogger(GraphEditorMain.class); static { System.loadLibrary("gv_java"); } public static void main(String[] args) throws Exception { try { Properties prop = new Properties(); prop.load(new FileInputStream(CONFIG_PATH)); // Let the system properties override the ones in the config file prop.putAll(System.getProperties()); String connectString = prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.quorum") + prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.tmeroot"); ZKSessionManager.initialize(connectString, Integer.valueOf(prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.timeout"))); ZKSessionManager.instance().waitConnected(); HandlerList handlers = new HandlerList(); Map<Class<?>, Object> classMap = new HashMap<Class<?>, Object>(); classMap.put(ExchangeFarm.class, new ExchangeFarm()); ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS); ServletHolder jerseyHolder = new ServletHolder(new GraphEditorContainer(classMap)); handler.addServlet(new ServletHolder(new DefaultServlet()), "/static/*"); handler.addServlet(new ServletHolder(new Proxy()), "/proxy/*"); ServletHolder jspHolder = new ServletHolder(new JspServlet()); jspHolder.setInitParameter("scratchdir", prop.getProperty("jasper.scratchdir", "/var/lib/tme/graph-editor/jsp")); jspHolder.setInitParameter("trimSpaces", "true"); jspHolder.setInitParameter("portalhost", prop.getProperty("com.trendmicro.tme.grapheditor.portalhost", "")); handler.addServlet(jspHolder, "*.jsp"); handler.setResourceBase(prop.getProperty("com.trendmicro.tme.grapheditor.webdir")); logger.info("Web resource base is set to {}", prop.getProperty("com.trendmicro.tme.grapheditor.webdir")); jerseyHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); jerseyHolder.setInitParameter("com.sun.jersey.config.property.packages", "com.trendmicro.tme.grapheditor"); handler.addServlet(jerseyHolder, "/webapp/graph-editor/*"); FilterHolder loggingFilterHolder = new FilterHolder(new LoggingFilter()); loggingFilterHolder.setInitParameter("name", "Brain"); handler.addFilter(loggingFilterHolder, "/*", 1); handlers.addHandler(handler); int port = Integer.valueOf(prop.getProperty("com.trendmicro.tme.grapheditor.port")); Server server = new Server(port); server.setHandler(handlers); server.start(); System.err.println("Graph Editor started listening on port " + port); logger.info("Graph Editor started listening on port " + port); - IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "graph/graph.jsp")).openConnection().getInputStream()); - IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "graph/index.jsp")).openConnection().getInputStream()); - IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "processor/processor.jsp")).openConnection().getInputStream()); - IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "processor/index.jsp")).openConnection().getInputStream()); - IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "exchange/exchange.jsp")).openConnection().getInputStream()); + IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "graph/graph.jsp")).openConnection().getInputStream()); + IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "graph/index.jsp")).openConnection().getInputStream()); + IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "processor/processor.jsp")).openConnection().getInputStream()); + IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "processor/index.jsp")).openConnection().getInputStream()); + IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "exchange/exchange.jsp")).openConnection().getInputStream()); server.join(); } catch(Exception e) { e.printStackTrace(); logger.error("Graph Editor startup error: ", e); System.exit(-1); } } }
true
true
public static void main(String[] args) throws Exception { try { Properties prop = new Properties(); prop.load(new FileInputStream(CONFIG_PATH)); // Let the system properties override the ones in the config file prop.putAll(System.getProperties()); String connectString = prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.quorum") + prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.tmeroot"); ZKSessionManager.initialize(connectString, Integer.valueOf(prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.timeout"))); ZKSessionManager.instance().waitConnected(); HandlerList handlers = new HandlerList(); Map<Class<?>, Object> classMap = new HashMap<Class<?>, Object>(); classMap.put(ExchangeFarm.class, new ExchangeFarm()); ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS); ServletHolder jerseyHolder = new ServletHolder(new GraphEditorContainer(classMap)); handler.addServlet(new ServletHolder(new DefaultServlet()), "/static/*"); handler.addServlet(new ServletHolder(new Proxy()), "/proxy/*"); ServletHolder jspHolder = new ServletHolder(new JspServlet()); jspHolder.setInitParameter("scratchdir", prop.getProperty("jasper.scratchdir", "/var/lib/tme/graph-editor/jsp")); jspHolder.setInitParameter("trimSpaces", "true"); jspHolder.setInitParameter("portalhost", prop.getProperty("com.trendmicro.tme.grapheditor.portalhost", "")); handler.addServlet(jspHolder, "*.jsp"); handler.setResourceBase(prop.getProperty("com.trendmicro.tme.grapheditor.webdir")); logger.info("Web resource base is set to {}", prop.getProperty("com.trendmicro.tme.grapheditor.webdir")); jerseyHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); jerseyHolder.setInitParameter("com.sun.jersey.config.property.packages", "com.trendmicro.tme.grapheditor"); handler.addServlet(jerseyHolder, "/webapp/graph-editor/*"); FilterHolder loggingFilterHolder = new FilterHolder(new LoggingFilter()); loggingFilterHolder.setInitParameter("name", "Brain"); handler.addFilter(loggingFilterHolder, "/*", 1); handlers.addHandler(handler); int port = Integer.valueOf(prop.getProperty("com.trendmicro.tme.grapheditor.port")); Server server = new Server(port); server.setHandler(handlers); server.start(); System.err.println("Graph Editor started listening on port " + port); logger.info("Graph Editor started listening on port " + port); IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "graph/graph.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "graph/index.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "processor/processor.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "processor/index.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://localhost:%d/%s?jsp_precompile", port, "exchange/exchange.jsp")).openConnection().getInputStream()); server.join(); } catch(Exception e) { e.printStackTrace(); logger.error("Graph Editor startup error: ", e); System.exit(-1); } }
public static void main(String[] args) throws Exception { try { Properties prop = new Properties(); prop.load(new FileInputStream(CONFIG_PATH)); // Let the system properties override the ones in the config file prop.putAll(System.getProperties()); String connectString = prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.quorum") + prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.tmeroot"); ZKSessionManager.initialize(connectString, Integer.valueOf(prop.getProperty("com.trendmicro.tme.grapheditor.zookeeper.timeout"))); ZKSessionManager.instance().waitConnected(); HandlerList handlers = new HandlerList(); Map<Class<?>, Object> classMap = new HashMap<Class<?>, Object>(); classMap.put(ExchangeFarm.class, new ExchangeFarm()); ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS); ServletHolder jerseyHolder = new ServletHolder(new GraphEditorContainer(classMap)); handler.addServlet(new ServletHolder(new DefaultServlet()), "/static/*"); handler.addServlet(new ServletHolder(new Proxy()), "/proxy/*"); ServletHolder jspHolder = new ServletHolder(new JspServlet()); jspHolder.setInitParameter("scratchdir", prop.getProperty("jasper.scratchdir", "/var/lib/tme/graph-editor/jsp")); jspHolder.setInitParameter("trimSpaces", "true"); jspHolder.setInitParameter("portalhost", prop.getProperty("com.trendmicro.tme.grapheditor.portalhost", "")); handler.addServlet(jspHolder, "*.jsp"); handler.setResourceBase(prop.getProperty("com.trendmicro.tme.grapheditor.webdir")); logger.info("Web resource base is set to {}", prop.getProperty("com.trendmicro.tme.grapheditor.webdir")); jerseyHolder.setInitParameter("com.sun.jersey.config.property.resourceConfigClass", "com.sun.jersey.api.core.PackagesResourceConfig"); jerseyHolder.setInitParameter("com.sun.jersey.config.property.packages", "com.trendmicro.tme.grapheditor"); handler.addServlet(jerseyHolder, "/webapp/graph-editor/*"); FilterHolder loggingFilterHolder = new FilterHolder(new LoggingFilter()); loggingFilterHolder.setInitParameter("name", "Brain"); handler.addFilter(loggingFilterHolder, "/*", 1); handlers.addHandler(handler); int port = Integer.valueOf(prop.getProperty("com.trendmicro.tme.grapheditor.port")); Server server = new Server(port); server.setHandler(handlers); server.start(); System.err.println("Graph Editor started listening on port " + port); logger.info("Graph Editor started listening on port " + port); IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "graph/graph.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "graph/index.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "processor/processor.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "processor/index.jsp")).openConnection().getInputStream()); IOUtils.closeQuietly(new URL(String.format("http://127.0.0.1:%d/%s?jsp_precompile", port, "exchange/exchange.jsp")).openConnection().getInputStream()); server.join(); } catch(Exception e) { e.printStackTrace(); logger.error("Graph Editor startup error: ", e); System.exit(-1); } }
diff --git a/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerRun.java b/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerRun.java index 659020a6..96b718cf 100644 --- a/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerRun.java +++ b/javafx.project/src/org/netbeans/modules/javafx/project/ui/customizer/CustomizerRun.java @@ -1,813 +1,813 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * The Original Software is NetBeans. The Initial Developer of the Original * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun * Microsystems, Inc. All Rights Reserved. * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. */ package org.netbeans.modules.javafx.project.ui.customizer; import java.awt.Component; import java.awt.Dialog; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.text.Collator; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.SortedSet; import java.util.TreeSet; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.ListCellRenderer; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.plaf.UIResource; import javax.swing.text.JTextComponent; import org.netbeans.api.java.platform.JavaPlatform; import org.netbeans.api.javafx.platform.JavaFXPlatform; import org.netbeans.modules.java.api.common.SourceRoots; import org.netbeans.modules.javafx.platform.PlatformUiSupport; import org.netbeans.modules.javafx.project.JavaFXProject; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.awt.MouseUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.util.RequestProcessor; import org.openide.util.Utilities; public class CustomizerRun extends JPanel implements HelpCtx.Provider { private JavaFXProject project; private JTextComponent[] data; private JLabel[] dataLabels; private String[] keys; private Map<String, Map<String, String>> configs; JavaFXProjectProperties uiProperties; public CustomizerRun(JavaFXProjectProperties uiProperties) { this.uiProperties = uiProperties; initComponents(); this.project = uiProperties.getProject(); PlatformUiSupport.PlatformKey pk = (PlatformUiSupport.PlatformKey)uiProperties.PLATFORM_MODEL.getSelectedItem(); if (pk != null) { JavaPlatform jp = PlatformUiSupport.getPlatform(pk); if (jp instanceof JavaFXPlatform) try { jRadioButton4.setEnabled(new File(new File(((JavaFXPlatform)jp).getJavaFXFolder().toURI()), "emulator/mobile/bin/preverify" + (Utilities.isWindows() ? ".exe" : "")).isFile()); //NOI18N } catch (URISyntaxException e) {} } configs = uiProperties.RUN_CONFIGS; data = new JTextComponent[]{jTextFieldMainClass, jTextArguments, jvmText, (JTextComponent)deviceCombo.getEditor().getEditorComponent()}; dataLabels = new JLabel[]{jLabelMainClass, jLabelArguments, jvmLabel, deviceLabel}; keys = new String[]{JavaFXProjectProperties.MAIN_CLASS, JavaFXProjectProperties.APPLICATION_ARGS, JavaFXProjectProperties.RUN_JVM_ARGS, JavaFXProjectProperties.MOBILE_DEVICE}; assert data.length == keys.length; configChanged(uiProperties.activeConfig); configUpdated(); configCombo.setRenderer(new ConfigListCellRenderer()); for (int i = 0; i < data.length; i++) { final JTextComponent field = data[i]; final String prop = keys[i]; final JLabel label = dataLabels[i]; field.getDocument().addDocumentListener(new DocumentListener() { Font basefont = label.getFont(); Font boldfont = basefont.deriveFont(Font.BOLD); { updateFont(); } public void insertUpdate(DocumentEvent e) { changed(); } public void removeUpdate(DocumentEvent e) { changed(); } public void changedUpdate(DocumentEvent e) { } void changed() { String config = (String) configCombo.getSelectedItem(); if (config.length() == 0) { config = null; } String v = field.getText(); if (v != null && config != null && v.equals(configs.get(null).get(prop))) { // default value, do not store as such v = null; } if (v != null && v.equals("")) v = " "; // NOI18N configs.get(config).put(prop, v); updateFont(); } void updateFont() { String v = field.getText(); String config = (String) configCombo.getSelectedItem(); if (config.length() == 0) { config = null; } String def = configs.get(null).get(prop); label.setFont(config != null && !Utilities.compareObjects(v != null ? v : "", def != null ? def : "") ? boldfont : basefont); // NOI18N } }); } installCheckBox1.addActionListener(new ActionListener() { Font basefont = installCheckBox1.getFont(); Font boldfont = basefont.deriveFont(Font.BOLD); { updateFont(); } public void actionPerformed(ActionEvent e) { String config = (String) configCombo.getSelectedItem(); if (config.length() == 0) { configs.get(null).put(JavaFXProjectProperties.JAD_INSTALL, String.valueOf(installCheckBox1.isSelected())); } else { configs.get(config).put(JavaFXProjectProperties.JAD_INSTALL, Boolean.parseBoolean(configs.get(null).get(JavaFXProjectProperties.JAD_INSTALL)) != installCheckBox1.isSelected() ? String.valueOf(installCheckBox1.isSelected()) : null); } updateFont(); } void updateFont() { String config = (String) configCombo.getSelectedItem(); if (config.length() == 0) { installCheckBox1.setFont(basefont); } else { installCheckBox1.setFont(Boolean.parseBoolean(configs.get(null).get(JavaFXProjectProperties.JAD_INSTALL)) == installCheckBox1.isSelected() ? basefont : boldfont); // NOI18N } } }); jButtonMainClass.addActionListener(new MainClassListener(project.getSourceRoots(), jTextFieldMainClass)); } public HelpCtx getHelpCtx() { return new HelpCtx(CustomizerRun.class); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); configSep = new javax.swing.JSeparator(); configPanel = new javax.swing.JPanel(); configLabel = new javax.swing.JLabel(); configCombo = new javax.swing.JComboBox(); configNew = new javax.swing.JButton(); configDel = new javax.swing.JButton(); mainPanel = new javax.swing.JPanel(); jLabelMainClass = new javax.swing.JLabel(); jTextFieldMainClass = new javax.swing.JTextField(); jButtonMainClass = new javax.swing.JButton(); jLabelArguments = new javax.swing.JLabel(); jTextArguments = new javax.swing.JTextField(); extPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jRadioButton4 = new javax.swing.JRadioButton(); deviceLabel = new javax.swing.JLabel(); deviceCombo = new javax.swing.JComboBox(); installCheckBox1 = new javax.swing.JCheckBox(); jvmLabel = new javax.swing.JLabel(); jvmText = new javax.swing.JTextField(); jRadioButton5 = new javax.swing.JRadioButton(); setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(configSep, gridBagConstraints); configPanel.setLayout(new java.awt.GridBagLayout()); configLabel.setLabelFor(configCombo); org.openide.awt.Mnemonics.setLocalizedText(configLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configLabel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0); configPanel.add(configLabel, gridBagConstraints); configLabel.getAccessibleContext().setAccessibleDescription("Configuration profile"); configCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<default>" })); configCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(configNew, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configNew")); // NOI18N configNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configNewActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configNew, gridBagConstraints); configNew.getAccessibleContext().setAccessibleDescription("Button for creating new profile"); org.openide.awt.Mnemonics.setLocalizedText(configDel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configDelete")); // NOI18N configDel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configDelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configDel, gridBagConstraints); configDel.getAccessibleContext().setAccessibleDescription("Deletes current configuration profile"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(configPanel, gridBagConstraints); mainPanel.setLayout(new java.awt.GridBagLayout()); jLabelMainClass.setLabelFor(jTextFieldMainClass); org.openide.awt.Mnemonics.setLocalizedText(jLabelMainClass, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizeRun_Run_MainClass_JLabel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); mainPanel.add(jLabelMainClass, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 5, 0); mainPanel.add(jTextFieldMainClass, gridBagConstraints); jTextFieldMainClass.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("AD_jTextFieldMainClass")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jButtonMainClass, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizeRun_Run_MainClass_JButton")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 6, 5, 0); mainPanel.add(jButtonMainClass, gridBagConstraints); jButtonMainClass.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("AD_jButtonMainClass")); // NOI18N jLabelArguments.setLabelFor(jTextArguments); org.openide.awt.Mnemonics.setLocalizedText(jLabelArguments, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustRun_Arguments")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); mainPanel.add(jLabelArguments, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 5, 0); mainPanel.add(jTextArguments, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(mainPanel, gridBagConstraints); extPanel.setLayout(new java.awt.GridBagLayout()); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jLabel1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 0, 5, 0); extPanel.add(jLabel1, gridBagConstraints); buttonGroup1.add(jRadioButton1); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton1, org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("CustomizerRunComponent.jRadioButton1.text")); // NOI18N jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; extPanel.add(jRadioButton1, gridBagConstraints); buttonGroup1.add(jRadioButton2); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton2, org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("CustomizerRunComponent.jRadioButton2.text")); // NOI18N jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton2, gridBagConstraints); buttonGroup1.add(jRadioButton3); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton3, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton3.text")); // NOI18N jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton3, gridBagConstraints); buttonGroup1.add(jRadioButton4); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton4, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton4.text")); // NOI18N jRadioButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton4ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton4, gridBagConstraints); deviceLabel.setLabelFor(deviceCombo); org.openide.awt.Mnemonics.setLocalizedText(deviceLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_MobileDevice")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(5, 32, 0, 0); extPanel.add(deviceLabel, gridBagConstraints); deviceCombo.setEditable(true); deviceCombo.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { deviceComboPopupMenuWillBecomeVisible(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); extPanel.add(deviceCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(installCheckBox1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizerRun_InstallPermanently")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); extPanel.add(installCheckBox1, gridBagConstraints); jvmLabel.setLabelFor(jvmText); org.openide.awt.Mnemonics.setLocalizedText(jvmLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizerRun_JVMArgs")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0); extPanel.add(jvmLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 12, 0, 0); extPanel.add(jvmText, gridBagConstraints); buttonGroup1.add(jRadioButton5); + org.openide.awt.Mnemonics.setLocalizedText(jRadioButton5, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton5.text")); // NOI18N jRadioButton5.setActionCommand("Run in &TV Emulator"); - jRadioButton5.setLabel("Run in TV Emulator"); jRadioButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton5ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(extPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents private void configDelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configDelActionPerformed String config = (String) configCombo.getSelectedItem(); assert config != null; configs.put(config, null); configChanged(null); uiProperties.activeConfig = null; }//GEN-LAST:event_configDelActionPerformed private void configNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configNewActionPerformed NotifyDescriptor.InputLine d = new NotifyDescriptor.InputLine(NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.input.prompt"), NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.input.title")); // NOI18N if (DialogDisplayer.getDefault().notify(d) != NotifyDescriptor.OK_OPTION) { return; } String name = d.getInputText(); String config = name.replaceAll("[^a-zA-Z0-9_.-]", "_"); // NOI18N if (configs.get(config) != null) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.input.duplicate", config), NotifyDescriptor.WARNING_MESSAGE)); // NOI18N return; } Map<String, String> m = new HashMap<String, String>(); if (!name.equals(config)) { m.put("$label", name); // NOI18N } m.put("javafx.profile", "desktop"); //NOI18N m.put("execution.target", "standard"); //NOI18N configs.put(config, m); configChanged(config); uiProperties.activeConfig = config; }//GEN-LAST:event_configNewActionPerformed private void configComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_configComboActionPerformed String config = (String) configCombo.getSelectedItem(); if (config.length() == 0) { config = null; } configChanged(config); uiProperties.activeConfig = config; configUpdated(); }//GEN-LAST:event_configComboActionPerformed private void enableDeviceCombo() { boolean enabled = jRadioButton4.isEnabled() && jRadioButton4.isSelected(); deviceLabel.setEnabled(enabled); deviceCombo.setEnabled(enabled); installCheckBox1.setEnabled(enabled); } private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed Map<String, String> m = configs.get(uiProperties.activeConfig); m.put("javafx.profile", "desktop"); //NOI18N m.put("execution.target", "standard"); //NOI18N enableDeviceCombo(); }//GEN-LAST:event_jRadioButton1ActionPerformed private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed Map<String, String> m = configs.get(uiProperties.activeConfig); m.put("javafx.profile", "desktop"); //NOI18N m.put("execution.target", "jnlp"); //NOI18N enableDeviceCombo(); }//GEN-LAST:event_jRadioButton2ActionPerformed private void jRadioButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton3ActionPerformed Map<String, String> m = configs.get(uiProperties.activeConfig); m.put("javafx.profile", "desktop"); //NOI18N m.put("execution.target", "applet"); //NOI18N enableDeviceCombo(); }//GEN-LAST:event_jRadioButton3ActionPerformed private void jRadioButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton4ActionPerformed Map<String, String> m = configs.get(uiProperties.activeConfig); m.put("javafx.profile", "mobile"); //NOI18N m.put("execution.target", "midp"); //NOI18N enableDeviceCombo(); }//GEN-LAST:event_jRadioButton4ActionPerformed boolean firstPopup = true; private void deviceComboPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_deviceComboPopupMenuWillBecomeVisible deviceCombo.setSelectedItem(deviceCombo.getEditor().getItem()); if (firstPopup) { firstPopup = false; deviceCombo.addItem(NbBundle.getMessage(CustomizerRun.class, "NODE_PleaseWait"));//NOI18N RequestProcessor.getDefault().post(new Runnable() { public void run() { PlatformUiSupport.PlatformKey pk = (PlatformUiSupport.PlatformKey)uiProperties.PLATFORM_MODEL.getSelectedItem(); if (pk != null) { JavaPlatform jp = PlatformUiSupport.getPlatform(pk); if (jp instanceof JavaFXPlatform) { FileObject fo = jp.findTool("javafxpackager"); //NOI18N if (fo != null) { File em = new File(FileUtil.toFile(fo).getParentFile().getParentFile(), "emulator/mobile/bin/emulator" + (Utilities.isWindows() ? ".exe" : "")); //NOI18N if (em.isFile()) try { Properties p = new Properties(); p.load(Runtime.getRuntime().exec(new String[] {em.getAbsolutePath(), "-Xquery"}).getInputStream()); //NOI18N final String list = p.getProperty("device.list"); //NOI18N if (list != null) SwingUtilities.invokeLater(new Runnable() { public void run() { Object dev = deviceCombo.getEditor().getItem(); deviceCombo.removeAllItems(); for (String name : list.split(",")) deviceCombo.addItem(name.trim()); deviceCombo.setSelectedItem(dev); if (deviceCombo.isPopupVisible()) { deviceCombo.hidePopup(); deviceCombo.showPopup(); } } }); } catch (IOException e) {} } } } } } ); } }//GEN-LAST:event_deviceComboPopupMenuWillBecomeVisible private void jRadioButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton5ActionPerformed Map<String, String> m = configs.get(uiProperties.activeConfig); m.put("javafx.profile", "tv"); //NOI18N m.put("execution.target", "cvm"); //NOI18N enableDeviceCombo(); }//GEN-LAST:event_jRadioButton5ActionPerformed public void configUpdated() { Map<String, String> m = configs.get(uiProperties.activeConfig); String run = m.get("execution.target"); //NOI18N if (run == null || run.equals("standard")) jRadioButton1.setSelected(true); //NOI18N else if (run.equals("jnlp")) jRadioButton2.setSelected(true); //NOI18N else if (run.equals("applet")) jRadioButton3.setSelected(true); //NOI18N else if (run.equals("midp")) jRadioButton4.setSelected(true); //NOI18N else if (run.equals("cvm")) jRadioButton5.setSelected(true); //NOI18N enableDeviceCombo(); } private void configChanged(String activeConfig) { DefaultComboBoxModel model = new DefaultComboBoxModel(); model.addElement(""); // NOI18N SortedSet<String> alphaConfigs = new TreeSet<String>(new Comparator<String>() { Collator coll = Collator.getInstance(); public int compare(String s1, String s2) { return coll.compare(label(s1), label(s2)); } private String label(String c) { Map<String, String> m = configs.get(c); String label = m.get("$label"); // NOI18N return label != null ? label : c; } }); for (Map.Entry<String, Map<String, String>> entry : configs.entrySet()) { String config = entry.getKey(); if (config != null && entry.getValue() != null) { alphaConfigs.add(config); } } for (String c : alphaConfigs) { model.addElement(c); } configCombo.setModel(model); configCombo.setSelectedItem(activeConfig != null ? activeConfig : ""); // NOI18N Map<String, String> m = configs.get(activeConfig); Map<String, String> def = configs.get(null); if (m != null) { for (int i = 0; i < data.length; i++) { String v = m.get(keys[i]); if (v == null) { // display default value v = def.get(keys[i]); } data[i].setText(v); } String v = m.get(JavaFXProjectProperties.JAD_INSTALL); if (v == null) { // display default value v = def.get(JavaFXProjectProperties.JAD_INSTALL); } installCheckBox1.setSelected(Boolean.parseBoolean(v)); for (ActionListener l : installCheckBox1.getActionListeners()) l.actionPerformed(null); } // else ?? configDel.setEnabled(activeConfig != null); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox configCombo; private javax.swing.JButton configDel; private javax.swing.JLabel configLabel; private javax.swing.JButton configNew; private javax.swing.JPanel configPanel; private javax.swing.JSeparator configSep; private javax.swing.JComboBox deviceCombo; private javax.swing.JLabel deviceLabel; private javax.swing.JPanel extPanel; private javax.swing.JCheckBox installCheckBox1; private javax.swing.JButton jButtonMainClass; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabelArguments; private javax.swing.JLabel jLabelMainClass; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JRadioButton jRadioButton4; private javax.swing.JRadioButton jRadioButton5; private javax.swing.JTextField jTextArguments; private javax.swing.JTextField jTextFieldMainClass; private javax.swing.JLabel jvmLabel; private javax.swing.JTextField jvmText; private javax.swing.JPanel mainPanel; // End of variables declaration//GEN-END:variables // End of variables declaration // End of variables declaration // Innercasses ------------------------------------------------------------- private class MainClassListener implements ActionListener { private final JButton okButton; private SourceRoots sourceRoots; private JTextField mainClassTextField; MainClassListener(SourceRoots sourceRoots, JTextField mainClassTextField) { this.sourceRoots = sourceRoots; this.mainClassTextField = mainClassTextField; this.okButton = new JButton(NbBundle.getMessage(CustomizerRun.class, "LBL_ChooseMainClass_OK")); // NOI18N this.okButton.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(CustomizerRun.class, "AD_ChooseMainClass_OK")); // NOI18N } // Implementation of ActionListener ------------------------------------ /** Handles button events */ public void actionPerformed(ActionEvent e) { // only chooseMainClassButton can be performed final MainClassChooser panel = new MainClassChooser(sourceRoots.getRoots() ,null , mainClassTextField.getText()); Object[] options = new Object[]{okButton, DialogDescriptor.CANCEL_OPTION}; panel.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (e.getSource() instanceof MouseEvent && MouseUtils.isDoubleClick((MouseEvent) e.getSource ())) { // click button and finish the dialog with selected class okButton.doClick(); } else { okButton.setEnabled(panel.getSelectedMainClass() != null); } } }); okButton.setEnabled(false); DialogDescriptor desc = new DialogDescriptor(panel, NbBundle.getMessage(CustomizerRun.class, "LBL_ChooseMainClass_Title"), true, options, options[0], DialogDescriptor.BOTTOM_ALIGN, null, null); // NOI18N //desc.setMessageType (DialogDescriptor.INFORMATION_MESSAGE); //desc.setMessageType (DialogDescriptor.INFORMATION_MESSAGE); //desc.setMessageType (DialogDescriptor.INFORMATION_MESSAGE); //desc.setMessageType (DialogDescriptor.INFORMATION_MESSAGE); Dialog dlg = DialogDisplayer.getDefault().createDialog(desc); dlg.setVisible(true); if (desc.getValue() == options[0]) { mainClassTextField.setText(panel.getSelectedMainClass()); } dlg.dispose(); } } private final class ConfigListCellRenderer extends JLabel implements ListCellRenderer, UIResource { public ConfigListCellRenderer() { setOpaque(true); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // #93658: GTK needs name to render cell renderer "natively" setName("ComboBox.listRenderer"); // NOI18N // NOI18N // NOI18N // NOI18N String config = (String) value; String label; if (config == null) { // uninitialized? label = null; } else if (config.length() > 0) { Map<String, String> m = configs.get(config); label = m != null ? m.get("$label") : null; // NOI18N if (label == null) { label = config; } } else { label = NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.default"); // NOI18N } setText(label); if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } return this; } // #93658: GTK needs name to render cell renderer "natively" public String getName() { String name = super.getName(); return name == null ? "ComboBox.renderer" : name; // NOI18N } } }
false
true
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); configSep = new javax.swing.JSeparator(); configPanel = new javax.swing.JPanel(); configLabel = new javax.swing.JLabel(); configCombo = new javax.swing.JComboBox(); configNew = new javax.swing.JButton(); configDel = new javax.swing.JButton(); mainPanel = new javax.swing.JPanel(); jLabelMainClass = new javax.swing.JLabel(); jTextFieldMainClass = new javax.swing.JTextField(); jButtonMainClass = new javax.swing.JButton(); jLabelArguments = new javax.swing.JLabel(); jTextArguments = new javax.swing.JTextField(); extPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jRadioButton4 = new javax.swing.JRadioButton(); deviceLabel = new javax.swing.JLabel(); deviceCombo = new javax.swing.JComboBox(); installCheckBox1 = new javax.swing.JCheckBox(); jvmLabel = new javax.swing.JLabel(); jvmText = new javax.swing.JTextField(); jRadioButton5 = new javax.swing.JRadioButton(); setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(configSep, gridBagConstraints); configPanel.setLayout(new java.awt.GridBagLayout()); configLabel.setLabelFor(configCombo); org.openide.awt.Mnemonics.setLocalizedText(configLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configLabel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0); configPanel.add(configLabel, gridBagConstraints); configLabel.getAccessibleContext().setAccessibleDescription("Configuration profile"); configCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<default>" })); configCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(configNew, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configNew")); // NOI18N configNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configNewActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configNew, gridBagConstraints); configNew.getAccessibleContext().setAccessibleDescription("Button for creating new profile"); org.openide.awt.Mnemonics.setLocalizedText(configDel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configDelete")); // NOI18N configDel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configDelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configDel, gridBagConstraints); configDel.getAccessibleContext().setAccessibleDescription("Deletes current configuration profile"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(configPanel, gridBagConstraints); mainPanel.setLayout(new java.awt.GridBagLayout()); jLabelMainClass.setLabelFor(jTextFieldMainClass); org.openide.awt.Mnemonics.setLocalizedText(jLabelMainClass, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizeRun_Run_MainClass_JLabel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); mainPanel.add(jLabelMainClass, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 5, 0); mainPanel.add(jTextFieldMainClass, gridBagConstraints); jTextFieldMainClass.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("AD_jTextFieldMainClass")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jButtonMainClass, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizeRun_Run_MainClass_JButton")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 6, 5, 0); mainPanel.add(jButtonMainClass, gridBagConstraints); jButtonMainClass.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("AD_jButtonMainClass")); // NOI18N jLabelArguments.setLabelFor(jTextArguments); org.openide.awt.Mnemonics.setLocalizedText(jLabelArguments, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustRun_Arguments")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); mainPanel.add(jLabelArguments, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 5, 0); mainPanel.add(jTextArguments, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(mainPanel, gridBagConstraints); extPanel.setLayout(new java.awt.GridBagLayout()); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jLabel1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 0, 5, 0); extPanel.add(jLabel1, gridBagConstraints); buttonGroup1.add(jRadioButton1); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton1, org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("CustomizerRunComponent.jRadioButton1.text")); // NOI18N jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; extPanel.add(jRadioButton1, gridBagConstraints); buttonGroup1.add(jRadioButton2); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton2, org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("CustomizerRunComponent.jRadioButton2.text")); // NOI18N jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton2, gridBagConstraints); buttonGroup1.add(jRadioButton3); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton3, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton3.text")); // NOI18N jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton3, gridBagConstraints); buttonGroup1.add(jRadioButton4); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton4, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton4.text")); // NOI18N jRadioButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton4ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton4, gridBagConstraints); deviceLabel.setLabelFor(deviceCombo); org.openide.awt.Mnemonics.setLocalizedText(deviceLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_MobileDevice")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(5, 32, 0, 0); extPanel.add(deviceLabel, gridBagConstraints); deviceCombo.setEditable(true); deviceCombo.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { deviceComboPopupMenuWillBecomeVisible(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); extPanel.add(deviceCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(installCheckBox1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizerRun_InstallPermanently")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); extPanel.add(installCheckBox1, gridBagConstraints); jvmLabel.setLabelFor(jvmText); org.openide.awt.Mnemonics.setLocalizedText(jvmLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizerRun_JVMArgs")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0); extPanel.add(jvmLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 12, 0, 0); extPanel.add(jvmText, gridBagConstraints); buttonGroup1.add(jRadioButton5); jRadioButton5.setActionCommand("Run in &TV Emulator"); jRadioButton5.setLabel("Run in TV Emulator"); jRadioButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton5ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(extPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; buttonGroup1 = new javax.swing.ButtonGroup(); configSep = new javax.swing.JSeparator(); configPanel = new javax.swing.JPanel(); configLabel = new javax.swing.JLabel(); configCombo = new javax.swing.JComboBox(); configNew = new javax.swing.JButton(); configDel = new javax.swing.JButton(); mainPanel = new javax.swing.JPanel(); jLabelMainClass = new javax.swing.JLabel(); jTextFieldMainClass = new javax.swing.JTextField(); jButtonMainClass = new javax.swing.JButton(); jLabelArguments = new javax.swing.JLabel(); jTextArguments = new javax.swing.JTextField(); extPanel = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); jRadioButton4 = new javax.swing.JRadioButton(); deviceLabel = new javax.swing.JLabel(); deviceCombo = new javax.swing.JComboBox(); installCheckBox1 = new javax.swing.JCheckBox(); jvmLabel = new javax.swing.JLabel(); jvmText = new javax.swing.JTextField(); jRadioButton5 = new javax.swing.JRadioButton(); setLayout(new java.awt.GridBagLayout()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(configSep, gridBagConstraints); configPanel.setLayout(new java.awt.GridBagLayout()); configLabel.setLabelFor(configCombo); org.openide.awt.Mnemonics.setLocalizedText(configLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configLabel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 0); configPanel.add(configLabel, gridBagConstraints); configLabel.getAccessibleContext().setAccessibleDescription("Configuration profile"); configCombo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "<default>" })); configCombo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configComboActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(configNew, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configNew")); // NOI18N configNew.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configNewActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configNew, gridBagConstraints); configNew.getAccessibleContext().setAccessibleDescription("Button for creating new profile"); org.openide.awt.Mnemonics.setLocalizedText(configDel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRun.configDelete")); // NOI18N configDel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { configDelActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(2, 6, 2, 0); configPanel.add(configDel, gridBagConstraints); configDel.getAccessibleContext().setAccessibleDescription("Deletes current configuration profile"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(configPanel, gridBagConstraints); mainPanel.setLayout(new java.awt.GridBagLayout()); jLabelMainClass.setLabelFor(jTextFieldMainClass); org.openide.awt.Mnemonics.setLocalizedText(jLabelMainClass, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizeRun_Run_MainClass_JLabel")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); mainPanel.add(jLabelMainClass, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 5, 0); mainPanel.add(jTextFieldMainClass, gridBagConstraints); jTextFieldMainClass.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("AD_jTextFieldMainClass")); // NOI18N org.openide.awt.Mnemonics.setLocalizedText(jButtonMainClass, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizeRun_Run_MainClass_JButton")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 6, 5, 0); mainPanel.add(jButtonMainClass, gridBagConstraints); jButtonMainClass.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("AD_jButtonMainClass")); // NOI18N jLabelArguments.setLabelFor(jTextArguments); org.openide.awt.Mnemonics.setLocalizedText(jLabelArguments, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustRun_Arguments")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0); mainPanel.add(jLabelArguments, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(0, 12, 5, 0); mainPanel.add(jTextArguments, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(6, 0, 6, 0); add(mainPanel, gridBagConstraints); extPanel.setLayout(new java.awt.GridBagLayout()); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jLabel1.text")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 0, 5, 0); extPanel.add(jLabel1, gridBagConstraints); buttonGroup1.add(jRadioButton1); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton1, org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("CustomizerRunComponent.jRadioButton1.text")); // NOI18N jRadioButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton1ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; extPanel.add(jRadioButton1, gridBagConstraints); buttonGroup1.add(jRadioButton2); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton2, org.openide.util.NbBundle.getBundle(CustomizerRun.class).getString("CustomizerRunComponent.jRadioButton2.text")); // NOI18N jRadioButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton2ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton2, gridBagConstraints); buttonGroup1.add(jRadioButton3); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton3, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton3.text")); // NOI18N jRadioButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton3ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton3, gridBagConstraints); buttonGroup1.add(jRadioButton4); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton4, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton4.text")); // NOI18N jRadioButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton4ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton4, gridBagConstraints); deviceLabel.setLabelFor(deviceCombo); org.openide.awt.Mnemonics.setLocalizedText(deviceLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_MobileDevice")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 5; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST; gridBagConstraints.insets = new java.awt.Insets(5, 32, 0, 0); extPanel.add(deviceLabel, gridBagConstraints); deviceCombo.setEditable(true); deviceCombo.addPopupMenuListener(new javax.swing.event.PopupMenuListener() { public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) { } public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) { deviceComboPopupMenuWillBecomeVisible(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 5; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); extPanel.add(deviceCombo, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(installCheckBox1, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizerRun_InstallPermanently")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 6; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0); extPanel.add(installCheckBox1, gridBagConstraints); jvmLabel.setLabelFor(jvmText); org.openide.awt.Mnemonics.setLocalizedText(jvmLabel, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "LBL_CustomizerRun_JVMArgs")); // NOI18N gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 8; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.insets = new java.awt.Insets(12, 0, 0, 0); extPanel.add(jvmLabel, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 8; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; gridBagConstraints.insets = new java.awt.Insets(10, 12, 0, 0); extPanel.add(jvmText, gridBagConstraints); buttonGroup1.add(jRadioButton5); org.openide.awt.Mnemonics.setLocalizedText(jRadioButton5, org.openide.util.NbBundle.getMessage(CustomizerRun.class, "CustomizerRunComponent.jRadioButton5.text")); // NOI18N jRadioButton5.setActionCommand("Run in &TV Emulator"); jRadioButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jRadioButton5ActionPerformed(evt); } }); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 7; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; extPanel.add(jRadioButton5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(extPanel, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/tconstruct/common/TContent.java b/src/tconstruct/common/TContent.java index ba6891d01..ad73b3bab 100644 --- a/src/tconstruct/common/TContent.java +++ b/src/tconstruct/common/TContent.java @@ -1,2552 +1,2552 @@ package tconstruct.common; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import tconstruct.library.armor.EnumArmorPart; import tconstruct.library.crafting.ToolBuilder; import cpw.mods.fml.common.*; import cpw.mods.fml.common.event.FMLInterModComms; import cpw.mods.fml.common.registry.*; import java.lang.reflect.Field; import java.util.*; import net.minecraft.block.*; import net.minecraft.block.material.*; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.*; import net.minecraft.item.crafting.*; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.stats.Achievement; import net.minecraft.util.WeightedRandomChestContent; import net.minecraftforge.common.*; import net.minecraftforge.fluids.*; import net.minecraftforge.fluids.FluidContainerRegistry.FluidContainerData; import net.minecraftforge.oredict.*; import tconstruct.TConstruct; import tconstruct.achievements.TAchievements; import tconstruct.blocks.*; import tconstruct.blocks.logic.*; import tconstruct.blocks.slime.*; import tconstruct.blocks.traps.*; import tconstruct.client.StepSoundSlime; import tconstruct.entity.*; import tconstruct.entity.item.*; import tconstruct.entity.projectile.*; import tconstruct.items.*; import tconstruct.items.armor.*; import tconstruct.items.blocks.*; import tconstruct.items.tools.*; import tconstruct.library.TConstructRegistry; import tconstruct.library.client.*; import tconstruct.library.client.FluidRenderProperties.Applications; import tconstruct.library.crafting.*; import tconstruct.library.tools.ToolCore; import tconstruct.library.util.IPattern; import tconstruct.modifiers.tools.*; import tconstruct.modifiers.armor.*; import tconstruct.util.*; import tconstruct.util.config.*; public class TContent implements IFuelHandler { // Supresses console spam when iguana's tweaks remove stuff public static boolean supressMissingToolLogs = PHConstruct.forceToolLogsOff; //Patterns and other materials public static Item blankPattern; public static Item materials; public static Item toolRod; public static Item toolShard; public static Item woodPattern; public static Item metalPattern; //public static Item armorPattern; public static Item manualBook; public static Item buckets; public static Item titleIcon; public static Item strangeFood; public static Item diamondApple; public static Item jerky; //public static Item stonePattern; //public static Item netherPattern; //Tools public static ToolCore pickaxe; public static ToolCore shovel; public static ToolCore hatchet; public static ToolCore broadsword; public static ToolCore longsword; public static ToolCore rapier; public static ToolCore dagger; public static ToolCore cutlass; public static ToolCore frypan; public static ToolCore battlesign; public static ToolCore chisel; public static ToolCore mattock; public static ToolCore scythe; public static ToolCore lumberaxe; public static ToolCore cleaver; public static ToolCore excavator; public static ToolCore hammer; public static ToolCore battleaxe; public static ToolCore shortbow; public static ToolCore arrow; public static Item potionLauncher; //Tool parts public static Item binding; public static Item toughBinding; public static Item toughRod; public static Item largePlate; public static Item pickaxeHead; public static Item shovelHead; public static Item hatchetHead; public static Item frypanHead; public static Item signHead; public static Item chiselHead; public static Item scytheBlade; public static Item broadAxeHead; public static Item excavatorHead; public static Item hammerHead; public static Item swordBlade; public static Item largeSwordBlade; public static Item knifeBlade; public static Item wideGuard; public static Item handGuard; public static Item crossbar; public static Item fullGuard; public static Item bowstring; public static Item arrowhead; public static Item fletching; //Crafting blocks public static Block toolStationWood; public static Block toolStationStone; public static Block toolForge; public static Block craftingStationWood; public static Block craftingSlabWood; public static Block furnaceSlab; public static Block heldItemBlock; public static Block craftedSoil; public static Block smeltery; public static Block lavaTank; public static Block searedBlock; public static Block castingChannel; public static Block smelteryNether; public static Block lavaTankNether; public static Block searedBlockNether; public static Block metalBlock; public static Block tankAir; public static Block dryingRack; //Decoration public static Block stoneTorch; public static Block stoneLadder; public static Block multiBrick; public static Block multiBrickFancy; public static Block searedSlab; public static Block speedSlab; public static Block meatBlock; public static Block woolSlab1; public static Block woolSlab2; public static Block glueBlock; //Traps public static Block landmine; public static Block punji; public static Block barricadeOak; public static Block barricadeSpruce; public static Block barricadeBirch; public static Block barricadeJungle; public static Block slimeExplosive; //InfiBlocks public static Block speedBlock; public static Block clearGlass; //public static Block stainedGlass; public static Block stainedGlassClear; public static Block glassPane; //public static Block stainedGlassPane; public static Block stainedGlassClearPane; public static Block glassMagicSlab; public static Block stainedGlassMagicSlab; public static Block stainedGlassClearMagicSlab; //Liquids public static Material liquidMetal; public static Fluid moltenIronFluid; public static Fluid moltenGoldFluid; public static Fluid moltenCopperFluid; public static Fluid moltenTinFluid; public static Fluid moltenAluminumFluid; public static Fluid moltenCobaltFluid; public static Fluid moltenArditeFluid; public static Fluid moltenBronzeFluid; public static Fluid moltenAlubrassFluid; public static Fluid moltenManyullynFluid; public static Fluid moltenAlumiteFluid; public static Fluid moltenObsidianFluid; public static Fluid moltenSteelFluid; public static Fluid moltenGlassFluid; public static Fluid moltenStoneFluid; public static Fluid moltenEmeraldFluid; public static Fluid bloodFluid; public static Fluid moltenNickelFluid; public static Fluid moltenLeadFluid; public static Fluid moltenSilverFluid; public static Fluid moltenShinyFluid; public static Fluid moltenInvarFluid; public static Fluid moltenElectrumFluid; public static Fluid moltenEnderFluid; public static Fluid blueSlimeFluid; public static Fluid pigIronFluid; public static Block moltenIron; public static Block moltenGold; public static Block moltenCopper; public static Block moltenTin; public static Block moltenAluminum; public static Block moltenCobalt; public static Block moltenArdite; public static Block moltenBronze; public static Block moltenAlubrass; public static Block moltenManyullyn; public static Block moltenAlumite; public static Block moltenObsidian; public static Block moltenSteel; public static Block moltenGlass; public static Block moltenStone; public static Block moltenEmerald; public static Block blood; public static Block moltenNickel; public static Block moltenLead; public static Block moltenSilver; public static Block moltenShiny; public static Block moltenInvar; public static Block moltenElectrum; public static Block moltenEnder; //Slime public static StepSound slimeStep; public static Block slimePool; public static Block slimeGel; public static Block slimeGrass; public static Block slimeTallGrass; public static SlimeLeaves slimeLeaves; public static SlimeSapling slimeSapling; public static Block slimeChannel; public static Block slimePad; public static Block bloodChannel; //Glue public static Fluid glueFluid; public static Block glueFluidBlock; //Ores public static Block oreSlag; public static Block oreGravel; public static OreberryBush oreBerry; public static OreberryBush oreBerrySecond; public static Item oreBerries; //Tool modifiers public static ModFlux modFlux; public static ModLapis modLapis; public static ModAttack modAttack; //Wearables public static Item glove; public static Item knapsack; public static Item heartCanister; public static Item goldHead; //Rail-related public static Block woodenRail; //Chest hooks public static ChestGenHooks tinkerHouseChest; public static ChestGenHooks tinkerHousePatterns; //Armor - basic public static Item helmetWood; public static Item chestplateWood; public static Item leggingsWood; public static Item bootsWood; public static EnumArmorMaterial materialWood; //Armor - exosuit public static Item exoGoggles; public static Item exoChest; public static Item exoPants; public static Item exoShoes; //Temporary items //public static Item armorTest = new ArmorStandard(2445, 4, EnumArmorPart.HELMET).setCreativeTab(CreativeTabs.tabAllSearch); public TContent() { registerItems(); registerBlocks(); registerMaterials(); addCraftingRecipes(); setupToolTabs(); addLoot(); if (PHConstruct.achievementsEnabled) { addAchievements(); } } public void createEntities () { EntityRegistry.registerModEntity(FancyEntityItem.class, "Fancy Item", 0, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(DaggerEntity.class, "Dagger", 1, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(Crystal.class, "Crystal", 2, TConstruct.instance, 32, 3, true); EntityRegistry.registerModEntity(LaunchedPotion.class, "Launched Potion", 3, TConstruct.instance, 32, 3, true); EntityRegistry.registerModEntity(ArrowEntity.class, "Arrow", 4, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(EntityLandmineFirework.class, "LandmineFirework", 5, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(ExplosivePrimed.class, "SlimeExplosive", 6, TConstruct.instance, 32, 5, true); //EntityRegistry.registerModEntity(CartEntity.class, "Small Wagon", 1, TConstruct.instance, 32, 5, true); EntityRegistry.registerModEntity(BlueSlime.class, "EdibleSlime", 12, TConstruct.instance, 64, 5, true); //EntityRegistry.registerModEntity(MetalSlime.class, "MetalSlime", 13, TConstruct.instance, 64, 5, true); } public static Fluid[] fluids = new Fluid[27]; public static Block[] fluidBlocks = new Block[26]; void registerBlocks () { //Tool Station toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation"); GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock"); GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation"); GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter"); GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder"); GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper"); toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge"); GameRegistry.registerBlock(toolForge, MetadataItemBlock.class, "ToolForgeBlock"); GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge"); craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation"); GameRegistry.registerBlock(craftingStationWood, "CraftingStation"); GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation"); craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab"); GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab"); furnaceSlab = new FurnaceSlab(PHConstruct.furnaceSlab, Material.rock).setUnlocalizedName("FurnaceSlab"); GameRegistry.registerBlock(furnaceSlab, "FurnaceSlab"); GameRegistry.registerTileEntity(FurnaceLogic.class, "TConstruct.Furnace"); heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan"); GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock"); GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic"); craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil"); craftedSoil.stepSound = Block.soundGravelFootstep; GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil"); searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab"); searedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab"); speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab"); speedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab"); metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock"); metalBlock.stepSound = Block.soundMetalFootstep; GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock"); meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock"); GameRegistry.registerBlock(meatBlock, HamboneItemBlock.class, "MeatBlock"); OreDictionary.registerOre("hambone", new ItemStack(meatBlock)); LanguageRegistry.addName(meatBlock, "Hambone"); GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw)); glueBlock = new GlueBlock(PHConstruct.glueBlock).setUnlocalizedName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab); GameRegistry.registerBlock(glueBlock, "GlueBlock"); OreDictionary.registerOre("blockRubber", new ItemStack(glueBlock)); woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth"); woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1"); woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth"); woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2"); //Smeltery smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery"); smelteryNether = new SmelteryBlock(PHConstruct.smelteryNether, "nether").setUnlocalizedName("Smeltery"); GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery"); GameRegistry.registerBlock(smelteryNether, SmelteryItemBlock.class, "SmelteryNether"); if (PHConstruct.newSmeltery) { GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain"); } else { GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain"); } GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants"); lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("LavaTank"); lavaTankNether = new LavaTankBlock(PHConstruct.lavaTankNether, "nether").setStepSound(Block.soundGlassFootstep).setUnlocalizedName("LavaTank"); GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank"); GameRegistry.registerBlock(lavaTankNether, LavaTankItemBlock.class, "LavaTankNether"); GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank"); searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock"); searedBlockNether = new SearedBlock(PHConstruct.searedTableNether, "nether").setUnlocalizedName("SearedBlock"); GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock"); GameRegistry.registerBlock(searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether"); GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable"); GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet"); GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin"); castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel"); GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel"); GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel"); tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air"); GameRegistry.registerBlock(tankAir, "TankAir"); GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air"); //Traps landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone) .setUnlocalizedName("landmine"); GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine"); GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine"); punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji"); GameRegistry.registerBlock(punji, "trap.punji"); barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak"); GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak"); barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce"); GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce"); barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch"); GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch"); barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle"); GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle"); slimeExplosive = new SlimeExplosive(PHConstruct.slimeExplosive).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("explosive.slime"); GameRegistry.registerBlock(slimeExplosive, MetadataItemBlock.class, "explosive.slime"); dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack"); GameRegistry.registerBlock(dryingRack, "Armor.DryingRack"); GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack"); //Liquids liquidMetal = new MaterialLiquid(MapColor.tntColor); moltenIronFluid = new Fluid("iron.molten"); if (!FluidRegistry.registerFluid(moltenIronFluid)) moltenIronFluid = FluidRegistry.getFluid("iron.molten"); moltenIron = new TConstructFluid(PHConstruct.moltenIron, moltenIronFluid, Material.lava, "liquid_iron").setUnlocalizedName("metal.molten.iron"); GameRegistry.registerBlock(moltenIron, "metal.molten.iron"); fluids[0] = moltenIronFluid; fluidBlocks[0] = moltenIron; moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty))); moltenGoldFluid = new Fluid("gold.molten"); if (!FluidRegistry.registerFluid(moltenGoldFluid)) moltenGoldFluid = FluidRegistry.getFluid("gold.molten"); moltenGold = new TConstructFluid(PHConstruct.moltenGold, moltenGoldFluid, Material.lava, "liquid_gold").setUnlocalizedName("metal.molten.gold"); GameRegistry.registerBlock(moltenGold, "metal.molten.gold"); fluids[1] = moltenGoldFluid; fluidBlocks[1] = moltenGold; moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty))); moltenCopperFluid = new Fluid("copper.molten"); if (!FluidRegistry.registerFluid(moltenCopperFluid)) moltenCopperFluid = FluidRegistry.getFluid("copper.molten"); moltenCopper = new TConstructFluid(PHConstruct.moltenCopper, moltenCopperFluid, Material.lava, "liquid_copper").setUnlocalizedName("metal.molten.copper"); GameRegistry.registerBlock(moltenCopper, "metal.molten.copper"); fluids[2] = moltenCopperFluid; fluidBlocks[2] = moltenCopper; moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty))); moltenTinFluid = new Fluid("tin.molten"); if (!FluidRegistry.registerFluid(moltenTinFluid)) moltenTinFluid = FluidRegistry.getFluid("tin.molten"); moltenTin = new TConstructFluid(PHConstruct.moltenTin, moltenTinFluid, Material.lava, "liquid_tin").setUnlocalizedName("metal.molten.tin"); GameRegistry.registerBlock(moltenTin, "metal.molten.tin"); fluids[3] = moltenTinFluid; fluidBlocks[3] = moltenTin; moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty))); moltenAluminumFluid = new Fluid("aluminum.molten"); if (!FluidRegistry.registerFluid(moltenAluminumFluid)) moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten"); moltenAluminum = new TConstructFluid(PHConstruct.moltenAluminum, moltenAluminumFluid, Material.lava, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum"); GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum"); fluids[4] = moltenAluminumFluid; fluidBlocks[4] = moltenAluminum; moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty))); moltenCobaltFluid = new Fluid("cobalt.molten"); if (!FluidRegistry.registerFluid(moltenCobaltFluid)) moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten"); moltenCobalt = new TConstructFluid(PHConstruct.moltenCobalt, moltenCobaltFluid, Material.lava, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt"); GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt"); fluids[5] = moltenCobaltFluid; fluidBlocks[5] = moltenCobalt; moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty))); moltenArditeFluid = new Fluid("ardite.molten"); if (!FluidRegistry.registerFluid(moltenArditeFluid)) moltenArditeFluid = FluidRegistry.getFluid("ardite.molten"); moltenArdite = new TConstructFluid(PHConstruct.moltenArdite, moltenArditeFluid, Material.lava, "liquid_ardite").setUnlocalizedName("metal.molten.ardite"); GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite"); fluids[6] = moltenArditeFluid; fluidBlocks[6] = moltenArdite; moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty))); moltenBronzeFluid = new Fluid("bronze.molten"); if (!FluidRegistry.registerFluid(moltenBronzeFluid)) moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten"); moltenBronze = new TConstructFluid(PHConstruct.moltenBronze, moltenBronzeFluid, Material.lava, "liquid_bronze").setUnlocalizedName("metal.molten.bronze"); GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze"); fluids[7] = moltenBronzeFluid; fluidBlocks[7] = moltenBronze; moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty))); moltenAlubrassFluid = new Fluid("aluminumbrass.molten"); if (!FluidRegistry.registerFluid(moltenAlubrassFluid)) moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten"); moltenAlubrass = new TConstructFluid(PHConstruct.moltenAlubrass, moltenAlubrassFluid, Material.lava, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass"); GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass"); fluids[8] = moltenAlubrassFluid; fluidBlocks[8] = moltenAlubrass; moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty))); moltenManyullynFluid = new Fluid("manyullyn.molten"); if (!FluidRegistry.registerFluid(moltenManyullynFluid)) moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten"); moltenManyullyn = new TConstructFluid(PHConstruct.moltenManyullyn, moltenManyullynFluid, Material.lava, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn"); GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn"); fluids[9] = moltenManyullynFluid; fluidBlocks[9] = moltenManyullyn; moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty))); moltenAlumiteFluid = new Fluid("alumite.molten"); if (!FluidRegistry.registerFluid(moltenAlumiteFluid)) moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten"); moltenAlumite = new TConstructFluid(PHConstruct.moltenAlumite, moltenAlumiteFluid, Material.lava, "liquid_alumite").setUnlocalizedName("metal.molten.alumite"); GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite"); fluids[10] = moltenAlumiteFluid; fluidBlocks[10] = moltenAlumite; moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty))); moltenObsidianFluid = new Fluid("obsidian.molten"); if (!FluidRegistry.registerFluid(moltenObsidianFluid)) moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten"); moltenObsidian = new TConstructFluid(PHConstruct.moltenObsidian, moltenObsidianFluid, Material.lava, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian"); GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian"); fluids[11] = moltenObsidianFluid; fluidBlocks[11] = moltenObsidian; moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty))); moltenSteelFluid = new Fluid("steel.molten"); if (!FluidRegistry.registerFluid(moltenSteelFluid)) moltenSteelFluid = FluidRegistry.getFluid("steel.molten"); moltenSteel = new TConstructFluid(PHConstruct.moltenSteel, moltenSteelFluid, Material.lava, "liquid_steel").setUnlocalizedName("metal.molten.steel"); GameRegistry.registerBlock(moltenSteel, "metal.molten.steel"); fluids[12] = moltenSteelFluid; fluidBlocks[12] = moltenSteel; moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty))); moltenGlassFluid = new Fluid("glass.molten"); if (!FluidRegistry.registerFluid(moltenGlassFluid)) moltenGlassFluid = FluidRegistry.getFluid("glass.molten"); moltenGlass = new TConstructFluid(PHConstruct.moltenGlass, moltenGlassFluid, Material.lava, "liquid_glass", true).setUnlocalizedName("metal.molten.glass"); GameRegistry.registerBlock(moltenGlass, "metal.molten.glass"); fluids[13] = moltenGlassFluid; fluidBlocks[13] = moltenGlass; moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty))); moltenStoneFluid = new Fluid("stone.seared"); if (!FluidRegistry.registerFluid(moltenStoneFluid)) moltenStoneFluid = FluidRegistry.getFluid("stone.seared"); moltenStone = new TConstructFluid(PHConstruct.moltenStone, moltenStoneFluid, Material.lava, "liquid_stone").setUnlocalizedName("molten.stone"); GameRegistry.registerBlock(moltenStone, "molten.stone"); fluids[14] = moltenStoneFluid; fluidBlocks[14] = moltenStone; moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty))); moltenEmeraldFluid = new Fluid("emerald.liquid"); if (!FluidRegistry.registerFluid(moltenEmeraldFluid)) moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid"); moltenEmerald = new TConstructFluid(PHConstruct.moltenEmerald, moltenEmeraldFluid, Material.water, "liquid_villager").setUnlocalizedName("molten.emerald"); GameRegistry.registerBlock(moltenEmerald, "molten.emerald"); fluids[15] = moltenEmeraldFluid; fluidBlocks[15] = moltenEmerald; moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty))); bloodFluid = new Fluid("blood"); if (!FluidRegistry.registerFluid(bloodFluid)) bloodFluid = FluidRegistry.getFluid("blood"); blood = new BloodBlock(PHConstruct.blood, bloodFluid, Material.water, "liquid_cow").setUnlocalizedName("liquid.blood"); GameRegistry.registerBlock(blood, "liquid.blood"); fluids[16] = bloodFluid; fluidBlocks[16] = blood; bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty))); moltenNickelFluid = new Fluid("nickel.molten"); if (!FluidRegistry.registerFluid(moltenNickelFluid)) moltenNickelFluid = FluidRegistry.getFluid("nickel.molten"); moltenNickel = new TConstructFluid(PHConstruct.moltenNickel, moltenNickelFluid, Material.lava, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel"); GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel"); fluids[17] = moltenNickelFluid; fluidBlocks[17] = moltenNickel; moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty))); moltenLeadFluid = new Fluid("lead.molten"); if (!FluidRegistry.registerFluid(moltenLeadFluid)) moltenLeadFluid = FluidRegistry.getFluid("lead.molten"); moltenLead = new TConstructFluid(PHConstruct.moltenLead, moltenLeadFluid, Material.lava, "liquid_lead").setUnlocalizedName("metal.molten.lead"); GameRegistry.registerBlock(moltenLead, "metal.molten.lead"); fluids[18] = moltenLeadFluid; fluidBlocks[18] = moltenLead; moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty))); moltenSilverFluid = new Fluid("silver.molten"); if (!FluidRegistry.registerFluid(moltenSilverFluid)) moltenSilverFluid = FluidRegistry.getFluid("silver.molten"); moltenSilver = new TConstructFluid(PHConstruct.moltenSilver, moltenSilverFluid, Material.lava, "liquid_silver").setUnlocalizedName("metal.molten.silver"); GameRegistry.registerBlock(moltenSilver, "metal.molten.silver"); fluids[19] = moltenSilverFluid; fluidBlocks[19] = moltenSilver; moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty))); moltenShinyFluid = new Fluid("platinum.molten"); if (!FluidRegistry.registerFluid(moltenShinyFluid)) moltenShinyFluid = FluidRegistry.getFluid("platinum.molten"); moltenShiny = new TConstructFluid(PHConstruct.moltenShiny, moltenShinyFluid, Material.lava, "liquid_shiny").setUnlocalizedName("metal.molten.shiny"); GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny"); fluids[20] = moltenShinyFluid; fluidBlocks[20] = moltenShiny; moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty))); moltenInvarFluid = new Fluid("invar.molten"); if (!FluidRegistry.registerFluid(moltenInvarFluid)) moltenInvarFluid = FluidRegistry.getFluid("invar.molten"); moltenInvar = new TConstructFluid(PHConstruct.moltenInvar, moltenInvarFluid, Material.lava, "liquid_invar").setUnlocalizedName("metal.molten.invar"); GameRegistry.registerBlock(moltenInvar, "metal.molten.invar"); fluids[21] = moltenInvarFluid; fluidBlocks[21] = moltenInvar; moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty))); moltenElectrumFluid = new Fluid("electrum.molten"); if (!FluidRegistry.registerFluid(moltenElectrumFluid)) moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten"); moltenElectrum = new TConstructFluid(PHConstruct.moltenElectrum, moltenElectrumFluid, Material.lava, "liquid_electrum").setUnlocalizedName("metal.molten.electrum"); GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum"); fluids[22] = moltenElectrumFluid; fluidBlocks[22] = moltenElectrum; moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty))); moltenEnderFluid = new Fluid("ender"); if (!FluidRegistry.registerFluid(moltenEnderFluid)) { moltenEnderFluid = FluidRegistry.getFluid("ender"); moltenEnder = Block.blocksList[moltenEnderFluid.getBlockID()]; if (moltenEnder == null) TConstruct.logger.info("Molten ender block missing!"); } else { moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender"); GameRegistry.registerBlock(moltenEnder, "fluid.ender"); moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty))); } fluids[23] = moltenEnderFluid; fluidBlocks[23] = moltenEnder; //Slime slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f); blueSlimeFluid = new Fluid("slime.blue"); if (!FluidRegistry.registerFluid(blueSlimeFluid)) blueSlimeFluid = FluidRegistry.getFluid("slime.blue"); slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime"); GameRegistry.registerBlock(slimePool, "liquid.slime"); fluids[24] = blueSlimeFluid; fluidBlocks[24] = slimePool; blueSlimeFluid.setBlockID(slimePool); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty))); //Glue glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200); if (!FluidRegistry.registerFluid(glueFluid)) glueFluid = FluidRegistry.getFluid("glue"); glueFluidBlock = new GlueFluid(PHConstruct.glueFluidBlock, glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.glue"); GameRegistry.registerBlock(glueFluidBlock, "liquid.glue"); fluids[25] = glueFluid; fluidBlocks[25] = glueFluidBlock; glueFluid.setBlockID(glueFluidBlock); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(glueFluid, 1000), new ItemStack(buckets, 1, 26), new ItemStack(Item.bucketEmpty))); pigIronFluid = new Fluid("pigiron.molten"); if (!FluidRegistry.registerFluid(pigIronFluid)) pigIronFluid = FluidRegistry.getFluid("pigiron.molten"); else pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300); fluids[26] = pigIronFluid; slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel"); GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel"); slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass"); GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass"); slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall"); GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall"); slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves"); GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves"); slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling"); GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling"); slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water, "greencurrent").setHardness(0.3f).setStepSound(slimeStep).setUnlocalizedName("slime.channel"); GameRegistry.registerBlock(slimeChannel, "slime.channel"); TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1; bloodChannel = new ConveyorBase(PHConstruct.bloodChannel, Material.water, "liquid_cow").setHardness(0.3f).setStepSound(slimeStep).setUnlocalizedName("blood.channel"); GameRegistry.registerBlock(bloodChannel, "blood.channel"); TConstructRegistry.drawbridgeState[bloodChannel.blockID] = 1; slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setHardness(0.3f).setUnlocalizedName("slime.pad"); GameRegistry.registerBlock(slimePad, "slime.pad"); TConstructRegistry.drawbridgeState[slimePad.blockID] = 1; //Decoration stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch"); GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch"); stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder"); GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder"); multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick"); GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick"); multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy"); GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy"); //Ores String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" }; oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one"); GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one"); String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" }; oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two"); GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two"); String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" }; oreSlag = new MetalOre(PHConstruct.oreSlag, Material.rock, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore"); GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick"); MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1); oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore"); GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre"); MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2); MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4); speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock"); GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock"); //Glass clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock"); clearGlass.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock"); glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false); GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane"); stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear"); stainedGlassClear.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear"); stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane); GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained"); //Rail woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood"); GameRegistry.registerBlock(woodenRail, "rail.wood"); } void registerItems () { titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon"); GameRegistry.registerItem(titleIcon, "titleIcon"); String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" }; blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern"); GameRegistry.registerItem(blankPattern, "blankPattern"); materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials"); toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod"); toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard"); woodPattern = new Pattern(PHConstruct.woodPattern, "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern"); metalPattern = new MetalPattern(PHConstruct.metalPattern, "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern"); //armorPattern = new ArmorPattern(PHConstruct.armorPattern, "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern"); GameRegistry.registerItem(materials, "materials"); GameRegistry.registerItem(woodPattern, "woodPattern"); GameRegistry.registerItem(metalPattern, "metalPattern"); //GameRegistry.registerItem(armorPattern, "armorPattern"); TConstructRegistry.addItemToDirectory("blankPattern", blankPattern); TConstructRegistry.addItemToDirectory("woodPattern", woodPattern); TConstructRegistry.addItemToDirectory("metalPattern", metalPattern); //TConstructRegistry.addItemToDirectory("armorPattern", armorPattern); String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" }; for (int i = 1; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i)); } for (int i = 0; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i)); } /*String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" }; for (int i = 1; i < armorPartTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i)); }*/ manualBook = new Manual(PHConstruct.manual); GameRegistry.registerItem(manualBook, "manualBook"); buckets = new FilledBucket(PHConstruct.buckets); GameRegistry.registerItem(buckets, "buckets"); pickaxe = new Pickaxe(PHConstruct.pickaxe); shovel = new Shovel(PHConstruct.shovel); hatchet = new Hatchet(PHConstruct.axe); broadsword = new Broadsword(PHConstruct.broadsword); longsword = new Longsword(PHConstruct.longsword); rapier = new Rapier(PHConstruct.rapier); dagger = new Dagger(PHConstruct.dagger); cutlass = new Cutlass(PHConstruct.cutlass); frypan = new FryingPan(PHConstruct.frypan); battlesign = new BattleSign(PHConstruct.battlesign); mattock = new Mattock(PHConstruct.mattock); chisel = new Chisel(PHConstruct.chisel); lumberaxe = new LumberAxe(PHConstruct.lumberaxe); cleaver = new Cleaver(PHConstruct.cleaver); scythe = new Scythe(PHConstruct.scythe); excavator = new Excavator(PHConstruct.excavator); hammer = new Hammer(PHConstruct.hammer); battleaxe = new Battleaxe(PHConstruct.battleaxe); shortbow = new Shortbow(PHConstruct.shortbow); arrow = new Arrow(PHConstruct.arrow); Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, dagger, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe, shortbow, arrow }; String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" }; for (int i = 0; i < tools.length; i++) { GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]); } potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher"); GameRegistry.registerItem(potionLauncher, "potionLauncher"); pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead"); shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead"); hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead"); binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding"); toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding"); toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod"); largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate"); swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade"); wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard"); handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard"); crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar"); knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade"); fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard"); frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead"); signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead"); chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead"); scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade"); broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead"); excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead"); largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade"); hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead"); bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring"); arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead"); fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching"); Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard, frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead }; String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard", "crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring", "fletching", "arrowhead" }; for (int i = 0; i < toolParts.length; i++) { GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7 compat TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]); } diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond"); strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood"); oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry"); GameRegistry.registerItem(diamondApple, "diamondApple"); GameRegistry.registerItem(strangeFood, "strangeFood"); GameRegistry.registerItem(oreBerries, "oreBerries"); jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky"); GameRegistry.registerItem(jerky, "jerky"); //Wearables heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister"); knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage"); goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead"); GameRegistry.registerItem(heartCanister, "heartCanister"); GameRegistry.registerItem(knapsack, "knapsack"); GameRegistry.registerItem(goldHead, "goldHead"); LiquidCasting basinCasting = TConstruct.getBasinCasting(); materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3); helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood"); chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood"); leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood"); bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood"); GameRegistry.registerItem(helmetWood, "helmetWood"); GameRegistry.registerItem(chestplateWood, "chestplateWood"); GameRegistry.registerItem(leggingsWood, "leggingsWood"); GameRegistry.registerItem(bootsWood, "bootsWood"); exoGoggles = new ExoArmor(PHConstruct.exoGoggles, EnumArmorPart.HELMET, "exosuit").setUnlocalizedName("tconstruct.exoGoggles"); exoChest = new ExoArmor(PHConstruct.exoChest, EnumArmorPart.CHEST, "exosuit").setUnlocalizedName("tconstruct.exoChest"); exoPants = new ExoArmor(PHConstruct.exoPants, EnumArmorPart.PANTS, "exosuit").setUnlocalizedName("tconstruct.exoPants"); exoShoes = new ExoArmor(PHConstruct.exoShoes, EnumArmorPart.SHOES, "exosuit").setUnlocalizedName("tconstruct.exoShoes"); String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper", "ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper", "nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze", "nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" }; for (int i = 0; i < materialStrings.length; i++) { TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i)); } String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" }; for (int i = 0; i < oreberries.length; i++) { TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i)); } TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0)); TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0)); TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0)); TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1)); TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2)); //Vanilla stack sizes Item.doorWood.setMaxStackSize(16); Item.doorIron.setMaxStackSize(16); Item.snowball.setMaxStackSize(64); Item.boat.setMaxStackSize(16); Item.minecartEmpty.setMaxStackSize(3); Item.minecartCrate.setMaxStackSize(3); Item.minecartPowered.setMaxStackSize(3); Item.itemsList[Block.cake.blockID].setMaxStackSize(16); //Block.torchWood.setTickRandomly(false); } void registerMaterials () { TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound"); TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", ""); TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", ""); TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged"); TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", ""); TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable"); TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", ""); TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", ""); TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", ""); TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", ""); TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", ""); TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", ""); TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", "Tasty"); TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); //Slime //Material ID, mass, fragility TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime TConstructRegistry.addArrowMaterial(18, 6.8F, 0.5F, 100F); //Iron TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather for (int i = 0; i < 4; i++) TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime PatternBuilder pb = PatternBuilder.instance; if (PHConstruct.enableTWood) pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0); else pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0); if (PHConstruct.enableTStone) { pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1); pb.registerMaterial(Block.cobblestone, 2, "Stone"); } else pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0); pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2); if (PHConstruct.enableTFlint) pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); else pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); if (PHConstruct.enableTCactus) pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); else pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); if (PHConstruct.enableTBone) pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); else pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6); pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian"); if (PHConstruct.enableTNetherrack) pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); else pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); if (PHConstruct.enableTSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8); else pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8); if (PHConstruct.enableTPaper) pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9); else pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9); pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10); pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11); pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12); pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13); pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14); pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15); pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16); if (PHConstruct.enableTBlueSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17); else pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17); pb.registerFullMaterial(new ItemStack(materials, 1, 34), 2, "PigIron", new ItemStack(toolShard, 1, 18), new ItemStack(toolRod, 1, 18), 18); pb.addToolPattern((IPattern) woodPattern); } public static Item[] patternOutputs; public static FluidStack[] liquids; void addCraftingRecipes () { addPartMapping(); addRecipesForToolBuilder(); addRecipesForTableCasting(); addRecipesForBasinCasting(); addRecipesForSmeltery(); addRecipesForChisel(); addRecipesForFurnace(); addRecipesForCraftingTable(); addRecipesForDryingRack(); } private void addRecipesForCraftingTable () { String[] patBlock = { "###", "###", "###" }; String[] patSurround = { "###", "#m#", "###" }; Object[] toolForgeBlocks = { "blockIron", "blockGold", Block.blockDiamond, Block.blockEmerald, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin", "blockAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" }; // ToolForge Recipes (Metal Version) for (int sc = 0; sc < toolForgeBlocks.length; sc++) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', toolForgeBlocks[sc])); // adding slab version recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(craftingSlabWood, 1, 1), 'm', toolForgeBlocks[sc])); } // ToolStation Recipes (Wooden Version) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "craftingTableWood")); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingSlabWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood")); if (PHConstruct.stencilTableCrafting) { GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood")); } GameRegistry.addRecipe(new ItemStack(furnaceSlab, 1, 0), "###", "# #", "###", '#', new ItemStack(Block.stoneSingleSlab, 1, 3)); // Blank Pattern Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood")); // Manual Book Recipes GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 3), new ItemStack(manualBook, 1, 2)); // alternative Vanilla Book Recipe GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.nameTag), "P~ ", "~O ", " ~", '~', Item.silk, 'P', Item.paper, 'O', "slimeball")); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt)); // Paperstack Recipe GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper); // Mossball Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), patBlock, '#', "stoneMossy")); // LavaCrystal Recipes -Auto-smelt GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod); GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod); // Slimy sand Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt); // Grout Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 8, 1), new ItemStack(Block.blockClay, 1, Short.MAX_VALUE), Block.sand, Block.sand, Block.sand, Block.sand, Block.gravel, Block.gravel, Block.gravel, Block.gravel); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 6), Item.netherStalkSeeds, Block.slowSand, Block.gravel); // Graveyard Soil Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15)); // Silky Cloth Recipes GameRegistry.addRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', new ItemStack(materials, 1, 24), '#', new ItemStack(Item.silk)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Item.silk))); // Silky Jewel Recipes GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald)); // Armor Recipes Object[] helm = new String[] { "www", "w w" }; Object[] chest = new String[] { "w w", "www", "www" }; Object[] pants = new String[] { "www", "w w", "w w" }; Object[] shoes = new String[] { "w w", "w w" }; GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, helm, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, chest, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, pants, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, shoes, 'w', "logWood")); ItemStack exoGoggleStack = new ItemStack(exoGoggles); ItemStack exoChestStack = new ItemStack(exoChest); ItemStack exoPantsStack = new ItemStack(exoPants); ItemStack exoShoesStack = new ItemStack(exoShoes); ToolBuilder.instance.addArmorTag(exoGoggleStack); ToolBuilder.instance.addArmorTag(exoChestStack); ToolBuilder.instance.addArmorTag(exoPantsStack); ToolBuilder.instance.addArmorTag(exoShoesStack); GameRegistry.addShapedRecipe(exoGoggleStack, helm, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoChestStack, chest, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoPantsStack, pants, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoShoesStack, shoes, 'w', new ItemStack(largePlate, 1, 14)); // Metal conversion Recipes GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 3), patBlock, '#', new ItemStack(materials, 1, 9)); // Copper GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 5), patBlock, '#', new ItemStack(materials, 1, 10)); // Tin GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 6), patBlock, '#', new ItemStack(materials, 1, 11)); // Aluminum //GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 6), patBlock, '#', new ItemStack(materials, 1, 12)); // Aluminum GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 4), patBlock, '#', new ItemStack(materials, 1, 13)); // Bronze GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 7), patBlock, '#', new ItemStack(materials, 1, 14)); // AluBrass GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 0), patBlock, '#', new ItemStack(materials, 1, 3)); // Cobalt GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 1), patBlock, '#', new ItemStack(materials, 1, 4)); // Ardite GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 2), patBlock, '#', new ItemStack(materials, 1, 5)); // Manyullyn GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 8), patBlock, '#', new ItemStack(materials, 1, 15)); // Alumite GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 9), patBlock, '#', new ItemStack(materials, 1, 16)); // Steel - GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 11), patBlock, '#', new ItemStack(materials, 1, 12)); //Aluminum raw -> ingot + GameRegistry.addRecipe(new ItemStack(materials, 1, 11), patBlock, '#', new ItemStack(materials, 1, 12)); //Aluminum raw -> ingot GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 11), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel GameRegistry.addRecipe(new ItemStack(Item.ingotIron), patBlock, '#', new ItemStack(materials, 1, 19)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 1, 9), patBlock, '#', new ItemStack(materials, 1, 20)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 1, 10), patBlock, '#', new ItemStack(materials, 1, 21)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 1, 11), patBlock, '#', new ItemStack(materials, 1, 22)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 1, 14), patBlock, '#', new ItemStack(materials, 1, 24)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 1, 18), patBlock, '#', new ItemStack(materials, 1, 27)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 1, 3), patBlock, '#', new ItemStack(materials, 1, 28)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 1, 4), patBlock, '#', new ItemStack(materials, 1, 29)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 1, 5), patBlock, '#', new ItemStack(materials, 1, 30)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 1, 13), patBlock, '#', new ItemStack(materials, 1, 31)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 1, 15), patBlock, '#', new ItemStack(materials, 1, 32)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 1, 16), patBlock, '#', new ItemStack(materials, 1, 33)); //Steel GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 11)); //Aluminum //GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel // stained Glass Recipes String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; String color = ""; for (int i = 0; i < 16; i++) { color = dyeTypes[15 - i]; GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), patSurround, 'm', color, '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', clearGlass)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, clearGlass)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', glassPane)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, glassPane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); } // Glass Recipes GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass }); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', "glass", 'Q', Item.netherQuartz, 'W', "slabWood" })); GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian }); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glassPane, 16, 0), "GGG", "GGG", 'G', clearGlass)); // Smeltery Components Recipes ItemStack searedBrick = new ItemStack(materials, 1, 2); GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel searedBrick = new ItemStack(materials, 1, 37); GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel // Jack o'Latern Recipe - Stone Torch GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 's', new ItemStack(stoneTorch)); // Stone Torch Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod")); // Stone Ladder Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod")); // Wooden Rail Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood")); // Stonesticks Recipes GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone)); GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone)); // ItemStack aluBrass = new ItemStack(materials, 1, 14); // Clock Recipe - Vanilla alternativ GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone)); // Gold Pressure Plate - Vanilla alternativ GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass); //Accessories GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotAluminium")); //GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), " # ", "#B#", " # ", '#', "ingotTin", 'B', Item.bone)); GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed)); GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), new ItemStack(materials, 1, 8), new ItemStack(heartCanister, 1, 0), new ItemStack( heartCanister, 1, 1)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', "ingotGold")); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', aluBrass); // Drying Rack Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood")); //Landmine Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); //Ultra hardcore recipes GameRegistry.addRecipe(new ItemStack(goldHead), patSurround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3)); // Slab Smeltery Components Recipes for (int i = 0; i < 7; i++) { GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i)); } GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11)); // Wool Slab Recipes for (int sc = 0; sc <= 7; sc++) { GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc)); GameRegistry.addRecipe(new ItemStack(woolSlab2, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc + 8)); GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc), new ItemStack(woolSlab1, 1, sc), new ItemStack(woolSlab1, 1, sc)); GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc + 8), new ItemStack(woolSlab2, 1, sc), new ItemStack(woolSlab2, 1, sc)); } GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.cloth, 1, 0), "slabCloth", "slabCloth")); //Trap Recipes GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed)); GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood")); // Advanced WorkBench Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "craftingTableWood")); //Slab crafters GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "craftingTableWood")); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 0), "b", 'b', new ItemStack(craftingStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); // EssenceExtractor Recipe //Slime Recipes GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood); GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0)); GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall); GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1)); //slimeExplosive GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 0), Item.slimeBall, Block.tnt); GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 2), strangeFood, Block.tnt); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt)); GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone)); GameRegistry.addShapelessRecipe(new ItemStack(bloodChannel, 1, 0), new ItemStack(strangeFood, 1, 1), new ItemStack(strangeFood, 1, 1), new ItemStack(strangeFood, 1, 1), new ItemStack( strangeFood, 1, 1), new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeChannel, 1, 0), "slimeball", "slimeball", "slimeball", "slimeball", new ItemStack(Item.redstone))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, "slimeball")); } private void addRecipesForFurnace () { FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 6, new ItemStack(materials, 1, 37), 2f); //Nether seared brick //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 11), 0.5f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f); //FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 11), 0.2f); FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f); } private void addPartMapping () { /* Tools */ patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead, null }; int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 }; if (PHConstruct.craftMetalTools) { for (int mat = 0; mat < 18; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat)); } } } else { for (int mat = 0; mat < nonMetals.length; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat])); } } } } private void addRecipesForToolBuilder () { ToolBuilder tb = ToolBuilder.instance; tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding); tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard); tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod); tb.addNormalToolRecipe(shovel, shovelHead, toolRod); tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard); tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar); tb.addNormalToolRecipe(frypan, frypanHead, toolRod); tb.addNormalToolRecipe(battlesign, signHead, toolRod); tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead); tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar); tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard); tb.addNormalToolRecipe(chisel, chiselHead, toolRod); tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod); tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod); tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate); tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding); //tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod); BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow); tb.addCustomToolRecipe(recipe); tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching); ItemStack diamond = new ItemStack(Item.diamond); tb.registerToolMod(new ModRepair()); tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b")); tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72")); modFlux = new ModFlux(); tb.registerToolMod(modFlux); ItemStack redstoneItem = new ItemStack(Item.redstone); ItemStack redstoneBlock = new ItemStack(Block.blockRedstone); tb.registerToolMod(new ModRedstone(2, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 })); ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4); ItemStack lapisBlock = new ItemStack(Block.blockLapis); this.modLapis = new ModLapis(10, new ItemStack[] { lapisItem, lapisBlock }, new int[] { 1, 9 }); tb.registerToolMod(this.modLapis); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(this.materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair")); ItemStack blazePowder = new ItemStack(Item.blazePowder); tb.registerToolMod(new ModBlaze(7, new ItemStack[] { blazePowder }, new int[] { 1 })); tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(this.materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt")); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(this.materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal")); this.modAttack = new ModAttack("Quartz", 11, new ItemStack[] { new ItemStack(Item.netherQuartz), new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE) }, new int[] { 1, 4 }); tb.registerToolMod(this.modAttack); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Block.blockDiamond), new ItemStack(Item.appleGold, 1, 1) }, "Tier1.5Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free")); ItemStack silkyJewel = new ItemStack(this.materials, 1, 26); tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12)); ItemStack piston = new ItemStack(Block.pistonBase); tb.registerToolMod(new ModPiston(3, new ItemStack[] { piston }, new int[] { 1 })); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading")); ItemStack holySoil = new ItemStack(this.craftedSoil, 1, 4); tb.registerToolMod(new ModSmite("Smite", 14, new ItemStack[] { holySoil }, new int[] { 1 })); ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye); tb.registerToolMod(new ModAntiSpider("Anti-Spider", 15, new ItemStack[] { spidereyeball }, new int[] { 1 })); ItemStack obsidianPlate = new ItemStack(this.largePlate, 1, 6); tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1)); EnumSet<EnumArmorPart> allArmors = EnumSet.of(EnumArmorPart.HELMET, EnumArmorPart.CHEST, EnumArmorPart.PANTS, EnumArmorPart.SHOES); EnumSet<EnumArmorPart> chest = EnumSet.of(EnumArmorPart.CHEST); tb.registerArmorMod(new AModMoveSpeed(0, allArmors, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 }, false)); tb.registerArmorMod(new AModKnockbackResistance(1, allArmors, new ItemStack[] { new ItemStack(Item.ingotGold), new ItemStack(Block.blockGold) }, new int[] { 1, 9 }, false)); tb.registerArmorMod(new AModHealthBoost(2, allArmors, new ItemStack[] { new ItemStack(heartCanister, 1, 2) }, new int[] { 2 }, true)); tb.registerArmorMod(new AModDamageBoost(3, allArmors, new ItemStack[] { new ItemStack(Item.diamond), new ItemStack(Block.blockDiamond) }, new int[] { 1, 9 }, false, 3, 0.05)); tb.registerArmorMod(new AModDamageBoost(4, chest, new ItemStack[] { new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE) }, new int[] { 1 }, true, 5, 1)); tb.registerArmorMod(new AModProtection(5, allArmors, new ItemStack[] { new ItemStack(largePlate, 1, 2) }, new int[] { 2 } )); TConstructRegistry.registerActiveToolMod(new TActiveOmniMod()); } private void addRecipesForTableCasting () { /* Smeltery */ ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); ItemStack gemcast = new ItemStack(metalPattern, 1, 26); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); //Blank tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80); tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80); tableCasting.addCastingRecipe(gemcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(Item.emerald), 80); tableCasting.addCastingRecipe(gemcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(Item.emerald), 80); //Ingots tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 4), ingotcast, 80); //stone //Misc tableCasting.addCastingRecipe(new ItemStack(Item.emerald), new FluidStack(moltenEmeraldFluid, 640), gemcast, 80); tableCasting.addCastingRecipe(new ItemStack(materials, 1, 36), new FluidStack(glueFluid, TConstruct.ingotLiquidValue), null, 50); tableCasting.addCastingRecipe(new ItemStack(strangeFood, 1, 1), new FluidStack(bloodFluid, 160), null, 50); //Buckets ItemStack bucket = new ItemStack(Item.bucketEmpty); for (int sc = 0; sc < 24; sc++) { tableCasting.addCastingRecipe(new ItemStack(buckets, 1, sc), new FluidStack(fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); } tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 26), new FluidStack(fluids[26], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); // Clear glass pane casting tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80); // Metal toolpart casting liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1), new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1), new FluidStack(moltenSteelFluid, 1), new FluidStack(pigIronFluid, 1) }; int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16, 18 }; //ItemStack damage value int fluidAmount = 0; Fluid fs = null; for (int iter = 0; iter < patternOutputs.length; iter++) { if (patternOutputs[iter] != null) { ItemStack cast = new ItemStack(metalPattern, 1, iter + 1); tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++) { fs = liquids[iterTwo].getFluid(); fluidAmount = ((IPattern) metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2; ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]); tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50); Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount); } } } ItemStack[] ingotShapes = { new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2), new ItemStack(materials, 1, 37) }; for (int i = 0; i < ingotShapes.length; i++) { tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50); tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50); } ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); // Golden Food Stuff FluidStack goldAmount = null; if (PHConstruct.goldAppleRecipe) { goldAmount = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8); } else { goldAmount = new FluidStack(moltenGoldFluid, TConstruct.nuggetLiquidValue * 8); } tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), goldAmount, new ItemStack(Item.appleRed), true, 50); tableCasting.addCastingRecipe(new ItemStack(Item.goldenCarrot, 1), goldAmount, new ItemStack(Item.carrot), true, 50); tableCasting.addCastingRecipe(new ItemStack(Item.speckledMelon, 1), goldAmount, new ItemStack(Item.melon), true, 50); tableCasting.addCastingRecipe(new ItemStack(goldHead), goldAmount, new ItemStack(Item.skull, 1, 3), true, 50); } private void addRecipesForBasinCasting () { LiquidCasting basinCasting = TConstructRegistry.getBasinCasting(); // Block Casting basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); //Iron basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); //gold basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); //copper basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); //tin basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); //aluminum basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); //cobalt basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); //ardite basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); //bronze basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); //albrass basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); //manyullyn basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); //alumite basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); //steel basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 5), new FluidStack(moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.cobblestone), true, 100); basinCasting.addCastingRecipe(new ItemStack(Block.blockEmerald), new FluidStack(moltenEmeraldFluid, 640 * 9), null, true, 100); //emerald basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Block.gravel), true, 100); //brownstone if (PHConstruct.craftEndstone) basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.obsidian), true, 100); //endstone basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, 1000), null, true, 100); //ender basinCasting.addCastingRecipe(new ItemStack(glueBlock), new FluidStack(glueFluid, TConstruct.blockLiquidValue), null, true, 100); //glue // basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //Armor casts /*FluidRenderProperties frp = new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN); FluidStack aluFlu = new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10); FluidStack gloFlu = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10); ItemStack[] armor = { new ItemStack(helmetWood), new ItemStack(chestplateWood), new ItemStack(leggingsWood), new ItemStack(bootsWood) }; for (int sc = 0; sc < armor.length; sc++) { basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), gloFlu, armor[sc], 50, frp); }*/ } private void addRecipesForSmeltery () { //Alloy Smelting Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsBronzeAlloy), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue)); //Bronze Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsAluminumBrassAlloy), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 1)); //Aluminum Brass Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsAlumiteAlloy), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 5), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); //Alumite Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsManyullynAlloy), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue)); //Manyullyn Smeltery.addAlloyMixing(new FluidStack(pigIronFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsPigironAlloy), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue), new FluidStack(moltenEmeraldFluid, 640), new FluidStack(bloodFluid, 80)); //Pigiron // Stone parts for (int sc = 0; sc < patternOutputs.length; sc++) { if (patternOutputs[sc] != null) { Smeltery.addMelting(FluidType.Stone, new ItemStack(patternOutputs[sc], 1, 1), 1, (8 * ((IPattern) woodPattern).getPatternCost(new ItemStack(woodPattern, 1, sc + 1))) / 2); } } // Chunks Smeltery.addMelting(FluidType.Stone, new ItemStack(toolShard, 1, 1), 0, 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(toolShard, 1, 2), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Obsidian, new ItemStack(toolShard, 1, 6), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Cobalt, new ItemStack(toolShard, 1, 10), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Ardite, new ItemStack(toolShard, 1, 11), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Manyullyn, new ItemStack(toolShard, 1, 12), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Copper, new ItemStack(toolShard, 1, 13), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Bronze, new ItemStack(toolShard, 1, 14), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Alumite, new ItemStack(toolShard, 1, 15), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(toolShard, 1, 16), 0, TConstruct.chunkLiquidValue); // Items Smeltery.addMelting(FluidType.AluminumBrass, new ItemStack(blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue * 2); Smeltery.addMelting(FluidType.Glue, new ItemStack(materials, 1, 36), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Ender, new ItemStack(Item.enderPearl, 4), 0, 250); Smeltery.addMelting(metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000)); Smeltery.addMelting(FluidType.Water, new ItemStack(Item.snowball, 1, 0), 0, 125); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.flintAndSteel, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bucketEmpty), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartEmpty), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartCrate), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartPowered), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartHopper), 50, TConstruct.ingotLiquidValue * 10); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.doorIron), 0, TConstruct.ingotLiquidValue * 6); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.cauldron), 0, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shears), 0, TConstruct.ingotLiquidValue * 2); Smeltery.addMelting(FluidType.Emerald, new ItemStack(Item.emerald), -50, 640); //Blocks melt as themselves! //Ore Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); //Blocks Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000)); Smeltery.addMelting(Block.blockSnow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500)); Smeltery.addMelting(Block.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250)); Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.thinGlass, 0, 625, new FluidStack(moltenGlassFluid, 250)); Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.blockEmerald, 0, 800, new FluidStack(moltenEmeraldFluid, 640 * 9)); Smeltery.addMelting(glueBlock, 0, 250, new FluidStack(glueFluid, TConstruct.blockLiquidValue)); Smeltery.addMelting(craftedSoil, 1, 600, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 4)); Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250)); for (int i = 0; i < 16; i++) { Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250)); } //Bricks Smeltery.addMelting(multiBrick, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrickFancy, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrick, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrickFancy, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrick, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(multiBrickFancy, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); //Vanilla blocks Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.fenceIron), 0, TConstruct.ingotLiquidValue * 6 / 16); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.pressurePlateIron), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.pressurePlateGold, 4), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.rail), 0, TConstruct.ingotLiquidValue * 6 / 16); Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.railPowered), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railDetector), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railActivator), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Obsidian, new ItemStack(Block.enchantmentTable), 0, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.cauldron), 0, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.hopperBlock), 0, TConstruct.ingotLiquidValue * 5); //Vanilla Armor Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.helmetIron, 1, 0), 50, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.plateIron, 1, 0), 50, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.legsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bootsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.helmetGold, 1, 0), 50, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.plateGold, 1, 0), 50, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.legsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.bootsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.helmetChain, 1, 0), 25, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.plateChain, 1, 0), 50, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.legsChain, 1, 0), 50, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.bootsChain, 1, 0), 25, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.horseArmorIron, 1), 100, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.horseArmorGold, 1), 100, TConstruct.ingotLiquidValue * 8); //Vanilla tools Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.hoeIron, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.swordIron, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shovelIron, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.pickaxeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.axeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.hoeGold, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.swordGold, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.shovelGold, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.pickaxeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.axeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3); } private void addRecipesForDryingRack () { //Drying rack DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0)); DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1)); DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2)); //DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3)); DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4)); DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5)); DryingRackRecipes.addDryingRecipe(new ItemStack(strangeFood, 1, 0), 20 * 60 * 5, new ItemStack(jerky, 1, 6)); DryingRackRecipes.addDryingRecipe(new ItemStack(strangeFood, 1, 1), 20 * 60 * 5, new ItemStack(jerky, 1, 7)); //DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather); } private void addRecipesForChisel () { /* Detailing */ Detailing chiseling = TConstructRegistry.getChiselDetailing(); chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel); chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel); chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel); chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel); chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel); chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel); chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel); chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel); chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel); chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel); //chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel); //chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel); chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel); chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel); chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel); chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel); chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel); chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel); chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel); chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel); chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel); chiseling.addDetailing(materials, 18, multiBrick, 13, chisel); // adding multiBrick / multiBrickFanxy meta 0-13 to list for (int sc = 0; sc < 14; sc++) { chiseling.addDetailing(multiBrick, sc, multiBrickFancy, sc, chisel); } chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel); chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel); /*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/ chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel); chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel); chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel); chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel); chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel); chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel); } void setupToolTabs () { TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255)); TConstructRegistry.blockTab.init(new ItemStack(toolStationWood)); ItemStack tool = new ItemStack(longsword, 1, 0); NBTTagCompound compound = new NBTTagCompound(); compound.setCompoundTag("InfiTool", new NBTTagCompound()); compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2); compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0); compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10); tool.setTagCompound(compound); //TConstruct. TConstructRegistry.toolTab.init(tool); } public void addLoot () { //Item, min, max, weight ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27); tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1)); int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 }; Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead }; for (int partIter = 0; partIter < partTypes.length; partIter++) { for (int typeIter = 0; typeIter < validTypes.length; typeIter++) { tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15)); } } tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30); for (int i = 0; i < 13; i++) { tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20)); } tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40)); } public static String[] liquidNames; public void oreRegistry () { OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1)); OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2)); OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3)); OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4)); OreDictionary.registerOre("oreAluminum", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreAluminium", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0)); OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1)); OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5)); OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2)); OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3)); OreDictionary.registerOre("oreAluminum", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("oreAluminium", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3)); OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4)); OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5)); OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9)); OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10)); OreDictionary.registerOre("ingotAluminum", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("ingotAluminium", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13)); OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAluminiumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15)); OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16)); ensureOreIsRegistered("ingotIron", new ItemStack(Item.ingotIron)); ensureOreIsRegistered("ingotGold", new ItemStack(Item.ingotGold)); OreDictionary.registerOre("ingotObsidian", new ItemStack(materials, 1, 18)); OreDictionary.registerOre("ingotPigIron", new ItemStack(materials, 1, 34)); OreDictionary.registerOre("itemRawRubber", new ItemStack(materials, 1, 36)); OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0)); OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1)); OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2)); OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3)); OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4)); OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5)); OreDictionary.registerOre("blockAluminum", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminium", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAluminiumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8)); OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9)); ensureOreIsRegistered("blockIron", new ItemStack(Block.blockIron)); ensureOreIsRegistered("blockGold", new ItemStack(Block.blockGold)); OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19)); OreDictionary.registerOre("nuggetIron", new ItemStack(oreBerries, 1, 0)); OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20)); OreDictionary.registerOre("nuggetCopper", new ItemStack(oreBerries, 1, 2)); OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21)); OreDictionary.registerOre("nuggetTin", new ItemStack(oreBerries, 1, 3)); OreDictionary.registerOre("nuggetAluminum", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminum", new ItemStack(oreBerries, 1, 4)); OreDictionary.registerOre("nuggetAluminium", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminium", new ItemStack(oreBerries, 1, 4)); OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetAluminiumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27)); OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28)); OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29)); OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30)); OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31)); OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32)); OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33)); OreDictionary.registerOre("nuggetGold", new ItemStack(oreBerries, 1, 1)); ensureOreIsRegistered("nuggetGold", new ItemStack(Item.goldNugget)); OreDictionary.registerOre("nuggetPigIron", new ItemStack(materials, 1, 35)); OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab1, 1, Short.MAX_VALUE)); OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab2, 1, Short.MAX_VALUE)); ensureOreIsRegistered("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1)); ensureOreIsRegistered("stoneMossy", new ItemStack(Block.cobblestoneMossy)); OreDictionary.registerOre("crafterWood", new ItemStack(Block.workbench, 1)); OreDictionary.registerOre("craftingTableWood", new ItemStack(Block.workbench, 1)); OreDictionary.registerOre("torchStone", new ItemStack(stoneTorch)); String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel", "blueslime" }; for (int i = 0; i < matNames.length; i++) OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i)); OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31)); String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow", "glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" }; for (int i = 0; i < 16; i++) { OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i)); } BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg()); BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow()); //Vanilla stuff OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 1)); OreDictionary.registerOre("slimeball", new ItemStack(materials, 1, 36)); OreDictionary.registerOre("glass", new ItemStack(clearGlass)); OreDictionary.registerOre("glass", new ItemStack(Block.glass)); RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.leash)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.leash, 2), "ss ", "sS ", " s", 's', Item.silk, 'S', "slimeball")); } private void ensureOreIsRegistered (String oreName, ItemStack is) { int oreId = OreDictionary.getOreID(is); if (oreId == -1) { OreDictionary.registerOre(oreName, is); } } public static boolean thaumcraftAvailable; public void intermodCommunication () { if (Loader.isModLoaded("Thaumcraft")) { FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13)); } if (Loader.isModLoaded("Mystcraft")) { MystImcHandler.blacklistFluids(); } if (Loader.isModLoaded("BuildCraft|Transport")) { BCImcHandler.registerFacades(); } /* FORESTRY * Edit these strings to change what items are added to the backpacks * Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on * Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder * May add more backpack items later - Spyboticsguy */ if (Loader.isModLoaded("Forestry")) { String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*"; FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems); } if (!Loader.isModLoaded("AppliedEnergistics")) { AEImcHandler.registerForSpatialIO(); } } private static boolean initRecipes; public static void modRecipes () { if (!initRecipes) { initRecipes = true; if (PHConstruct.removeVanillaToolRecipes) { RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold)); } } } public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (objArray[var4] instanceof String[]) { String[] var7 = ((String[]) objArray[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (objArray[var4] instanceof String) { String var11 = (String) objArray[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < objArray.length; var4 += 2) { Character var13 = (Character) objArray[var4]; ItemStack var14 = null; if (objArray[var4 + 1] instanceof Item) { var14 = new ItemStack((Item) objArray[var4 + 1]); } else if (objArray[var4 + 1] instanceof Block) { var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE); } else if (objArray[var4 + 1] instanceof ItemStack) { var14 = (ItemStack) objArray[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack); recipeList.add(0, var17); } public void modIntegration () { ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), ""); /* Natura */ Block taintedSoil = GameRegistry.findBlock("Natura", "soil.tainted"); Block heatSand = GameRegistry.findBlock("Natura", "heatsand"); if (taintedSoil != null && heatSand != null) GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 6), Item.netherStalkSeeds, taintedSoil, heatSand); /*TE3 Flux*/ ItemStack batHardened = GameRegistry.findItemStack("ThermalExpansion", "capacitorHardened", 1); if (batHardened != null) { modFlux.batteries.add(batHardened); } ItemStack basicCell = GameRegistry.findItemStack("ThermalExpansion", "cellBasic", 1); if (basicCell != null) { modFlux.batteries.add(basicCell); } if (batHardened != null) TConstructClientRegistry.registerManualModifier("fluxmod", ironpick.copy(), (ItemStack) batHardened); if (basicCell != null) TConstructClientRegistry.registerManualModifier("fluxmod2", ironpick.copy(), (ItemStack) basicCell); /* Thaumcraft */ Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems"); if (obj != null) { TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools."); thaumcraftAvailable = true; TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true); TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic"); PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31); for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31)); } TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f); TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f); TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F); } else { TConstruct.logger.warning("Thaumcraft not detected."); } if (Loader.isModLoaded("Natura")) { try { Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent"); TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f); } catch (Exception e) { } //No need to handle } ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting(); /* Thermal Expansion 3 Metals */ ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotLead"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotSilver"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotPlatinum"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotInvar"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar } ores = OreDictionary.getOres("ingotElectrum"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum } ores = OreDictionary.getOres("blockNickel"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockLead"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockSilver"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockPlatinum"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockInvar"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockElectrum"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100); } /* Extra Utilities */ ores = OreDictionary.getOres("compressedGravel1x"); if (ores.size() > 0) { basinCasting.addCastingRecipe(new ItemStack(speedBlock, 9), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), ores.get(0), 100); } ores = OreDictionary.getOres("compressedGravel2x"); //Higher won't save properly if (ores.size() > 0) { basinCasting.addCastingRecipe(new ItemStack(speedBlock, 81), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue * 9), ores.get(0), 100); } /* Rubber */ ores = OreDictionary.getOres("itemRubber"); if (ores.size() > 0) { FurnaceRecipes.smelting().addSmelting(materials.itemID, 36, ores.get(0), 0.2f); } } public static Object getStaticItem (String name, String classPackage) { try { Class clazz = Class.forName(classPackage); Field field = clazz.getDeclaredField(name); Object ret = field.get(null); if (ret != null && (ret instanceof ItemStack || ret instanceof Item)) return ret; return null; } catch (Exception e) { TConstruct.logger.warning("Could not find " + name); return null; } } @Override public int getBurnTime (ItemStack fuel) { if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7) return 26400; return 0; } public void addOreDictionarySmelteryRecipes () { List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.Water, FluidType.Stone, FluidType.Ender, FluidType.Glass, FluidType.Slime }); for (FluidType ft : FluidType.values()) { if (exceptions.contains(ft)) continue; // Nuggets Smeltery.addDictionaryMelting("nugget" + ft.toString(), ft, -100, TConstruct.nuggetLiquidValue); // Ingots, Dust registerIngotCasting(ft); Smeltery.addDictionaryMelting("ingot" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue); Smeltery.addDictionaryMelting("dust" + ft.toString(), ft, -75, TConstruct.ingotLiquidValue); // Factorization support Smeltery.addDictionaryMelting("crystalline" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue); // Ores Smeltery.addDictionaryMelting("ore" + ft.toString(), ft, 0, TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre); // NetherOres support Smeltery.addDictionaryMelting("oreNether" + ft.toString(), ft, 75, TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre * 2); // Blocks Smeltery.addDictionaryMelting("block" + ft.toString(), ft, 100, TConstruct.blockLiquidValue); if (ft.isToolpart) { registerPatternMaterial("ingot" + ft.toString(), 2, ft.toString()); registerPatternMaterial("block" + ft.toString(), 18, ft.toString()); } } //Compressed materials for (int i = 1; i <= 8; i++) { Smeltery.addDictionaryMelting("compressedCobblestone" + i + "x", FluidType.Stone, 0, TConstruct.ingotLiquidValue / 18 * (9 ^ i)); } Smeltery.addDictionaryMelting("compressedSand1x", FluidType.Glass, 175, FluidContainerRegistry.BUCKET_VOLUME * 9); registerPatternMaterial("plankWood", 2, "Wood"); registerPatternMaterial("stickWood", 1, "Wood"); registerPatternMaterial("slabWood", 1, "Wood"); registerPatternMaterial("compressedCobblestone1x", 18, "Stone"); } private void registerPatternMaterial (String oreName, int value, String materialName) { for (ItemStack ore : OreDictionary.getOres(oreName)) { PatternBuilder.instance.registerMaterial(ore, value, materialName); } } private void registerIngotCasting (FluidType ft) { ItemStack pattern = new ItemStack(TContent.metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); for (ItemStack ore : OreDictionary.getOres("ingot" + ft.toString())) { tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50); tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenGoldFluid, TConstruct.oreLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50); tableCasting.addCastingRecipe(new ItemStack(ore.itemID, 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80); } } public void addAchievements () { HashMap<String, Achievement> achievements = TAchievements.achievements; achievements.put("tconstruct.beginner", new Achievement(2741, "tconstruct.beginner", 0, 0, manualBook, null).setIndependent().registerAchievement()); achievements.put("tconstruct.pattern", new Achievement(2742, "tconstruct.pattern", 2, 1, blankPattern, achievements.get("tconstruct.beginner")).registerAchievement()); achievements.put("tconstruct.tinkerer", new Achievement(2743, "tconstruct.tinkerer", 2, 2, new ItemStack(titleIcon, 1, 4096), achievements.get("tconstruct.pattern")).registerAchievement()); achievements.put("tconstruct.preparedFight", new Achievement(2744, "tconstruct.preparedFight", 1, 3, new ItemStack(titleIcon, 1, 4097), achievements.get("tconstruct.tinkerer")).registerAchievement()); achievements.put("tconstruct.proTinkerer", new Achievement(2745, "tconstruct.proTinkerer", 4, 4, new ItemStack(titleIcon, 1, 4098), achievements.get("tconstruct.tinkerer")).setSpecial() .registerAchievement()); achievements.put("tconstruct.smelteryMaker", new Achievement(2746, "tconstruct.smelteryMaker", -2, -1, smeltery, achievements.get("tconstruct.beginner")).registerAchievement()); achievements.put("tconstruct.enemySlayer", new Achievement(2747, "tconstruct.enemySlayer", 0, 5, new ItemStack(titleIcon, 1, 4099), achievements.get("tconstruct.preparedFight")).registerAchievement()); achievements.put("tconstruct.dualConvenience", new Achievement(2748, "tconstruct.dualConvenience", 0, 7, new ItemStack(titleIcon, 1, 4100), achievements.get("tconstruct.enemySlayer")) .setSpecial().registerAchievement()); } }
true
true
void registerBlocks () { //Tool Station toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation"); GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock"); GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation"); GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter"); GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder"); GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper"); toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge"); GameRegistry.registerBlock(toolForge, MetadataItemBlock.class, "ToolForgeBlock"); GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge"); craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation"); GameRegistry.registerBlock(craftingStationWood, "CraftingStation"); GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation"); craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab"); GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab"); furnaceSlab = new FurnaceSlab(PHConstruct.furnaceSlab, Material.rock).setUnlocalizedName("FurnaceSlab"); GameRegistry.registerBlock(furnaceSlab, "FurnaceSlab"); GameRegistry.registerTileEntity(FurnaceLogic.class, "TConstruct.Furnace"); heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan"); GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock"); GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic"); craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil"); craftedSoil.stepSound = Block.soundGravelFootstep; GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil"); searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab"); searedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab"); speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab"); speedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab"); metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock"); metalBlock.stepSound = Block.soundMetalFootstep; GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock"); meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock"); GameRegistry.registerBlock(meatBlock, HamboneItemBlock.class, "MeatBlock"); OreDictionary.registerOre("hambone", new ItemStack(meatBlock)); LanguageRegistry.addName(meatBlock, "Hambone"); GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw)); glueBlock = new GlueBlock(PHConstruct.glueBlock).setUnlocalizedName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab); GameRegistry.registerBlock(glueBlock, "GlueBlock"); OreDictionary.registerOre("blockRubber", new ItemStack(glueBlock)); woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth"); woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1"); woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth"); woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2"); //Smeltery smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery"); smelteryNether = new SmelteryBlock(PHConstruct.smelteryNether, "nether").setUnlocalizedName("Smeltery"); GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery"); GameRegistry.registerBlock(smelteryNether, SmelteryItemBlock.class, "SmelteryNether"); if (PHConstruct.newSmeltery) { GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain"); } else { GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain"); } GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants"); lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("LavaTank"); lavaTankNether = new LavaTankBlock(PHConstruct.lavaTankNether, "nether").setStepSound(Block.soundGlassFootstep).setUnlocalizedName("LavaTank"); GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank"); GameRegistry.registerBlock(lavaTankNether, LavaTankItemBlock.class, "LavaTankNether"); GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank"); searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock"); searedBlockNether = new SearedBlock(PHConstruct.searedTableNether, "nether").setUnlocalizedName("SearedBlock"); GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock"); GameRegistry.registerBlock(searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether"); GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable"); GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet"); GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin"); castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel"); GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel"); GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel"); tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air"); GameRegistry.registerBlock(tankAir, "TankAir"); GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air"); //Traps landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone) .setUnlocalizedName("landmine"); GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine"); GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine"); punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji"); GameRegistry.registerBlock(punji, "trap.punji"); barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak"); GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak"); barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce"); GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce"); barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch"); GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch"); barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle"); GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle"); slimeExplosive = new SlimeExplosive(PHConstruct.slimeExplosive).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("explosive.slime"); GameRegistry.registerBlock(slimeExplosive, MetadataItemBlock.class, "explosive.slime"); dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack"); GameRegistry.registerBlock(dryingRack, "Armor.DryingRack"); GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack"); //Liquids liquidMetal = new MaterialLiquid(MapColor.tntColor); moltenIronFluid = new Fluid("iron.molten"); if (!FluidRegistry.registerFluid(moltenIronFluid)) moltenIronFluid = FluidRegistry.getFluid("iron.molten"); moltenIron = new TConstructFluid(PHConstruct.moltenIron, moltenIronFluid, Material.lava, "liquid_iron").setUnlocalizedName("metal.molten.iron"); GameRegistry.registerBlock(moltenIron, "metal.molten.iron"); fluids[0] = moltenIronFluid; fluidBlocks[0] = moltenIron; moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty))); moltenGoldFluid = new Fluid("gold.molten"); if (!FluidRegistry.registerFluid(moltenGoldFluid)) moltenGoldFluid = FluidRegistry.getFluid("gold.molten"); moltenGold = new TConstructFluid(PHConstruct.moltenGold, moltenGoldFluid, Material.lava, "liquid_gold").setUnlocalizedName("metal.molten.gold"); GameRegistry.registerBlock(moltenGold, "metal.molten.gold"); fluids[1] = moltenGoldFluid; fluidBlocks[1] = moltenGold; moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty))); moltenCopperFluid = new Fluid("copper.molten"); if (!FluidRegistry.registerFluid(moltenCopperFluid)) moltenCopperFluid = FluidRegistry.getFluid("copper.molten"); moltenCopper = new TConstructFluid(PHConstruct.moltenCopper, moltenCopperFluid, Material.lava, "liquid_copper").setUnlocalizedName("metal.molten.copper"); GameRegistry.registerBlock(moltenCopper, "metal.molten.copper"); fluids[2] = moltenCopperFluid; fluidBlocks[2] = moltenCopper; moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty))); moltenTinFluid = new Fluid("tin.molten"); if (!FluidRegistry.registerFluid(moltenTinFluid)) moltenTinFluid = FluidRegistry.getFluid("tin.molten"); moltenTin = new TConstructFluid(PHConstruct.moltenTin, moltenTinFluid, Material.lava, "liquid_tin").setUnlocalizedName("metal.molten.tin"); GameRegistry.registerBlock(moltenTin, "metal.molten.tin"); fluids[3] = moltenTinFluid; fluidBlocks[3] = moltenTin; moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty))); moltenAluminumFluid = new Fluid("aluminum.molten"); if (!FluidRegistry.registerFluid(moltenAluminumFluid)) moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten"); moltenAluminum = new TConstructFluid(PHConstruct.moltenAluminum, moltenAluminumFluid, Material.lava, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum"); GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum"); fluids[4] = moltenAluminumFluid; fluidBlocks[4] = moltenAluminum; moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty))); moltenCobaltFluid = new Fluid("cobalt.molten"); if (!FluidRegistry.registerFluid(moltenCobaltFluid)) moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten"); moltenCobalt = new TConstructFluid(PHConstruct.moltenCobalt, moltenCobaltFluid, Material.lava, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt"); GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt"); fluids[5] = moltenCobaltFluid; fluidBlocks[5] = moltenCobalt; moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty))); moltenArditeFluid = new Fluid("ardite.molten"); if (!FluidRegistry.registerFluid(moltenArditeFluid)) moltenArditeFluid = FluidRegistry.getFluid("ardite.molten"); moltenArdite = new TConstructFluid(PHConstruct.moltenArdite, moltenArditeFluid, Material.lava, "liquid_ardite").setUnlocalizedName("metal.molten.ardite"); GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite"); fluids[6] = moltenArditeFluid; fluidBlocks[6] = moltenArdite; moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty))); moltenBronzeFluid = new Fluid("bronze.molten"); if (!FluidRegistry.registerFluid(moltenBronzeFluid)) moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten"); moltenBronze = new TConstructFluid(PHConstruct.moltenBronze, moltenBronzeFluid, Material.lava, "liquid_bronze").setUnlocalizedName("metal.molten.bronze"); GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze"); fluids[7] = moltenBronzeFluid; fluidBlocks[7] = moltenBronze; moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty))); moltenAlubrassFluid = new Fluid("aluminumbrass.molten"); if (!FluidRegistry.registerFluid(moltenAlubrassFluid)) moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten"); moltenAlubrass = new TConstructFluid(PHConstruct.moltenAlubrass, moltenAlubrassFluid, Material.lava, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass"); GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass"); fluids[8] = moltenAlubrassFluid; fluidBlocks[8] = moltenAlubrass; moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty))); moltenManyullynFluid = new Fluid("manyullyn.molten"); if (!FluidRegistry.registerFluid(moltenManyullynFluid)) moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten"); moltenManyullyn = new TConstructFluid(PHConstruct.moltenManyullyn, moltenManyullynFluid, Material.lava, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn"); GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn"); fluids[9] = moltenManyullynFluid; fluidBlocks[9] = moltenManyullyn; moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty))); moltenAlumiteFluid = new Fluid("alumite.molten"); if (!FluidRegistry.registerFluid(moltenAlumiteFluid)) moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten"); moltenAlumite = new TConstructFluid(PHConstruct.moltenAlumite, moltenAlumiteFluid, Material.lava, "liquid_alumite").setUnlocalizedName("metal.molten.alumite"); GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite"); fluids[10] = moltenAlumiteFluid; fluidBlocks[10] = moltenAlumite; moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty))); moltenObsidianFluid = new Fluid("obsidian.molten"); if (!FluidRegistry.registerFluid(moltenObsidianFluid)) moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten"); moltenObsidian = new TConstructFluid(PHConstruct.moltenObsidian, moltenObsidianFluid, Material.lava, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian"); GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian"); fluids[11] = moltenObsidianFluid; fluidBlocks[11] = moltenObsidian; moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty))); moltenSteelFluid = new Fluid("steel.molten"); if (!FluidRegistry.registerFluid(moltenSteelFluid)) moltenSteelFluid = FluidRegistry.getFluid("steel.molten"); moltenSteel = new TConstructFluid(PHConstruct.moltenSteel, moltenSteelFluid, Material.lava, "liquid_steel").setUnlocalizedName("metal.molten.steel"); GameRegistry.registerBlock(moltenSteel, "metal.molten.steel"); fluids[12] = moltenSteelFluid; fluidBlocks[12] = moltenSteel; moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty))); moltenGlassFluid = new Fluid("glass.molten"); if (!FluidRegistry.registerFluid(moltenGlassFluid)) moltenGlassFluid = FluidRegistry.getFluid("glass.molten"); moltenGlass = new TConstructFluid(PHConstruct.moltenGlass, moltenGlassFluid, Material.lava, "liquid_glass", true).setUnlocalizedName("metal.molten.glass"); GameRegistry.registerBlock(moltenGlass, "metal.molten.glass"); fluids[13] = moltenGlassFluid; fluidBlocks[13] = moltenGlass; moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty))); moltenStoneFluid = new Fluid("stone.seared"); if (!FluidRegistry.registerFluid(moltenStoneFluid)) moltenStoneFluid = FluidRegistry.getFluid("stone.seared"); moltenStone = new TConstructFluid(PHConstruct.moltenStone, moltenStoneFluid, Material.lava, "liquid_stone").setUnlocalizedName("molten.stone"); GameRegistry.registerBlock(moltenStone, "molten.stone"); fluids[14] = moltenStoneFluid; fluidBlocks[14] = moltenStone; moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty))); moltenEmeraldFluid = new Fluid("emerald.liquid"); if (!FluidRegistry.registerFluid(moltenEmeraldFluid)) moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid"); moltenEmerald = new TConstructFluid(PHConstruct.moltenEmerald, moltenEmeraldFluid, Material.water, "liquid_villager").setUnlocalizedName("molten.emerald"); GameRegistry.registerBlock(moltenEmerald, "molten.emerald"); fluids[15] = moltenEmeraldFluid; fluidBlocks[15] = moltenEmerald; moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty))); bloodFluid = new Fluid("blood"); if (!FluidRegistry.registerFluid(bloodFluid)) bloodFluid = FluidRegistry.getFluid("blood"); blood = new BloodBlock(PHConstruct.blood, bloodFluid, Material.water, "liquid_cow").setUnlocalizedName("liquid.blood"); GameRegistry.registerBlock(blood, "liquid.blood"); fluids[16] = bloodFluid; fluidBlocks[16] = blood; bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty))); moltenNickelFluid = new Fluid("nickel.molten"); if (!FluidRegistry.registerFluid(moltenNickelFluid)) moltenNickelFluid = FluidRegistry.getFluid("nickel.molten"); moltenNickel = new TConstructFluid(PHConstruct.moltenNickel, moltenNickelFluid, Material.lava, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel"); GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel"); fluids[17] = moltenNickelFluid; fluidBlocks[17] = moltenNickel; moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty))); moltenLeadFluid = new Fluid("lead.molten"); if (!FluidRegistry.registerFluid(moltenLeadFluid)) moltenLeadFluid = FluidRegistry.getFluid("lead.molten"); moltenLead = new TConstructFluid(PHConstruct.moltenLead, moltenLeadFluid, Material.lava, "liquid_lead").setUnlocalizedName("metal.molten.lead"); GameRegistry.registerBlock(moltenLead, "metal.molten.lead"); fluids[18] = moltenLeadFluid; fluidBlocks[18] = moltenLead; moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty))); moltenSilverFluid = new Fluid("silver.molten"); if (!FluidRegistry.registerFluid(moltenSilverFluid)) moltenSilverFluid = FluidRegistry.getFluid("silver.molten"); moltenSilver = new TConstructFluid(PHConstruct.moltenSilver, moltenSilverFluid, Material.lava, "liquid_silver").setUnlocalizedName("metal.molten.silver"); GameRegistry.registerBlock(moltenSilver, "metal.molten.silver"); fluids[19] = moltenSilverFluid; fluidBlocks[19] = moltenSilver; moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty))); moltenShinyFluid = new Fluid("platinum.molten"); if (!FluidRegistry.registerFluid(moltenShinyFluid)) moltenShinyFluid = FluidRegistry.getFluid("platinum.molten"); moltenShiny = new TConstructFluid(PHConstruct.moltenShiny, moltenShinyFluid, Material.lava, "liquid_shiny").setUnlocalizedName("metal.molten.shiny"); GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny"); fluids[20] = moltenShinyFluid; fluidBlocks[20] = moltenShiny; moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty))); moltenInvarFluid = new Fluid("invar.molten"); if (!FluidRegistry.registerFluid(moltenInvarFluid)) moltenInvarFluid = FluidRegistry.getFluid("invar.molten"); moltenInvar = new TConstructFluid(PHConstruct.moltenInvar, moltenInvarFluid, Material.lava, "liquid_invar").setUnlocalizedName("metal.molten.invar"); GameRegistry.registerBlock(moltenInvar, "metal.molten.invar"); fluids[21] = moltenInvarFluid; fluidBlocks[21] = moltenInvar; moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty))); moltenElectrumFluid = new Fluid("electrum.molten"); if (!FluidRegistry.registerFluid(moltenElectrumFluid)) moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten"); moltenElectrum = new TConstructFluid(PHConstruct.moltenElectrum, moltenElectrumFluid, Material.lava, "liquid_electrum").setUnlocalizedName("metal.molten.electrum"); GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum"); fluids[22] = moltenElectrumFluid; fluidBlocks[22] = moltenElectrum; moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty))); moltenEnderFluid = new Fluid("ender"); if (!FluidRegistry.registerFluid(moltenEnderFluid)) { moltenEnderFluid = FluidRegistry.getFluid("ender"); moltenEnder = Block.blocksList[moltenEnderFluid.getBlockID()]; if (moltenEnder == null) TConstruct.logger.info("Molten ender block missing!"); } else { moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender"); GameRegistry.registerBlock(moltenEnder, "fluid.ender"); moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty))); } fluids[23] = moltenEnderFluid; fluidBlocks[23] = moltenEnder; //Slime slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f); blueSlimeFluid = new Fluid("slime.blue"); if (!FluidRegistry.registerFluid(blueSlimeFluid)) blueSlimeFluid = FluidRegistry.getFluid("slime.blue"); slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime"); GameRegistry.registerBlock(slimePool, "liquid.slime"); fluids[24] = blueSlimeFluid; fluidBlocks[24] = slimePool; blueSlimeFluid.setBlockID(slimePool); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty))); //Glue glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200); if (!FluidRegistry.registerFluid(glueFluid)) glueFluid = FluidRegistry.getFluid("glue"); glueFluidBlock = new GlueFluid(PHConstruct.glueFluidBlock, glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.glue"); GameRegistry.registerBlock(glueFluidBlock, "liquid.glue"); fluids[25] = glueFluid; fluidBlocks[25] = glueFluidBlock; glueFluid.setBlockID(glueFluidBlock); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(glueFluid, 1000), new ItemStack(buckets, 1, 26), new ItemStack(Item.bucketEmpty))); pigIronFluid = new Fluid("pigiron.molten"); if (!FluidRegistry.registerFluid(pigIronFluid)) pigIronFluid = FluidRegistry.getFluid("pigiron.molten"); else pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300); fluids[26] = pigIronFluid; slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel"); GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel"); slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass"); GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass"); slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall"); GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall"); slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves"); GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves"); slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling"); GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling"); slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water, "greencurrent").setHardness(0.3f).setStepSound(slimeStep).setUnlocalizedName("slime.channel"); GameRegistry.registerBlock(slimeChannel, "slime.channel"); TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1; bloodChannel = new ConveyorBase(PHConstruct.bloodChannel, Material.water, "liquid_cow").setHardness(0.3f).setStepSound(slimeStep).setUnlocalizedName("blood.channel"); GameRegistry.registerBlock(bloodChannel, "blood.channel"); TConstructRegistry.drawbridgeState[bloodChannel.blockID] = 1; slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setHardness(0.3f).setUnlocalizedName("slime.pad"); GameRegistry.registerBlock(slimePad, "slime.pad"); TConstructRegistry.drawbridgeState[slimePad.blockID] = 1; //Decoration stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch"); GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch"); stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder"); GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder"); multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick"); GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick"); multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy"); GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy"); //Ores String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" }; oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one"); GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one"); String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" }; oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two"); GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two"); String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" }; oreSlag = new MetalOre(PHConstruct.oreSlag, Material.rock, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore"); GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick"); MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1); oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore"); GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre"); MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2); MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4); speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock"); GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock"); //Glass clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock"); clearGlass.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock"); glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false); GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane"); stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear"); stainedGlassClear.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear"); stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane); GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained"); //Rail woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood"); GameRegistry.registerBlock(woodenRail, "rail.wood"); } void registerItems () { titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon"); GameRegistry.registerItem(titleIcon, "titleIcon"); String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" }; blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern"); GameRegistry.registerItem(blankPattern, "blankPattern"); materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials"); toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod"); toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard"); woodPattern = new Pattern(PHConstruct.woodPattern, "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern"); metalPattern = new MetalPattern(PHConstruct.metalPattern, "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern"); //armorPattern = new ArmorPattern(PHConstruct.armorPattern, "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern"); GameRegistry.registerItem(materials, "materials"); GameRegistry.registerItem(woodPattern, "woodPattern"); GameRegistry.registerItem(metalPattern, "metalPattern"); //GameRegistry.registerItem(armorPattern, "armorPattern"); TConstructRegistry.addItemToDirectory("blankPattern", blankPattern); TConstructRegistry.addItemToDirectory("woodPattern", woodPattern); TConstructRegistry.addItemToDirectory("metalPattern", metalPattern); //TConstructRegistry.addItemToDirectory("armorPattern", armorPattern); String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" }; for (int i = 1; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i)); } for (int i = 0; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i)); } /*String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" }; for (int i = 1; i < armorPartTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i)); }*/ manualBook = new Manual(PHConstruct.manual); GameRegistry.registerItem(manualBook, "manualBook"); buckets = new FilledBucket(PHConstruct.buckets); GameRegistry.registerItem(buckets, "buckets"); pickaxe = new Pickaxe(PHConstruct.pickaxe); shovel = new Shovel(PHConstruct.shovel); hatchet = new Hatchet(PHConstruct.axe); broadsword = new Broadsword(PHConstruct.broadsword); longsword = new Longsword(PHConstruct.longsword); rapier = new Rapier(PHConstruct.rapier); dagger = new Dagger(PHConstruct.dagger); cutlass = new Cutlass(PHConstruct.cutlass); frypan = new FryingPan(PHConstruct.frypan); battlesign = new BattleSign(PHConstruct.battlesign); mattock = new Mattock(PHConstruct.mattock); chisel = new Chisel(PHConstruct.chisel); lumberaxe = new LumberAxe(PHConstruct.lumberaxe); cleaver = new Cleaver(PHConstruct.cleaver); scythe = new Scythe(PHConstruct.scythe); excavator = new Excavator(PHConstruct.excavator); hammer = new Hammer(PHConstruct.hammer); battleaxe = new Battleaxe(PHConstruct.battleaxe); shortbow = new Shortbow(PHConstruct.shortbow); arrow = new Arrow(PHConstruct.arrow); Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, dagger, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe, shortbow, arrow }; String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" }; for (int i = 0; i < tools.length; i++) { GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]); } potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher"); GameRegistry.registerItem(potionLauncher, "potionLauncher"); pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead"); shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead"); hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead"); binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding"); toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding"); toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod"); largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate"); swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade"); wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard"); handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard"); crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar"); knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade"); fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard"); frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead"); signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead"); chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead"); scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade"); broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead"); excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead"); largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade"); hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead"); bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring"); arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead"); fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching"); Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard, frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead }; String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard", "crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring", "fletching", "arrowhead" }; for (int i = 0; i < toolParts.length; i++) { GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7 compat TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]); } diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond"); strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood"); oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry"); GameRegistry.registerItem(diamondApple, "diamondApple"); GameRegistry.registerItem(strangeFood, "strangeFood"); GameRegistry.registerItem(oreBerries, "oreBerries"); jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky"); GameRegistry.registerItem(jerky, "jerky"); //Wearables heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister"); knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage"); goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead"); GameRegistry.registerItem(heartCanister, "heartCanister"); GameRegistry.registerItem(knapsack, "knapsack"); GameRegistry.registerItem(goldHead, "goldHead"); LiquidCasting basinCasting = TConstruct.getBasinCasting(); materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3); helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood"); chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood"); leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood"); bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood"); GameRegistry.registerItem(helmetWood, "helmetWood"); GameRegistry.registerItem(chestplateWood, "chestplateWood"); GameRegistry.registerItem(leggingsWood, "leggingsWood"); GameRegistry.registerItem(bootsWood, "bootsWood"); exoGoggles = new ExoArmor(PHConstruct.exoGoggles, EnumArmorPart.HELMET, "exosuit").setUnlocalizedName("tconstruct.exoGoggles"); exoChest = new ExoArmor(PHConstruct.exoChest, EnumArmorPart.CHEST, "exosuit").setUnlocalizedName("tconstruct.exoChest"); exoPants = new ExoArmor(PHConstruct.exoPants, EnumArmorPart.PANTS, "exosuit").setUnlocalizedName("tconstruct.exoPants"); exoShoes = new ExoArmor(PHConstruct.exoShoes, EnumArmorPart.SHOES, "exosuit").setUnlocalizedName("tconstruct.exoShoes"); String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper", "ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper", "nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze", "nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" }; for (int i = 0; i < materialStrings.length; i++) { TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i)); } String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" }; for (int i = 0; i < oreberries.length; i++) { TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i)); } TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0)); TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0)); TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0)); TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1)); TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2)); //Vanilla stack sizes Item.doorWood.setMaxStackSize(16); Item.doorIron.setMaxStackSize(16); Item.snowball.setMaxStackSize(64); Item.boat.setMaxStackSize(16); Item.minecartEmpty.setMaxStackSize(3); Item.minecartCrate.setMaxStackSize(3); Item.minecartPowered.setMaxStackSize(3); Item.itemsList[Block.cake.blockID].setMaxStackSize(16); //Block.torchWood.setTickRandomly(false); } void registerMaterials () { TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound"); TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", ""); TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", ""); TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged"); TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", ""); TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable"); TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", ""); TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", ""); TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", ""); TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", ""); TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", ""); TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", ""); TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", "Tasty"); TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); //Slime //Material ID, mass, fragility TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime TConstructRegistry.addArrowMaterial(18, 6.8F, 0.5F, 100F); //Iron TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather for (int i = 0; i < 4; i++) TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime PatternBuilder pb = PatternBuilder.instance; if (PHConstruct.enableTWood) pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0); else pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0); if (PHConstruct.enableTStone) { pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1); pb.registerMaterial(Block.cobblestone, 2, "Stone"); } else pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0); pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2); if (PHConstruct.enableTFlint) pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); else pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); if (PHConstruct.enableTCactus) pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); else pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); if (PHConstruct.enableTBone) pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); else pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6); pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian"); if (PHConstruct.enableTNetherrack) pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); else pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); if (PHConstruct.enableTSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8); else pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8); if (PHConstruct.enableTPaper) pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9); else pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9); pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10); pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11); pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12); pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13); pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14); pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15); pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16); if (PHConstruct.enableTBlueSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17); else pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17); pb.registerFullMaterial(new ItemStack(materials, 1, 34), 2, "PigIron", new ItemStack(toolShard, 1, 18), new ItemStack(toolRod, 1, 18), 18); pb.addToolPattern((IPattern) woodPattern); } public static Item[] patternOutputs; public static FluidStack[] liquids; void addCraftingRecipes () { addPartMapping(); addRecipesForToolBuilder(); addRecipesForTableCasting(); addRecipesForBasinCasting(); addRecipesForSmeltery(); addRecipesForChisel(); addRecipesForFurnace(); addRecipesForCraftingTable(); addRecipesForDryingRack(); } private void addRecipesForCraftingTable () { String[] patBlock = { "###", "###", "###" }; String[] patSurround = { "###", "#m#", "###" }; Object[] toolForgeBlocks = { "blockIron", "blockGold", Block.blockDiamond, Block.blockEmerald, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin", "blockAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" }; // ToolForge Recipes (Metal Version) for (int sc = 0; sc < toolForgeBlocks.length; sc++) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', toolForgeBlocks[sc])); // adding slab version recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(craftingSlabWood, 1, 1), 'm', toolForgeBlocks[sc])); } // ToolStation Recipes (Wooden Version) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "craftingTableWood")); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingSlabWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood")); if (PHConstruct.stencilTableCrafting) { GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood")); } GameRegistry.addRecipe(new ItemStack(furnaceSlab, 1, 0), "###", "# #", "###", '#', new ItemStack(Block.stoneSingleSlab, 1, 3)); // Blank Pattern Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood")); // Manual Book Recipes GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 3), new ItemStack(manualBook, 1, 2)); // alternative Vanilla Book Recipe GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.nameTag), "P~ ", "~O ", " ~", '~', Item.silk, 'P', Item.paper, 'O', "slimeball")); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt)); // Paperstack Recipe GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper); // Mossball Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), patBlock, '#', "stoneMossy")); // LavaCrystal Recipes -Auto-smelt GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod); GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod); // Slimy sand Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt); // Grout Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 8, 1), new ItemStack(Block.blockClay, 1, Short.MAX_VALUE), Block.sand, Block.sand, Block.sand, Block.sand, Block.gravel, Block.gravel, Block.gravel, Block.gravel); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 6), Item.netherStalkSeeds, Block.slowSand, Block.gravel); // Graveyard Soil Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15)); // Silky Cloth Recipes GameRegistry.addRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', new ItemStack(materials, 1, 24), '#', new ItemStack(Item.silk)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Item.silk))); // Silky Jewel Recipes GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald)); // Armor Recipes Object[] helm = new String[] { "www", "w w" }; Object[] chest = new String[] { "w w", "www", "www" }; Object[] pants = new String[] { "www", "w w", "w w" }; Object[] shoes = new String[] { "w w", "w w" }; GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, helm, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, chest, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, pants, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, shoes, 'w', "logWood")); ItemStack exoGoggleStack = new ItemStack(exoGoggles); ItemStack exoChestStack = new ItemStack(exoChest); ItemStack exoPantsStack = new ItemStack(exoPants); ItemStack exoShoesStack = new ItemStack(exoShoes); ToolBuilder.instance.addArmorTag(exoGoggleStack); ToolBuilder.instance.addArmorTag(exoChestStack); ToolBuilder.instance.addArmorTag(exoPantsStack); ToolBuilder.instance.addArmorTag(exoShoesStack); GameRegistry.addShapedRecipe(exoGoggleStack, helm, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoChestStack, chest, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoPantsStack, pants, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoShoesStack, shoes, 'w', new ItemStack(largePlate, 1, 14)); // Metal conversion Recipes GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 3), patBlock, '#', new ItemStack(materials, 1, 9)); // Copper GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 5), patBlock, '#', new ItemStack(materials, 1, 10)); // Tin GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 6), patBlock, '#', new ItemStack(materials, 1, 11)); // Aluminum //GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 6), patBlock, '#', new ItemStack(materials, 1, 12)); // Aluminum GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 4), patBlock, '#', new ItemStack(materials, 1, 13)); // Bronze GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 7), patBlock, '#', new ItemStack(materials, 1, 14)); // AluBrass GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 0), patBlock, '#', new ItemStack(materials, 1, 3)); // Cobalt GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 1), patBlock, '#', new ItemStack(materials, 1, 4)); // Ardite GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 2), patBlock, '#', new ItemStack(materials, 1, 5)); // Manyullyn GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 8), patBlock, '#', new ItemStack(materials, 1, 15)); // Alumite GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 9), patBlock, '#', new ItemStack(materials, 1, 16)); // Steel GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 11), patBlock, '#', new ItemStack(materials, 1, 12)); //Aluminum raw -> ingot GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 11), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel GameRegistry.addRecipe(new ItemStack(Item.ingotIron), patBlock, '#', new ItemStack(materials, 1, 19)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 1, 9), patBlock, '#', new ItemStack(materials, 1, 20)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 1, 10), patBlock, '#', new ItemStack(materials, 1, 21)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 1, 11), patBlock, '#', new ItemStack(materials, 1, 22)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 1, 14), patBlock, '#', new ItemStack(materials, 1, 24)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 1, 18), patBlock, '#', new ItemStack(materials, 1, 27)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 1, 3), patBlock, '#', new ItemStack(materials, 1, 28)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 1, 4), patBlock, '#', new ItemStack(materials, 1, 29)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 1, 5), patBlock, '#', new ItemStack(materials, 1, 30)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 1, 13), patBlock, '#', new ItemStack(materials, 1, 31)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 1, 15), patBlock, '#', new ItemStack(materials, 1, 32)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 1, 16), patBlock, '#', new ItemStack(materials, 1, 33)); //Steel GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 11)); //Aluminum //GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel // stained Glass Recipes String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; String color = ""; for (int i = 0; i < 16; i++) { color = dyeTypes[15 - i]; GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), patSurround, 'm', color, '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', clearGlass)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, clearGlass)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', glassPane)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, glassPane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); } // Glass Recipes GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass }); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', "glass", 'Q', Item.netherQuartz, 'W', "slabWood" })); GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian }); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glassPane, 16, 0), "GGG", "GGG", 'G', clearGlass)); // Smeltery Components Recipes ItemStack searedBrick = new ItemStack(materials, 1, 2); GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel searedBrick = new ItemStack(materials, 1, 37); GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel // Jack o'Latern Recipe - Stone Torch GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 's', new ItemStack(stoneTorch)); // Stone Torch Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod")); // Stone Ladder Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod")); // Wooden Rail Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood")); // Stonesticks Recipes GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone)); GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone)); // ItemStack aluBrass = new ItemStack(materials, 1, 14); // Clock Recipe - Vanilla alternativ GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone)); // Gold Pressure Plate - Vanilla alternativ GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass); //Accessories GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotAluminium")); //GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), " # ", "#B#", " # ", '#', "ingotTin", 'B', Item.bone)); GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed)); GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), new ItemStack(materials, 1, 8), new ItemStack(heartCanister, 1, 0), new ItemStack( heartCanister, 1, 1)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', "ingotGold")); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', aluBrass); // Drying Rack Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood")); //Landmine Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); //Ultra hardcore recipes GameRegistry.addRecipe(new ItemStack(goldHead), patSurround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3)); // Slab Smeltery Components Recipes for (int i = 0; i < 7; i++) { GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i)); } GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11)); // Wool Slab Recipes for (int sc = 0; sc <= 7; sc++) { GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc)); GameRegistry.addRecipe(new ItemStack(woolSlab2, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc + 8)); GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc), new ItemStack(woolSlab1, 1, sc), new ItemStack(woolSlab1, 1, sc)); GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc + 8), new ItemStack(woolSlab2, 1, sc), new ItemStack(woolSlab2, 1, sc)); } GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.cloth, 1, 0), "slabCloth", "slabCloth")); //Trap Recipes GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed)); GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood")); // Advanced WorkBench Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "craftingTableWood")); //Slab crafters GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "craftingTableWood")); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 0), "b", 'b', new ItemStack(craftingStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); // EssenceExtractor Recipe //Slime Recipes GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood); GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0)); GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall); GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1)); //slimeExplosive GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 0), Item.slimeBall, Block.tnt); GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 2), strangeFood, Block.tnt); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt)); GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone)); GameRegistry.addShapelessRecipe(new ItemStack(bloodChannel, 1, 0), new ItemStack(strangeFood, 1, 1), new ItemStack(strangeFood, 1, 1), new ItemStack(strangeFood, 1, 1), new ItemStack( strangeFood, 1, 1), new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeChannel, 1, 0), "slimeball", "slimeball", "slimeball", "slimeball", new ItemStack(Item.redstone))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, "slimeball")); } private void addRecipesForFurnace () { FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 6, new ItemStack(materials, 1, 37), 2f); //Nether seared brick //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 11), 0.5f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f); //FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 11), 0.2f); FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f); } private void addPartMapping () { /* Tools */ patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead, null }; int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 }; if (PHConstruct.craftMetalTools) { for (int mat = 0; mat < 18; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat)); } } } else { for (int mat = 0; mat < nonMetals.length; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat])); } } } } private void addRecipesForToolBuilder () { ToolBuilder tb = ToolBuilder.instance; tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding); tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard); tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod); tb.addNormalToolRecipe(shovel, shovelHead, toolRod); tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard); tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar); tb.addNormalToolRecipe(frypan, frypanHead, toolRod); tb.addNormalToolRecipe(battlesign, signHead, toolRod); tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead); tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar); tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard); tb.addNormalToolRecipe(chisel, chiselHead, toolRod); tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod); tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod); tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate); tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding); //tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod); BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow); tb.addCustomToolRecipe(recipe); tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching); ItemStack diamond = new ItemStack(Item.diamond); tb.registerToolMod(new ModRepair()); tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b")); tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72")); modFlux = new ModFlux(); tb.registerToolMod(modFlux); ItemStack redstoneItem = new ItemStack(Item.redstone); ItemStack redstoneBlock = new ItemStack(Block.blockRedstone); tb.registerToolMod(new ModRedstone(2, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 })); ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4); ItemStack lapisBlock = new ItemStack(Block.blockLapis); this.modLapis = new ModLapis(10, new ItemStack[] { lapisItem, lapisBlock }, new int[] { 1, 9 }); tb.registerToolMod(this.modLapis); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(this.materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair")); ItemStack blazePowder = new ItemStack(Item.blazePowder); tb.registerToolMod(new ModBlaze(7, new ItemStack[] { blazePowder }, new int[] { 1 })); tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(this.materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt")); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(this.materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal")); this.modAttack = new ModAttack("Quartz", 11, new ItemStack[] { new ItemStack(Item.netherQuartz), new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE) }, new int[] { 1, 4 }); tb.registerToolMod(this.modAttack); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Block.blockDiamond), new ItemStack(Item.appleGold, 1, 1) }, "Tier1.5Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free")); ItemStack silkyJewel = new ItemStack(this.materials, 1, 26); tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12)); ItemStack piston = new ItemStack(Block.pistonBase); tb.registerToolMod(new ModPiston(3, new ItemStack[] { piston }, new int[] { 1 })); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading")); ItemStack holySoil = new ItemStack(this.craftedSoil, 1, 4); tb.registerToolMod(new ModSmite("Smite", 14, new ItemStack[] { holySoil }, new int[] { 1 })); ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye); tb.registerToolMod(new ModAntiSpider("Anti-Spider", 15, new ItemStack[] { spidereyeball }, new int[] { 1 })); ItemStack obsidianPlate = new ItemStack(this.largePlate, 1, 6); tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1)); EnumSet<EnumArmorPart> allArmors = EnumSet.of(EnumArmorPart.HELMET, EnumArmorPart.CHEST, EnumArmorPart.PANTS, EnumArmorPart.SHOES); EnumSet<EnumArmorPart> chest = EnumSet.of(EnumArmorPart.CHEST); tb.registerArmorMod(new AModMoveSpeed(0, allArmors, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 }, false)); tb.registerArmorMod(new AModKnockbackResistance(1, allArmors, new ItemStack[] { new ItemStack(Item.ingotGold), new ItemStack(Block.blockGold) }, new int[] { 1, 9 }, false)); tb.registerArmorMod(new AModHealthBoost(2, allArmors, new ItemStack[] { new ItemStack(heartCanister, 1, 2) }, new int[] { 2 }, true)); tb.registerArmorMod(new AModDamageBoost(3, allArmors, new ItemStack[] { new ItemStack(Item.diamond), new ItemStack(Block.blockDiamond) }, new int[] { 1, 9 }, false, 3, 0.05)); tb.registerArmorMod(new AModDamageBoost(4, chest, new ItemStack[] { new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE) }, new int[] { 1 }, true, 5, 1)); tb.registerArmorMod(new AModProtection(5, allArmors, new ItemStack[] { new ItemStack(largePlate, 1, 2) }, new int[] { 2 } )); TConstructRegistry.registerActiveToolMod(new TActiveOmniMod()); } private void addRecipesForTableCasting () { /* Smeltery */ ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); ItemStack gemcast = new ItemStack(metalPattern, 1, 26); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); //Blank tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80); tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80); tableCasting.addCastingRecipe(gemcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(Item.emerald), 80); tableCasting.addCastingRecipe(gemcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(Item.emerald), 80); //Ingots tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 4), ingotcast, 80); //stone //Misc tableCasting.addCastingRecipe(new ItemStack(Item.emerald), new FluidStack(moltenEmeraldFluid, 640), gemcast, 80); tableCasting.addCastingRecipe(new ItemStack(materials, 1, 36), new FluidStack(glueFluid, TConstruct.ingotLiquidValue), null, 50); tableCasting.addCastingRecipe(new ItemStack(strangeFood, 1, 1), new FluidStack(bloodFluid, 160), null, 50); //Buckets ItemStack bucket = new ItemStack(Item.bucketEmpty); for (int sc = 0; sc < 24; sc++) { tableCasting.addCastingRecipe(new ItemStack(buckets, 1, sc), new FluidStack(fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); } tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 26), new FluidStack(fluids[26], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); // Clear glass pane casting tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80); // Metal toolpart casting liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1), new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1), new FluidStack(moltenSteelFluid, 1), new FluidStack(pigIronFluid, 1) }; int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16, 18 }; //ItemStack damage value int fluidAmount = 0; Fluid fs = null; for (int iter = 0; iter < patternOutputs.length; iter++) { if (patternOutputs[iter] != null) { ItemStack cast = new ItemStack(metalPattern, 1, iter + 1); tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++) { fs = liquids[iterTwo].getFluid(); fluidAmount = ((IPattern) metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2; ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]); tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50); Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount); } } } ItemStack[] ingotShapes = { new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2), new ItemStack(materials, 1, 37) }; for (int i = 0; i < ingotShapes.length; i++) { tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50); tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50); } ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); // Golden Food Stuff FluidStack goldAmount = null; if (PHConstruct.goldAppleRecipe) { goldAmount = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8); } else { goldAmount = new FluidStack(moltenGoldFluid, TConstruct.nuggetLiquidValue * 8); } tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), goldAmount, new ItemStack(Item.appleRed), true, 50); tableCasting.addCastingRecipe(new ItemStack(Item.goldenCarrot, 1), goldAmount, new ItemStack(Item.carrot), true, 50); tableCasting.addCastingRecipe(new ItemStack(Item.speckledMelon, 1), goldAmount, new ItemStack(Item.melon), true, 50); tableCasting.addCastingRecipe(new ItemStack(goldHead), goldAmount, new ItemStack(Item.skull, 1, 3), true, 50); } private void addRecipesForBasinCasting () { LiquidCasting basinCasting = TConstructRegistry.getBasinCasting(); // Block Casting basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); //Iron basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); //gold basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); //copper basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); //tin basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); //aluminum basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); //cobalt basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); //ardite basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); //bronze basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); //albrass basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); //manyullyn basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); //alumite basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); //steel basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 5), new FluidStack(moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.cobblestone), true, 100); basinCasting.addCastingRecipe(new ItemStack(Block.blockEmerald), new FluidStack(moltenEmeraldFluid, 640 * 9), null, true, 100); //emerald basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Block.gravel), true, 100); //brownstone if (PHConstruct.craftEndstone) basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.obsidian), true, 100); //endstone basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, 1000), null, true, 100); //ender basinCasting.addCastingRecipe(new ItemStack(glueBlock), new FluidStack(glueFluid, TConstruct.blockLiquidValue), null, true, 100); //glue // basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //Armor casts /*FluidRenderProperties frp = new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN); FluidStack aluFlu = new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10); FluidStack gloFlu = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10); ItemStack[] armor = { new ItemStack(helmetWood), new ItemStack(chestplateWood), new ItemStack(leggingsWood), new ItemStack(bootsWood) }; for (int sc = 0; sc < armor.length; sc++) { basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), gloFlu, armor[sc], 50, frp); }*/ } private void addRecipesForSmeltery () { //Alloy Smelting Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsBronzeAlloy), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue)); //Bronze Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsAluminumBrassAlloy), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 1)); //Aluminum Brass Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsAlumiteAlloy), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 5), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); //Alumite Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsManyullynAlloy), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue)); //Manyullyn Smeltery.addAlloyMixing(new FluidStack(pigIronFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsPigironAlloy), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue), new FluidStack(moltenEmeraldFluid, 640), new FluidStack(bloodFluid, 80)); //Pigiron // Stone parts for (int sc = 0; sc < patternOutputs.length; sc++) { if (patternOutputs[sc] != null) { Smeltery.addMelting(FluidType.Stone, new ItemStack(patternOutputs[sc], 1, 1), 1, (8 * ((IPattern) woodPattern).getPatternCost(new ItemStack(woodPattern, 1, sc + 1))) / 2); } } // Chunks Smeltery.addMelting(FluidType.Stone, new ItemStack(toolShard, 1, 1), 0, 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(toolShard, 1, 2), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Obsidian, new ItemStack(toolShard, 1, 6), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Cobalt, new ItemStack(toolShard, 1, 10), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Ardite, new ItemStack(toolShard, 1, 11), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Manyullyn, new ItemStack(toolShard, 1, 12), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Copper, new ItemStack(toolShard, 1, 13), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Bronze, new ItemStack(toolShard, 1, 14), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Alumite, new ItemStack(toolShard, 1, 15), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(toolShard, 1, 16), 0, TConstruct.chunkLiquidValue); // Items Smeltery.addMelting(FluidType.AluminumBrass, new ItemStack(blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue * 2); Smeltery.addMelting(FluidType.Glue, new ItemStack(materials, 1, 36), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Ender, new ItemStack(Item.enderPearl, 4), 0, 250); Smeltery.addMelting(metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000)); Smeltery.addMelting(FluidType.Water, new ItemStack(Item.snowball, 1, 0), 0, 125); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.flintAndSteel, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bucketEmpty), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartEmpty), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartCrate), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartPowered), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartHopper), 50, TConstruct.ingotLiquidValue * 10); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.doorIron), 0, TConstruct.ingotLiquidValue * 6); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.cauldron), 0, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shears), 0, TConstruct.ingotLiquidValue * 2); Smeltery.addMelting(FluidType.Emerald, new ItemStack(Item.emerald), -50, 640); //Blocks melt as themselves! //Ore Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); //Blocks Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000)); Smeltery.addMelting(Block.blockSnow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500)); Smeltery.addMelting(Block.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250)); Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.thinGlass, 0, 625, new FluidStack(moltenGlassFluid, 250)); Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.blockEmerald, 0, 800, new FluidStack(moltenEmeraldFluid, 640 * 9)); Smeltery.addMelting(glueBlock, 0, 250, new FluidStack(glueFluid, TConstruct.blockLiquidValue)); Smeltery.addMelting(craftedSoil, 1, 600, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 4)); Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250)); for (int i = 0; i < 16; i++) { Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250)); } //Bricks Smeltery.addMelting(multiBrick, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrickFancy, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrick, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrickFancy, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrick, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(multiBrickFancy, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); //Vanilla blocks Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.fenceIron), 0, TConstruct.ingotLiquidValue * 6 / 16); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.pressurePlateIron), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.pressurePlateGold, 4), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.rail), 0, TConstruct.ingotLiquidValue * 6 / 16); Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.railPowered), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railDetector), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railActivator), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Obsidian, new ItemStack(Block.enchantmentTable), 0, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.cauldron), 0, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.hopperBlock), 0, TConstruct.ingotLiquidValue * 5); //Vanilla Armor Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.helmetIron, 1, 0), 50, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.plateIron, 1, 0), 50, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.legsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bootsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.helmetGold, 1, 0), 50, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.plateGold, 1, 0), 50, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.legsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.bootsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.helmetChain, 1, 0), 25, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.plateChain, 1, 0), 50, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.legsChain, 1, 0), 50, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.bootsChain, 1, 0), 25, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.horseArmorIron, 1), 100, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.horseArmorGold, 1), 100, TConstruct.ingotLiquidValue * 8); //Vanilla tools Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.hoeIron, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.swordIron, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shovelIron, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.pickaxeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.axeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.hoeGold, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.swordGold, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.shovelGold, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.pickaxeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.axeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3); } private void addRecipesForDryingRack () { //Drying rack DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0)); DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1)); DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2)); //DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3)); DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4)); DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5)); DryingRackRecipes.addDryingRecipe(new ItemStack(strangeFood, 1, 0), 20 * 60 * 5, new ItemStack(jerky, 1, 6)); DryingRackRecipes.addDryingRecipe(new ItemStack(strangeFood, 1, 1), 20 * 60 * 5, new ItemStack(jerky, 1, 7)); //DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather); } private void addRecipesForChisel () { /* Detailing */ Detailing chiseling = TConstructRegistry.getChiselDetailing(); chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel); chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel); chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel); chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel); chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel); chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel); chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel); chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel); chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel); chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel); //chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel); //chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel); chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel); chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel); chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel); chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel); chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel); chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel); chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel); chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel); chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel); chiseling.addDetailing(materials, 18, multiBrick, 13, chisel); // adding multiBrick / multiBrickFanxy meta 0-13 to list for (int sc = 0; sc < 14; sc++) { chiseling.addDetailing(multiBrick, sc, multiBrickFancy, sc, chisel); } chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel); chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel); /*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/ chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel); chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel); chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel); chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel); chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel); chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel); } void setupToolTabs () { TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255)); TConstructRegistry.blockTab.init(new ItemStack(toolStationWood)); ItemStack tool = new ItemStack(longsword, 1, 0); NBTTagCompound compound = new NBTTagCompound(); compound.setCompoundTag("InfiTool", new NBTTagCompound()); compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2); compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0); compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10); tool.setTagCompound(compound); //TConstruct. TConstructRegistry.toolTab.init(tool); } public void addLoot () { //Item, min, max, weight ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27); tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1)); int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 }; Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead }; for (int partIter = 0; partIter < partTypes.length; partIter++) { for (int typeIter = 0; typeIter < validTypes.length; typeIter++) { tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15)); } } tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30); for (int i = 0; i < 13; i++) { tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20)); } tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40)); } public static String[] liquidNames; public void oreRegistry () { OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1)); OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2)); OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3)); OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4)); OreDictionary.registerOre("oreAluminum", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreAluminium", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0)); OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1)); OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5)); OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2)); OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3)); OreDictionary.registerOre("oreAluminum", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("oreAluminium", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3)); OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4)); OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5)); OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9)); OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10)); OreDictionary.registerOre("ingotAluminum", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("ingotAluminium", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13)); OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAluminiumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15)); OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16)); ensureOreIsRegistered("ingotIron", new ItemStack(Item.ingotIron)); ensureOreIsRegistered("ingotGold", new ItemStack(Item.ingotGold)); OreDictionary.registerOre("ingotObsidian", new ItemStack(materials, 1, 18)); OreDictionary.registerOre("ingotPigIron", new ItemStack(materials, 1, 34)); OreDictionary.registerOre("itemRawRubber", new ItemStack(materials, 1, 36)); OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0)); OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1)); OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2)); OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3)); OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4)); OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5)); OreDictionary.registerOre("blockAluminum", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminium", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAluminiumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8)); OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9)); ensureOreIsRegistered("blockIron", new ItemStack(Block.blockIron)); ensureOreIsRegistered("blockGold", new ItemStack(Block.blockGold)); OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19)); OreDictionary.registerOre("nuggetIron", new ItemStack(oreBerries, 1, 0)); OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20)); OreDictionary.registerOre("nuggetCopper", new ItemStack(oreBerries, 1, 2)); OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21)); OreDictionary.registerOre("nuggetTin", new ItemStack(oreBerries, 1, 3)); OreDictionary.registerOre("nuggetAluminum", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminum", new ItemStack(oreBerries, 1, 4)); OreDictionary.registerOre("nuggetAluminium", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminium", new ItemStack(oreBerries, 1, 4)); OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetAluminiumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27)); OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28)); OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29)); OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30)); OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31)); OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32)); OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33)); OreDictionary.registerOre("nuggetGold", new ItemStack(oreBerries, 1, 1)); ensureOreIsRegistered("nuggetGold", new ItemStack(Item.goldNugget)); OreDictionary.registerOre("nuggetPigIron", new ItemStack(materials, 1, 35)); OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab1, 1, Short.MAX_VALUE)); OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab2, 1, Short.MAX_VALUE)); ensureOreIsRegistered("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1)); ensureOreIsRegistered("stoneMossy", new ItemStack(Block.cobblestoneMossy)); OreDictionary.registerOre("crafterWood", new ItemStack(Block.workbench, 1)); OreDictionary.registerOre("craftingTableWood", new ItemStack(Block.workbench, 1)); OreDictionary.registerOre("torchStone", new ItemStack(stoneTorch)); String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel", "blueslime" }; for (int i = 0; i < matNames.length; i++) OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i)); OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31)); String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow", "glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" }; for (int i = 0; i < 16; i++) { OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i)); } BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg()); BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow()); //Vanilla stuff OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 1)); OreDictionary.registerOre("slimeball", new ItemStack(materials, 1, 36)); OreDictionary.registerOre("glass", new ItemStack(clearGlass)); OreDictionary.registerOre("glass", new ItemStack(Block.glass)); RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.leash)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.leash, 2), "ss ", "sS ", " s", 's', Item.silk, 'S', "slimeball")); } private void ensureOreIsRegistered (String oreName, ItemStack is) { int oreId = OreDictionary.getOreID(is); if (oreId == -1) { OreDictionary.registerOre(oreName, is); } } public static boolean thaumcraftAvailable; public void intermodCommunication () { if (Loader.isModLoaded("Thaumcraft")) { FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13)); } if (Loader.isModLoaded("Mystcraft")) { MystImcHandler.blacklistFluids(); } if (Loader.isModLoaded("BuildCraft|Transport")) { BCImcHandler.registerFacades(); } /* FORESTRY * Edit these strings to change what items are added to the backpacks * Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on * Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder * May add more backpack items later - Spyboticsguy */ if (Loader.isModLoaded("Forestry")) { String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*"; FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems); } if (!Loader.isModLoaded("AppliedEnergistics")) { AEImcHandler.registerForSpatialIO(); } } private static boolean initRecipes; public static void modRecipes () { if (!initRecipes) { initRecipes = true; if (PHConstruct.removeVanillaToolRecipes) { RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold)); } } } public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (objArray[var4] instanceof String[]) { String[] var7 = ((String[]) objArray[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (objArray[var4] instanceof String) { String var11 = (String) objArray[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < objArray.length; var4 += 2) { Character var13 = (Character) objArray[var4]; ItemStack var14 = null; if (objArray[var4 + 1] instanceof Item) { var14 = new ItemStack((Item) objArray[var4 + 1]); } else if (objArray[var4 + 1] instanceof Block) { var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE); } else if (objArray[var4 + 1] instanceof ItemStack) { var14 = (ItemStack) objArray[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack); recipeList.add(0, var17); } public void modIntegration () { ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), ""); /* Natura */ Block taintedSoil = GameRegistry.findBlock("Natura", "soil.tainted"); Block heatSand = GameRegistry.findBlock("Natura", "heatsand"); if (taintedSoil != null && heatSand != null) GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 6), Item.netherStalkSeeds, taintedSoil, heatSand); /*TE3 Flux*/ ItemStack batHardened = GameRegistry.findItemStack("ThermalExpansion", "capacitorHardened", 1); if (batHardened != null) { modFlux.batteries.add(batHardened); } ItemStack basicCell = GameRegistry.findItemStack("ThermalExpansion", "cellBasic", 1); if (basicCell != null) { modFlux.batteries.add(basicCell); } if (batHardened != null) TConstructClientRegistry.registerManualModifier("fluxmod", ironpick.copy(), (ItemStack) batHardened); if (basicCell != null) TConstructClientRegistry.registerManualModifier("fluxmod2", ironpick.copy(), (ItemStack) basicCell); /* Thaumcraft */ Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems"); if (obj != null) { TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools."); thaumcraftAvailable = true; TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true); TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic"); PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31); for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31)); } TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f); TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f); TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F); } else { TConstruct.logger.warning("Thaumcraft not detected."); } if (Loader.isModLoaded("Natura")) { try { Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent"); TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f); } catch (Exception e) { } //No need to handle } ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting(); /* Thermal Expansion 3 Metals */ ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotLead"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotSilver"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotPlatinum"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotInvar"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar } ores = OreDictionary.getOres("ingotElectrum"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum } ores = OreDictionary.getOres("blockNickel"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockLead"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockSilver"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockPlatinum"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockInvar"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockElectrum"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100); } /* Extra Utilities */ ores = OreDictionary.getOres("compressedGravel1x"); if (ores.size() > 0) { basinCasting.addCastingRecipe(new ItemStack(speedBlock, 9), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), ores.get(0), 100); } ores = OreDictionary.getOres("compressedGravel2x"); //Higher won't save properly if (ores.size() > 0) { basinCasting.addCastingRecipe(new ItemStack(speedBlock, 81), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue * 9), ores.get(0), 100); } /* Rubber */ ores = OreDictionary.getOres("itemRubber"); if (ores.size() > 0) { FurnaceRecipes.smelting().addSmelting(materials.itemID, 36, ores.get(0), 0.2f); } } public static Object getStaticItem (String name, String classPackage) { try { Class clazz = Class.forName(classPackage); Field field = clazz.getDeclaredField(name); Object ret = field.get(null); if (ret != null && (ret instanceof ItemStack || ret instanceof Item)) return ret; return null; } catch (Exception e) { TConstruct.logger.warning("Could not find " + name); return null; } } @Override public int getBurnTime (ItemStack fuel) { if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7) return 26400; return 0; } public void addOreDictionarySmelteryRecipes () { List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.Water, FluidType.Stone, FluidType.Ender, FluidType.Glass, FluidType.Slime }); for (FluidType ft : FluidType.values()) { if (exceptions.contains(ft)) continue; // Nuggets Smeltery.addDictionaryMelting("nugget" + ft.toString(), ft, -100, TConstruct.nuggetLiquidValue); // Ingots, Dust registerIngotCasting(ft); Smeltery.addDictionaryMelting("ingot" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue); Smeltery.addDictionaryMelting("dust" + ft.toString(), ft, -75, TConstruct.ingotLiquidValue); // Factorization support Smeltery.addDictionaryMelting("crystalline" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue); // Ores Smeltery.addDictionaryMelting("ore" + ft.toString(), ft, 0, TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre); // NetherOres support Smeltery.addDictionaryMelting("oreNether" + ft.toString(), ft, 75, TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre * 2); // Blocks Smeltery.addDictionaryMelting("block" + ft.toString(), ft, 100, TConstruct.blockLiquidValue); if (ft.isToolpart) { registerPatternMaterial("ingot" + ft.toString(), 2, ft.toString()); registerPatternMaterial("block" + ft.toString(), 18, ft.toString()); } } //Compressed materials for (int i = 1; i <= 8; i++) { Smeltery.addDictionaryMelting("compressedCobblestone" + i + "x", FluidType.Stone, 0, TConstruct.ingotLiquidValue / 18 * (9 ^ i)); } Smeltery.addDictionaryMelting("compressedSand1x", FluidType.Glass, 175, FluidContainerRegistry.BUCKET_VOLUME * 9); registerPatternMaterial("plankWood", 2, "Wood"); registerPatternMaterial("stickWood", 1, "Wood"); registerPatternMaterial("slabWood", 1, "Wood"); registerPatternMaterial("compressedCobblestone1x", 18, "Stone"); } private void registerPatternMaterial (String oreName, int value, String materialName) { for (ItemStack ore : OreDictionary.getOres(oreName)) { PatternBuilder.instance.registerMaterial(ore, value, materialName); } } private void registerIngotCasting (FluidType ft) { ItemStack pattern = new ItemStack(TContent.metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); for (ItemStack ore : OreDictionary.getOres("ingot" + ft.toString())) { tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50); tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenGoldFluid, TConstruct.oreLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50); tableCasting.addCastingRecipe(new ItemStack(ore.itemID, 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80); } } public void addAchievements () { HashMap<String, Achievement> achievements = TAchievements.achievements; achievements.put("tconstruct.beginner", new Achievement(2741, "tconstruct.beginner", 0, 0, manualBook, null).setIndependent().registerAchievement()); achievements.put("tconstruct.pattern", new Achievement(2742, "tconstruct.pattern", 2, 1, blankPattern, achievements.get("tconstruct.beginner")).registerAchievement()); achievements.put("tconstruct.tinkerer", new Achievement(2743, "tconstruct.tinkerer", 2, 2, new ItemStack(titleIcon, 1, 4096), achievements.get("tconstruct.pattern")).registerAchievement()); achievements.put("tconstruct.preparedFight", new Achievement(2744, "tconstruct.preparedFight", 1, 3, new ItemStack(titleIcon, 1, 4097), achievements.get("tconstruct.tinkerer")).registerAchievement()); achievements.put("tconstruct.proTinkerer", new Achievement(2745, "tconstruct.proTinkerer", 4, 4, new ItemStack(titleIcon, 1, 4098), achievements.get("tconstruct.tinkerer")).setSpecial() .registerAchievement()); achievements.put("tconstruct.smelteryMaker", new Achievement(2746, "tconstruct.smelteryMaker", -2, -1, smeltery, achievements.get("tconstruct.beginner")).registerAchievement()); achievements.put("tconstruct.enemySlayer", new Achievement(2747, "tconstruct.enemySlayer", 0, 5, new ItemStack(titleIcon, 1, 4099), achievements.get("tconstruct.preparedFight")).registerAchievement()); achievements.put("tconstruct.dualConvenience", new Achievement(2748, "tconstruct.dualConvenience", 0, 7, new ItemStack(titleIcon, 1, 4100), achievements.get("tconstruct.enemySlayer")) .setSpecial().registerAchievement()); } }
void registerBlocks () { //Tool Station toolStationWood = new ToolStationBlock(PHConstruct.woodStation, Material.wood).setUnlocalizedName("ToolStation"); GameRegistry.registerBlock(toolStationWood, ToolStationItemBlock.class, "ToolStationBlock"); GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation"); GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter"); GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder"); GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper"); toolForge = new ToolForgeBlock(PHConstruct.toolForge, Material.iron).setUnlocalizedName("ToolForge"); GameRegistry.registerBlock(toolForge, MetadataItemBlock.class, "ToolForgeBlock"); GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge"); craftingStationWood = new CraftingStationBlock(PHConstruct.woodCrafter, Material.wood).setUnlocalizedName("CraftingStation"); GameRegistry.registerBlock(craftingStationWood, "CraftingStation"); GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation"); craftingSlabWood = new CraftingSlab(PHConstruct.woodCrafterSlab, Material.wood).setUnlocalizedName("CraftingSlab"); GameRegistry.registerBlock(craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab"); furnaceSlab = new FurnaceSlab(PHConstruct.furnaceSlab, Material.rock).setUnlocalizedName("FurnaceSlab"); GameRegistry.registerBlock(furnaceSlab, "FurnaceSlab"); GameRegistry.registerTileEntity(FurnaceLogic.class, "TConstruct.Furnace"); heldItemBlock = new EquipBlock(PHConstruct.heldItemBlock, Material.wood).setUnlocalizedName("Frypan"); GameRegistry.registerBlock(heldItemBlock, "HeldItemBlock"); GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic"); craftedSoil = new SoilBlock(PHConstruct.craftedSoil).setLightOpacity(0).setUnlocalizedName("TConstruct.Soil"); craftedSoil.stepSound = Block.soundGravelFootstep; GameRegistry.registerBlock(craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil"); searedSlab = new SearedSlab(PHConstruct.searedSlab).setUnlocalizedName("SearedSlab"); searedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(searedSlab, SearedSlabItem.class, "SearedSlab"); speedSlab = new SpeedSlab(PHConstruct.speedSlab).setUnlocalizedName("SpeedSlab"); speedSlab.stepSound = Block.soundStoneFootstep; GameRegistry.registerBlock(speedSlab, SpeedSlabItem.class, "SpeedSlab"); metalBlock = new TMetalBlock(PHConstruct.metalBlock, Material.iron, 10.0F).setUnlocalizedName("tconstruct.metalblock"); metalBlock.stepSound = Block.soundMetalFootstep; GameRegistry.registerBlock(metalBlock, MetalItemBlock.class, "MetalBlock"); meatBlock = new MeatBlock(PHConstruct.meatBlock).setUnlocalizedName("tconstruct.meatblock"); GameRegistry.registerBlock(meatBlock, HamboneItemBlock.class, "MeatBlock"); OreDictionary.registerOre("hambone", new ItemStack(meatBlock)); LanguageRegistry.addName(meatBlock, "Hambone"); GameRegistry.addRecipe(new ItemStack(meatBlock), "mmm", "mbm", "mmm", 'b', new ItemStack(Item.bone), 'm', new ItemStack(Item.porkRaw)); glueBlock = new GlueBlock(PHConstruct.glueBlock).setUnlocalizedName("GlueBlock").setCreativeTab(TConstructRegistry.blockTab); GameRegistry.registerBlock(glueBlock, "GlueBlock"); OreDictionary.registerOre("blockRubber", new ItemStack(glueBlock)); woolSlab1 = new SlabBase(PHConstruct.woolSlab1, Material.cloth, Block.cloth, 0, 8).setUnlocalizedName("cloth"); woolSlab1.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab1, WoolSlab1Item.class, "WoolSlab1"); woolSlab2 = new SlabBase(PHConstruct.woolSlab2, Material.cloth, Block.cloth, 8, 8).setUnlocalizedName("cloth"); woolSlab2.setStepSound(Block.soundClothFootstep).setCreativeTab(CreativeTabs.tabDecorations); GameRegistry.registerBlock(woolSlab2, WoolSlab2Item.class, "WoolSlab2"); //Smeltery smeltery = new SmelteryBlock(PHConstruct.smeltery).setUnlocalizedName("Smeltery"); smelteryNether = new SmelteryBlock(PHConstruct.smelteryNether, "nether").setUnlocalizedName("Smeltery"); GameRegistry.registerBlock(smeltery, SmelteryItemBlock.class, "Smeltery"); GameRegistry.registerBlock(smelteryNether, SmelteryItemBlock.class, "SmelteryNether"); if (PHConstruct.newSmeltery) { GameRegistry.registerTileEntity(AdaptiveSmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(AdaptiveDrainLogic.class, "TConstruct.SmelteryDrain"); } else { GameRegistry.registerTileEntity(SmelteryLogic.class, "TConstruct.Smeltery"); GameRegistry.registerTileEntity(SmelteryDrainLogic.class, "TConstruct.SmelteryDrain"); } GameRegistry.registerTileEntity(MultiServantLogic.class, "TConstruct.Servants"); lavaTank = new LavaTankBlock(PHConstruct.lavaTank).setStepSound(Block.soundGlassFootstep).setUnlocalizedName("LavaTank"); lavaTankNether = new LavaTankBlock(PHConstruct.lavaTankNether, "nether").setStepSound(Block.soundGlassFootstep).setUnlocalizedName("LavaTank"); GameRegistry.registerBlock(lavaTank, LavaTankItemBlock.class, "LavaTank"); GameRegistry.registerBlock(lavaTankNether, LavaTankItemBlock.class, "LavaTankNether"); GameRegistry.registerTileEntity(LavaTankLogic.class, "TConstruct.LavaTank"); searedBlock = new SearedBlock(PHConstruct.searedTable).setUnlocalizedName("SearedBlock"); searedBlockNether = new SearedBlock(PHConstruct.searedTableNether, "nether").setUnlocalizedName("SearedBlock"); GameRegistry.registerBlock(searedBlock, SearedTableItemBlock.class, "SearedBlock"); GameRegistry.registerBlock(searedBlockNether, SearedTableItemBlock.class, "SearedBlockNether"); GameRegistry.registerTileEntity(CastingTableLogic.class, "CastingTable"); GameRegistry.registerTileEntity(FaucetLogic.class, "Faucet"); GameRegistry.registerTileEntity(CastingBasinLogic.class, "CastingBasin"); castingChannel = (new CastingChannelBlock(PHConstruct.castingChannel)).setUnlocalizedName("CastingChannel"); GameRegistry.registerBlock(castingChannel, CastingChannelItem.class, "CastingChannel"); GameRegistry.registerTileEntity(CastingChannelLogic.class, "CastingChannel"); tankAir = new TankAirBlock(PHConstruct.airTank, Material.leaves).setBlockUnbreakable().setUnlocalizedName("tconstruct.tank.air"); GameRegistry.registerBlock(tankAir, "TankAir"); GameRegistry.registerTileEntity(TankAirLogic.class, "tconstruct.tank.air"); //Traps landmine = new BlockLandmine(PHConstruct.landmine).setHardness(0.5F).setResistance(0F).setStepSound(Block.soundMetalFootstep).setCreativeTab(CreativeTabs.tabRedstone) .setUnlocalizedName("landmine"); GameRegistry.registerBlock(landmine, ItemBlockLandmine.class, "Redstone.Landmine"); GameRegistry.registerTileEntity(TileEntityLandmine.class, "Landmine"); punji = new Punji(PHConstruct.punji).setUnlocalizedName("trap.punji"); GameRegistry.registerBlock(punji, "trap.punji"); barricadeOak = new BarricadeBlock(PHConstruct.barricadeOak, Block.wood, 0).setUnlocalizedName("trap.barricade.oak"); GameRegistry.registerBlock(barricadeOak, BarricadeItem.class, "trap.barricade.oak"); barricadeSpruce = new BarricadeBlock(PHConstruct.barricadeSpruce, Block.wood, 1).setUnlocalizedName("trap.barricade.spruce"); GameRegistry.registerBlock(barricadeSpruce, BarricadeItem.class, "trap.barricade.spruce"); barricadeBirch = new BarricadeBlock(PHConstruct.barricadeBirch, Block.wood, 2).setUnlocalizedName("trap.barricade.birch"); GameRegistry.registerBlock(barricadeBirch, BarricadeItem.class, "trap.barricade.birch"); barricadeJungle = new BarricadeBlock(PHConstruct.barricadeJungle, Block.wood, 3).setUnlocalizedName("trap.barricade.jungle"); GameRegistry.registerBlock(barricadeJungle, BarricadeItem.class, "trap.barricade.jungle"); slimeExplosive = new SlimeExplosive(PHConstruct.slimeExplosive).setHardness(0.0F).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("explosive.slime"); GameRegistry.registerBlock(slimeExplosive, MetadataItemBlock.class, "explosive.slime"); dryingRack = new DryingRack(PHConstruct.dryingRack).setUnlocalizedName("Armor.DryingRack"); GameRegistry.registerBlock(dryingRack, "Armor.DryingRack"); GameRegistry.registerTileEntity(DryingRackLogic.class, "Armor.DryingRack"); //Liquids liquidMetal = new MaterialLiquid(MapColor.tntColor); moltenIronFluid = new Fluid("iron.molten"); if (!FluidRegistry.registerFluid(moltenIronFluid)) moltenIronFluid = FluidRegistry.getFluid("iron.molten"); moltenIron = new TConstructFluid(PHConstruct.moltenIron, moltenIronFluid, Material.lava, "liquid_iron").setUnlocalizedName("metal.molten.iron"); GameRegistry.registerBlock(moltenIron, "metal.molten.iron"); fluids[0] = moltenIronFluid; fluidBlocks[0] = moltenIron; moltenIronFluid.setBlockID(moltenIron).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenIronFluid, 1000), new ItemStack(buckets, 1, 0), new ItemStack(Item.bucketEmpty))); moltenGoldFluid = new Fluid("gold.molten"); if (!FluidRegistry.registerFluid(moltenGoldFluid)) moltenGoldFluid = FluidRegistry.getFluid("gold.molten"); moltenGold = new TConstructFluid(PHConstruct.moltenGold, moltenGoldFluid, Material.lava, "liquid_gold").setUnlocalizedName("metal.molten.gold"); GameRegistry.registerBlock(moltenGold, "metal.molten.gold"); fluids[1] = moltenGoldFluid; fluidBlocks[1] = moltenGold; moltenGoldFluid.setBlockID(moltenGold).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGoldFluid, 1000), new ItemStack(buckets, 1, 1), new ItemStack(Item.bucketEmpty))); moltenCopperFluid = new Fluid("copper.molten"); if (!FluidRegistry.registerFluid(moltenCopperFluid)) moltenCopperFluid = FluidRegistry.getFluid("copper.molten"); moltenCopper = new TConstructFluid(PHConstruct.moltenCopper, moltenCopperFluid, Material.lava, "liquid_copper").setUnlocalizedName("metal.molten.copper"); GameRegistry.registerBlock(moltenCopper, "metal.molten.copper"); fluids[2] = moltenCopperFluid; fluidBlocks[2] = moltenCopper; moltenCopperFluid.setBlockID(moltenCopper).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCopperFluid, 1000), new ItemStack(buckets, 1, 2), new ItemStack(Item.bucketEmpty))); moltenTinFluid = new Fluid("tin.molten"); if (!FluidRegistry.registerFluid(moltenTinFluid)) moltenTinFluid = FluidRegistry.getFluid("tin.molten"); moltenTin = new TConstructFluid(PHConstruct.moltenTin, moltenTinFluid, Material.lava, "liquid_tin").setUnlocalizedName("metal.molten.tin"); GameRegistry.registerBlock(moltenTin, "metal.molten.tin"); fluids[3] = moltenTinFluid; fluidBlocks[3] = moltenTin; moltenTinFluid.setBlockID(moltenTin).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenTinFluid, 1000), new ItemStack(buckets, 1, 3), new ItemStack(Item.bucketEmpty))); moltenAluminumFluid = new Fluid("aluminum.molten"); if (!FluidRegistry.registerFluid(moltenAluminumFluid)) moltenAluminumFluid = FluidRegistry.getFluid("aluminum.molten"); moltenAluminum = new TConstructFluid(PHConstruct.moltenAluminum, moltenAluminumFluid, Material.lava, "liquid_aluminum").setUnlocalizedName("metal.molten.aluminum"); GameRegistry.registerBlock(moltenAluminum, "metal.molten.aluminum"); fluids[4] = moltenAluminumFluid; fluidBlocks[4] = moltenAluminum; moltenAluminumFluid.setBlockID(moltenAluminum).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAluminumFluid, 1000), new ItemStack(buckets, 1, 4), new ItemStack(Item.bucketEmpty))); moltenCobaltFluid = new Fluid("cobalt.molten"); if (!FluidRegistry.registerFluid(moltenCobaltFluid)) moltenCobaltFluid = FluidRegistry.getFluid("cobalt.molten"); moltenCobalt = new TConstructFluid(PHConstruct.moltenCobalt, moltenCobaltFluid, Material.lava, "liquid_cobalt").setUnlocalizedName("metal.molten.cobalt"); GameRegistry.registerBlock(moltenCobalt, "metal.molten.cobalt"); fluids[5] = moltenCobaltFluid; fluidBlocks[5] = moltenCobalt; moltenCobaltFluid.setBlockID(moltenCobalt).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenCobaltFluid, 1000), new ItemStack(buckets, 1, 5), new ItemStack(Item.bucketEmpty))); moltenArditeFluid = new Fluid("ardite.molten"); if (!FluidRegistry.registerFluid(moltenArditeFluid)) moltenArditeFluid = FluidRegistry.getFluid("ardite.molten"); moltenArdite = new TConstructFluid(PHConstruct.moltenArdite, moltenArditeFluid, Material.lava, "liquid_ardite").setUnlocalizedName("metal.molten.ardite"); GameRegistry.registerBlock(moltenArdite, "metal.molten.ardite"); fluids[6] = moltenArditeFluid; fluidBlocks[6] = moltenArdite; moltenArditeFluid.setBlockID(moltenArdite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenArditeFluid, 1000), new ItemStack(buckets, 1, 6), new ItemStack(Item.bucketEmpty))); moltenBronzeFluid = new Fluid("bronze.molten"); if (!FluidRegistry.registerFluid(moltenBronzeFluid)) moltenBronzeFluid = FluidRegistry.getFluid("bronze.molten"); moltenBronze = new TConstructFluid(PHConstruct.moltenBronze, moltenBronzeFluid, Material.lava, "liquid_bronze").setUnlocalizedName("metal.molten.bronze"); GameRegistry.registerBlock(moltenBronze, "metal.molten.bronze"); fluids[7] = moltenBronzeFluid; fluidBlocks[7] = moltenBronze; moltenBronzeFluid.setBlockID(moltenBronze).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenBronzeFluid, 1000), new ItemStack(buckets, 1, 7), new ItemStack(Item.bucketEmpty))); moltenAlubrassFluid = new Fluid("aluminumbrass.molten"); if (!FluidRegistry.registerFluid(moltenAlubrassFluid)) moltenAlubrassFluid = FluidRegistry.getFluid("aluminumbrass.molten"); moltenAlubrass = new TConstructFluid(PHConstruct.moltenAlubrass, moltenAlubrassFluid, Material.lava, "liquid_alubrass").setUnlocalizedName("metal.molten.alubrass"); GameRegistry.registerBlock(moltenAlubrass, "metal.molten.alubrass"); fluids[8] = moltenAlubrassFluid; fluidBlocks[8] = moltenAlubrass; moltenAlubrassFluid.setBlockID(moltenAlubrass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlubrassFluid, 1000), new ItemStack(buckets, 1, 8), new ItemStack(Item.bucketEmpty))); moltenManyullynFluid = new Fluid("manyullyn.molten"); if (!FluidRegistry.registerFluid(moltenManyullynFluid)) moltenManyullynFluid = FluidRegistry.getFluid("manyullyn.molten"); moltenManyullyn = new TConstructFluid(PHConstruct.moltenManyullyn, moltenManyullynFluid, Material.lava, "liquid_manyullyn").setUnlocalizedName("metal.molten.manyullyn"); GameRegistry.registerBlock(moltenManyullyn, "metal.molten.manyullyn"); fluids[9] = moltenManyullynFluid; fluidBlocks[9] = moltenManyullyn; moltenManyullynFluid.setBlockID(moltenManyullyn).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenManyullynFluid, 1000), new ItemStack(buckets, 1, 9), new ItemStack(Item.bucketEmpty))); moltenAlumiteFluid = new Fluid("alumite.molten"); if (!FluidRegistry.registerFluid(moltenAlumiteFluid)) moltenAlumiteFluid = FluidRegistry.getFluid("alumite.molten"); moltenAlumite = new TConstructFluid(PHConstruct.moltenAlumite, moltenAlumiteFluid, Material.lava, "liquid_alumite").setUnlocalizedName("metal.molten.alumite"); GameRegistry.registerBlock(moltenAlumite, "metal.molten.alumite"); fluids[10] = moltenAlumiteFluid; fluidBlocks[10] = moltenAlumite; moltenAlumiteFluid.setBlockID(moltenAlumite).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenAlumiteFluid, 1000), new ItemStack(buckets, 1, 10), new ItemStack(Item.bucketEmpty))); moltenObsidianFluid = new Fluid("obsidian.molten"); if (!FluidRegistry.registerFluid(moltenObsidianFluid)) moltenObsidianFluid = FluidRegistry.getFluid("obsidian.molten"); moltenObsidian = new TConstructFluid(PHConstruct.moltenObsidian, moltenObsidianFluid, Material.lava, "liquid_obsidian").setUnlocalizedName("metal.molten.obsidian"); GameRegistry.registerBlock(moltenObsidian, "metal.molten.obsidian"); fluids[11] = moltenObsidianFluid; fluidBlocks[11] = moltenObsidian; moltenObsidianFluid.setBlockID(moltenObsidian).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenObsidianFluid, 1000), new ItemStack(buckets, 1, 11), new ItemStack(Item.bucketEmpty))); moltenSteelFluid = new Fluid("steel.molten"); if (!FluidRegistry.registerFluid(moltenSteelFluid)) moltenSteelFluid = FluidRegistry.getFluid("steel.molten"); moltenSteel = new TConstructFluid(PHConstruct.moltenSteel, moltenSteelFluid, Material.lava, "liquid_steel").setUnlocalizedName("metal.molten.steel"); GameRegistry.registerBlock(moltenSteel, "metal.molten.steel"); fluids[12] = moltenSteelFluid; fluidBlocks[12] = moltenSteel; moltenSteelFluid.setBlockID(moltenSteel).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSteelFluid, 1000), new ItemStack(buckets, 1, 12), new ItemStack(Item.bucketEmpty))); moltenGlassFluid = new Fluid("glass.molten"); if (!FluidRegistry.registerFluid(moltenGlassFluid)) moltenGlassFluid = FluidRegistry.getFluid("glass.molten"); moltenGlass = new TConstructFluid(PHConstruct.moltenGlass, moltenGlassFluid, Material.lava, "liquid_glass", true).setUnlocalizedName("metal.molten.glass"); GameRegistry.registerBlock(moltenGlass, "metal.molten.glass"); fluids[13] = moltenGlassFluid; fluidBlocks[13] = moltenGlass; moltenGlassFluid.setBlockID(moltenGlass).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenGlassFluid, 1000), new ItemStack(buckets, 1, 13), new ItemStack(Item.bucketEmpty))); moltenStoneFluid = new Fluid("stone.seared"); if (!FluidRegistry.registerFluid(moltenStoneFluid)) moltenStoneFluid = FluidRegistry.getFluid("stone.seared"); moltenStone = new TConstructFluid(PHConstruct.moltenStone, moltenStoneFluid, Material.lava, "liquid_stone").setUnlocalizedName("molten.stone"); GameRegistry.registerBlock(moltenStone, "molten.stone"); fluids[14] = moltenStoneFluid; fluidBlocks[14] = moltenStone; moltenStoneFluid.setBlockID(moltenStone).setLuminosity(12).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenStoneFluid, 1000), new ItemStack(buckets, 1, 14), new ItemStack(Item.bucketEmpty))); moltenEmeraldFluid = new Fluid("emerald.liquid"); if (!FluidRegistry.registerFluid(moltenEmeraldFluid)) moltenEmeraldFluid = FluidRegistry.getFluid("emerald.liquid"); moltenEmerald = new TConstructFluid(PHConstruct.moltenEmerald, moltenEmeraldFluid, Material.water, "liquid_villager").setUnlocalizedName("molten.emerald"); GameRegistry.registerBlock(moltenEmerald, "molten.emerald"); fluids[15] = moltenEmeraldFluid; fluidBlocks[15] = moltenEmerald; moltenEmeraldFluid.setBlockID(moltenEmerald).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEmeraldFluid, 1000), new ItemStack(buckets, 1, 15), new ItemStack(Item.bucketEmpty))); bloodFluid = new Fluid("blood"); if (!FluidRegistry.registerFluid(bloodFluid)) bloodFluid = FluidRegistry.getFluid("blood"); blood = new BloodBlock(PHConstruct.blood, bloodFluid, Material.water, "liquid_cow").setUnlocalizedName("liquid.blood"); GameRegistry.registerBlock(blood, "liquid.blood"); fluids[16] = bloodFluid; fluidBlocks[16] = blood; bloodFluid.setBlockID(blood).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(bloodFluid, 1000), new ItemStack(buckets, 1, 16), new ItemStack(Item.bucketEmpty))); moltenNickelFluid = new Fluid("nickel.molten"); if (!FluidRegistry.registerFluid(moltenNickelFluid)) moltenNickelFluid = FluidRegistry.getFluid("nickel.molten"); moltenNickel = new TConstructFluid(PHConstruct.moltenNickel, moltenNickelFluid, Material.lava, "liquid_ferrous").setUnlocalizedName("metal.molten.nickel"); GameRegistry.registerBlock(moltenNickel, "metal.molten.nickel"); fluids[17] = moltenNickelFluid; fluidBlocks[17] = moltenNickel; moltenNickelFluid.setBlockID(moltenNickel).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenNickelFluid, 1000), new ItemStack(buckets, 1, 17), new ItemStack(Item.bucketEmpty))); moltenLeadFluid = new Fluid("lead.molten"); if (!FluidRegistry.registerFluid(moltenLeadFluid)) moltenLeadFluid = FluidRegistry.getFluid("lead.molten"); moltenLead = new TConstructFluid(PHConstruct.moltenLead, moltenLeadFluid, Material.lava, "liquid_lead").setUnlocalizedName("metal.molten.lead"); GameRegistry.registerBlock(moltenLead, "metal.molten.lead"); fluids[18] = moltenLeadFluid; fluidBlocks[18] = moltenLead; moltenLeadFluid.setBlockID(moltenLead).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenLeadFluid, 1000), new ItemStack(buckets, 1, 18), new ItemStack(Item.bucketEmpty))); moltenSilverFluid = new Fluid("silver.molten"); if (!FluidRegistry.registerFluid(moltenSilverFluid)) moltenSilverFluid = FluidRegistry.getFluid("silver.molten"); moltenSilver = new TConstructFluid(PHConstruct.moltenSilver, moltenSilverFluid, Material.lava, "liquid_silver").setUnlocalizedName("metal.molten.silver"); GameRegistry.registerBlock(moltenSilver, "metal.molten.silver"); fluids[19] = moltenSilverFluid; fluidBlocks[19] = moltenSilver; moltenSilverFluid.setBlockID(moltenSilver).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenSilverFluid, 1000), new ItemStack(buckets, 1, 19), new ItemStack(Item.bucketEmpty))); moltenShinyFluid = new Fluid("platinum.molten"); if (!FluidRegistry.registerFluid(moltenShinyFluid)) moltenShinyFluid = FluidRegistry.getFluid("platinum.molten"); moltenShiny = new TConstructFluid(PHConstruct.moltenShiny, moltenShinyFluid, Material.lava, "liquid_shiny").setUnlocalizedName("metal.molten.shiny"); GameRegistry.registerBlock(moltenShiny, "metal.molten.shiny"); fluids[20] = moltenShinyFluid; fluidBlocks[20] = moltenShiny; moltenShinyFluid.setBlockID(moltenShiny).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenShinyFluid, 1000), new ItemStack(buckets, 1, 20), new ItemStack(Item.bucketEmpty))); moltenInvarFluid = new Fluid("invar.molten"); if (!FluidRegistry.registerFluid(moltenInvarFluid)) moltenInvarFluid = FluidRegistry.getFluid("invar.molten"); moltenInvar = new TConstructFluid(PHConstruct.moltenInvar, moltenInvarFluid, Material.lava, "liquid_invar").setUnlocalizedName("metal.molten.invar"); GameRegistry.registerBlock(moltenInvar, "metal.molten.invar"); fluids[21] = moltenInvarFluid; fluidBlocks[21] = moltenInvar; moltenInvarFluid.setBlockID(moltenInvar).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenInvarFluid, 1000), new ItemStack(buckets, 1, 21), new ItemStack(Item.bucketEmpty))); moltenElectrumFluid = new Fluid("electrum.molten"); if (!FluidRegistry.registerFluid(moltenElectrumFluid)) moltenElectrumFluid = FluidRegistry.getFluid("electrum.molten"); moltenElectrum = new TConstructFluid(PHConstruct.moltenElectrum, moltenElectrumFluid, Material.lava, "liquid_electrum").setUnlocalizedName("metal.molten.electrum"); GameRegistry.registerBlock(moltenElectrum, "metal.molten.electrum"); fluids[22] = moltenElectrumFluid; fluidBlocks[22] = moltenElectrum; moltenElectrumFluid.setBlockID(moltenElectrum).setDensity(3000).setViscosity(6000).setTemperature(1300); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenElectrumFluid, 1000), new ItemStack(buckets, 1, 22), new ItemStack(Item.bucketEmpty))); moltenEnderFluid = new Fluid("ender"); if (!FluidRegistry.registerFluid(moltenEnderFluid)) { moltenEnderFluid = FluidRegistry.getFluid("ender"); moltenEnder = Block.blocksList[moltenEnderFluid.getBlockID()]; if (moltenEnder == null) TConstruct.logger.info("Molten ender block missing!"); } else { moltenEnder = new TConstructFluid(PHConstruct.moltenEnder, moltenEnderFluid, Material.water, "liquid_ender").setUnlocalizedName("fluid.ender"); GameRegistry.registerBlock(moltenEnder, "fluid.ender"); moltenEnderFluid.setBlockID(moltenEnder).setDensity(3000).setViscosity(6000); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(moltenEnderFluid, 1000), new ItemStack(buckets, 1, 23), new ItemStack(Item.bucketEmpty))); } fluids[23] = moltenEnderFluid; fluidBlocks[23] = moltenEnder; //Slime slimeStep = new StepSoundSlime("mob.slime", 1.0f, 1.0f); blueSlimeFluid = new Fluid("slime.blue"); if (!FluidRegistry.registerFluid(blueSlimeFluid)) blueSlimeFluid = FluidRegistry.getFluid("slime.blue"); slimePool = new SlimeFluid(PHConstruct.slimePoolBlue, blueSlimeFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.slime"); GameRegistry.registerBlock(slimePool, "liquid.slime"); fluids[24] = blueSlimeFluid; fluidBlocks[24] = slimePool; blueSlimeFluid.setBlockID(slimePool); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(blueSlimeFluid, 1000), new ItemStack(buckets, 1, 24), new ItemStack(Item.bucketEmpty))); //Glue glueFluid = new Fluid("glue").setDensity(6000).setViscosity(6000).setTemperature(200); if (!FluidRegistry.registerFluid(glueFluid)) glueFluid = FluidRegistry.getFluid("glue"); glueFluidBlock = new GlueFluid(PHConstruct.glueFluidBlock, glueFluid, Material.water).setCreativeTab(TConstructRegistry.blockTab).setStepSound(slimeStep).setUnlocalizedName("liquid.glue"); GameRegistry.registerBlock(glueFluidBlock, "liquid.glue"); fluids[25] = glueFluid; fluidBlocks[25] = glueFluidBlock; glueFluid.setBlockID(glueFluidBlock); FluidContainerRegistry.registerFluidContainer(new FluidContainerData(new FluidStack(glueFluid, 1000), new ItemStack(buckets, 1, 26), new ItemStack(Item.bucketEmpty))); pigIronFluid = new Fluid("pigiron.molten"); if (!FluidRegistry.registerFluid(pigIronFluid)) pigIronFluid = FluidRegistry.getFluid("pigiron.molten"); else pigIronFluid.setDensity(3000).setViscosity(6000).setTemperature(1300); fluids[26] = pigIronFluid; slimeGel = new SlimeGel(PHConstruct.slimeGel).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.gel"); GameRegistry.registerBlock(slimeGel, SlimeGelItemBlock.class, "slime.gel"); slimeGrass = new SlimeGrass(PHConstruct.slimeGrass).setStepSound(Block.soundGrassFootstep).setLightOpacity(0).setUnlocalizedName("slime.grass"); GameRegistry.registerBlock(slimeGrass, SlimeGrassItemBlock.class, "slime.grass"); slimeTallGrass = new SlimeTallGrass(PHConstruct.slimeTallGrass).setStepSound(Block.soundGrassFootstep).setUnlocalizedName("slime.grass.tall"); GameRegistry.registerBlock(slimeTallGrass, SlimeTallGrassItem.class, "slime.grass.tall"); slimeLeaves = (SlimeLeaves) new SlimeLeaves(PHConstruct.slimeLeaves).setStepSound(slimeStep).setLightOpacity(0).setUnlocalizedName("slime.leaves"); GameRegistry.registerBlock(slimeLeaves, SlimeLeavesItemBlock.class, "slime.leaves"); slimeSapling = (SlimeSapling) new SlimeSapling(PHConstruct.slimeSapling).setStepSound(slimeStep).setUnlocalizedName("slime.sapling"); GameRegistry.registerBlock(slimeSapling, SlimeSaplingItemBlock.class, "slime.sapling"); slimeChannel = new ConveyorBase(PHConstruct.slimeChannel, Material.water, "greencurrent").setHardness(0.3f).setStepSound(slimeStep).setUnlocalizedName("slime.channel"); GameRegistry.registerBlock(slimeChannel, "slime.channel"); TConstructRegistry.drawbridgeState[slimeChannel.blockID] = 1; bloodChannel = new ConveyorBase(PHConstruct.bloodChannel, Material.water, "liquid_cow").setHardness(0.3f).setStepSound(slimeStep).setUnlocalizedName("blood.channel"); GameRegistry.registerBlock(bloodChannel, "blood.channel"); TConstructRegistry.drawbridgeState[bloodChannel.blockID] = 1; slimePad = new SlimePad(PHConstruct.slimePad, Material.cloth).setStepSound(slimeStep).setHardness(0.3f).setUnlocalizedName("slime.pad"); GameRegistry.registerBlock(slimePad, "slime.pad"); TConstructRegistry.drawbridgeState[slimePad.blockID] = 1; //Decoration stoneTorch = new StoneTorch(PHConstruct.stoneTorch).setUnlocalizedName("decoration.stonetorch"); GameRegistry.registerBlock(stoneTorch, "decoration.stonetorch"); stoneLadder = new StoneLadder(PHConstruct.stoneLadder).setUnlocalizedName("decoration.stoneladder"); GameRegistry.registerBlock(stoneLadder, "decoration.stoneladder"); multiBrick = new MultiBrick(PHConstruct.multiBrick).setUnlocalizedName("Decoration.Brick"); GameRegistry.registerBlock(multiBrick, MultiBrickItem.class, "decoration.multibrick"); multiBrickFancy = new MultiBrickFancy(PHConstruct.multiBrickFancy).setUnlocalizedName("Decoration.BrickFancy"); GameRegistry.registerBlock(multiBrickFancy, MultiBrickFancyItem.class, "decoration.multibrickfancy"); //Ores String[] berryOres = new String[] { "berry_iron", "berry_gold", "berry_copper", "berry_tin", "berry_iron_ripe", "berry_gold_ripe", "berry_copper_ripe", "berry_tin_ripe" }; oreBerry = (OreberryBush) new OreberryBush(PHConstruct.oreBerry, berryOres, 0, 4, new String[] { "oreIron", "oreGold", "oreCopper", "oreTin" }).setUnlocalizedName("ore.berries.one"); GameRegistry.registerBlock(oreBerry, OreberryBushItem.class, "ore.berries.one"); String[] berryOresTwo = new String[] { "berry_aluminum", "berry_essence", "", "", "berry_aluminum_ripe", "berry_essence_ripe", "", "" }; oreBerrySecond = (OreberryBush) new OreberryBushEssence(PHConstruct.oreBerrySecond, berryOresTwo, 4, 2, new String[] { "oreAluminum", "oreSilver" }).setUnlocalizedName("ore.berries.two"); GameRegistry.registerBlock(oreBerrySecond, OreberryBushSecondItem.class, "ore.berries.two"); String[] oreTypes = new String[] { "nether_slag", "nether_cobalt", "nether_ardite", "ore_copper", "ore_tin", "ore_aluminum", "ore_slag" }; oreSlag = new MetalOre(PHConstruct.oreSlag, Material.rock, 10.0F, oreTypes).setUnlocalizedName("tconstruct.stoneore"); GameRegistry.registerBlock(oreSlag, MetalOreItemBlock.class, "SearedBrick"); MinecraftForge.setBlockHarvestLevel(oreSlag, 1, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 2, "pickaxe", 4); MinecraftForge.setBlockHarvestLevel(oreSlag, 3, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 4, "pickaxe", 1); MinecraftForge.setBlockHarvestLevel(oreSlag, 5, "pickaxe", 1); oreGravel = new GravelOre(PHConstruct.oreGravel).setUnlocalizedName("GravelOre").setUnlocalizedName("tconstruct.gravelore"); GameRegistry.registerBlock(oreGravel, GravelOreItem.class, "GravelOre"); MinecraftForge.setBlockHarvestLevel(oreGravel, 0, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 1, "shovel", 2); MinecraftForge.setBlockHarvestLevel(oreGravel, 2, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 3, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 4, "shovel", 1); MinecraftForge.setBlockHarvestLevel(oreGravel, 5, "shovel", 4); speedBlock = new SpeedBlock(PHConstruct.speedBlock).setUnlocalizedName("SpeedBlock"); GameRegistry.registerBlock(speedBlock, SpeedBlockItem.class, "SpeedBlock"); //Glass clearGlass = new GlassBlockConnected(PHConstruct.glass, "clear", false).setUnlocalizedName("GlassBlock"); clearGlass.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(clearGlass, GlassBlockItem.class, "GlassBlock"); glassPane = new GlassPaneConnected(PHConstruct.glassPane, "clear", false); GameRegistry.registerBlock(glassPane, GlassPaneItem.class, "GlassPane"); stainedGlassClear = new GlassBlockConnectedMeta(PHConstruct.stainedGlassClear, "stained", true, "white", "orange", "magenta", "light_blue", "yellow", "lime", "pink", "gray", "light_gray", "cyan", "purple", "blue", "brown", "green", "red", "black").setUnlocalizedName("GlassBlock.StainedClear"); stainedGlassClear.stepSound = Block.soundGlassFootstep; GameRegistry.registerBlock(stainedGlassClear, StainedGlassClearItem.class, "GlassBlock.StainedClear"); stainedGlassClearPane = new GlassPaneStained(PHConstruct.stainedGlassClearPane); GameRegistry.registerBlock(stainedGlassClearPane, StainedGlassClearPaneItem.class, "GlassPaneClearStained"); //Rail woodenRail = new WoodRail(PHConstruct.woodenRail).setStepSound(Block.soundWoodFootstep).setCreativeTab(TConstructRegistry.blockTab).setUnlocalizedName("rail.wood"); GameRegistry.registerBlock(woodenRail, "rail.wood"); } void registerItems () { titleIcon = new TitleIcon(PHConstruct.uselessItem).setUnlocalizedName("tconstruct.titleicon"); GameRegistry.registerItem(titleIcon, "titleIcon"); String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" }; blankPattern = new CraftingItem(PHConstruct.blankPattern, blanks, blanks, "materials/").setUnlocalizedName("tconstruct.Pattern"); GameRegistry.registerItem(blankPattern, "blankPattern"); materials = new MaterialItem(PHConstruct.materials).setUnlocalizedName("tconstruct.Materials"); toolRod = new ToolPart(PHConstruct.toolRod, "_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod"); toolShard = new ToolShard(PHConstruct.toolShard, "_chunk").setUnlocalizedName("tconstruct.ToolShard"); woodPattern = new Pattern(PHConstruct.woodPattern, "pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern"); metalPattern = new MetalPattern(PHConstruct.metalPattern, "cast_", "materials/").setUnlocalizedName("tconstruct.MetalPattern"); //armorPattern = new ArmorPattern(PHConstruct.armorPattern, "armorcast_", "materials/").setUnlocalizedName("tconstruct.ArmorPattern"); GameRegistry.registerItem(materials, "materials"); GameRegistry.registerItem(woodPattern, "woodPattern"); GameRegistry.registerItem(metalPattern, "metalPattern"); //GameRegistry.registerItem(armorPattern, "armorPattern"); TConstructRegistry.addItemToDirectory("blankPattern", blankPattern); TConstructRegistry.addItemToDirectory("woodPattern", woodPattern); TConstructRegistry.addItemToDirectory("metalPattern", metalPattern); //TConstructRegistry.addItemToDirectory("armorPattern", armorPattern); String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead", "knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" }; for (int i = 1; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(woodPattern, 1, i)); } for (int i = 0; i < patternTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Cast", new ItemStack(metalPattern, 1, i)); } /*String[] armorPartTypes = { "helmet", "chestplate", "leggings", "boots" }; for (int i = 1; i < armorPartTypes.length; i++) { TConstructRegistry.addItemStackToDirectory(armorPartTypes[i] + "Cast", new ItemStack(armorPattern, 1, i)); }*/ manualBook = new Manual(PHConstruct.manual); GameRegistry.registerItem(manualBook, "manualBook"); buckets = new FilledBucket(PHConstruct.buckets); GameRegistry.registerItem(buckets, "buckets"); pickaxe = new Pickaxe(PHConstruct.pickaxe); shovel = new Shovel(PHConstruct.shovel); hatchet = new Hatchet(PHConstruct.axe); broadsword = new Broadsword(PHConstruct.broadsword); longsword = new Longsword(PHConstruct.longsword); rapier = new Rapier(PHConstruct.rapier); dagger = new Dagger(PHConstruct.dagger); cutlass = new Cutlass(PHConstruct.cutlass); frypan = new FryingPan(PHConstruct.frypan); battlesign = new BattleSign(PHConstruct.battlesign); mattock = new Mattock(PHConstruct.mattock); chisel = new Chisel(PHConstruct.chisel); lumberaxe = new LumberAxe(PHConstruct.lumberaxe); cleaver = new Cleaver(PHConstruct.cleaver); scythe = new Scythe(PHConstruct.scythe); excavator = new Excavator(PHConstruct.excavator); hammer = new Hammer(PHConstruct.hammer); battleaxe = new Battleaxe(PHConstruct.battleaxe); shortbow = new Shortbow(PHConstruct.shortbow); arrow = new Arrow(PHConstruct.arrow); Item[] tools = { pickaxe, shovel, hatchet, broadsword, longsword, rapier, dagger, cutlass, frypan, battlesign, mattock, chisel, lumberaxe, cleaver, scythe, excavator, hammer, battleaxe, shortbow, arrow }; String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver", "scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" }; for (int i = 0; i < tools.length; i++) { GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]); } potionLauncher = new PotionLauncher(PHConstruct.potionLauncher).setUnlocalizedName("tconstruct.PotionLauncher"); GameRegistry.registerItem(potionLauncher, "potionLauncher"); pickaxeHead = new ToolPart(PHConstruct.pickaxeHead, "_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead"); shovelHead = new ToolPart(PHConstruct.shovelHead, "_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead"); hatchetHead = new ToolPart(PHConstruct.axeHead, "_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead"); binding = new ToolPart(PHConstruct.binding, "_binding", "Binding").setUnlocalizedName("tconstruct.Binding"); toughBinding = new ToolPart(PHConstruct.toughBinding, "_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding"); toughRod = new ToolPart(PHConstruct.toughRod, "_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod"); largePlate = new ToolPart(PHConstruct.largePlate, "_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate"); swordBlade = new ToolPart(PHConstruct.swordBlade, "_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade"); wideGuard = new ToolPart(PHConstruct.largeGuard, "_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard"); handGuard = new ToolPart(PHConstruct.medGuard, "_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard"); crossbar = new ToolPart(PHConstruct.crossbar, "_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar"); knifeBlade = new ToolPart(PHConstruct.knifeBlade, "_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade"); fullGuard = new ToolPartHidden(PHConstruct.fullGuard, "_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard"); frypanHead = new ToolPart(PHConstruct.frypanHead, "_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead"); signHead = new ToolPart(PHConstruct.signHead, "_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead"); chiselHead = new ToolPart(PHConstruct.chiselHead, "_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead"); scytheBlade = new ToolPart(PHConstruct.scytheBlade, "_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade"); broadAxeHead = new ToolPart(PHConstruct.lumberHead, "_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead"); excavatorHead = new ToolPart(PHConstruct.excavatorHead, "_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead"); largeSwordBlade = new ToolPart(PHConstruct.largeSwordBlade, "_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade"); hammerHead = new ToolPart(PHConstruct.hammerHead, "_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead"); bowstring = new Bowstring(PHConstruct.bowstring).setUnlocalizedName("tconstruct.Bowstring"); arrowhead = new ToolPart(PHConstruct.arrowhead, "_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead"); fletching = new Fletching(PHConstruct.fletching).setUnlocalizedName("tconstruct.Fletching"); Item[] toolParts = { toolRod, toolShard, pickaxeHead, shovelHead, hatchetHead, binding, toughBinding, toughRod, largePlate, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, fullGuard, frypanHead, signHead, chiselHead, scytheBlade, broadAxeHead, excavatorHead, largeSwordBlade, hammerHead, bowstring, fletching, arrowhead }; String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard", "crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring", "fletching", "arrowhead" }; for (int i = 0; i < toolParts.length; i++) { GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7 compat TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]); } diamondApple = new DiamondApple(PHConstruct.diamondApple).setUnlocalizedName("tconstruct.apple.diamond"); strangeFood = new StrangeFood(PHConstruct.slimefood).setUnlocalizedName("tconstruct.strangefood"); oreBerries = new OreBerries(PHConstruct.oreChunks).setUnlocalizedName("oreberry"); GameRegistry.registerItem(diamondApple, "diamondApple"); GameRegistry.registerItem(strangeFood, "strangeFood"); GameRegistry.registerItem(oreBerries, "oreBerries"); jerky = new Jerky(PHConstruct.jerky, Loader.isModLoaded("HungerOverhaul")).setUnlocalizedName("tconstruct.jerky"); GameRegistry.registerItem(jerky, "jerky"); //Wearables heartCanister = new HeartCanister(PHConstruct.heartCanister).setUnlocalizedName("tconstruct.canister"); knapsack = new Knapsack(PHConstruct.knapsack).setUnlocalizedName("tconstruct.storage"); goldHead = new GoldenHead(PHConstruct.goldHead, 4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead"); GameRegistry.registerItem(heartCanister, "heartCanister"); GameRegistry.registerItem(knapsack, "knapsack"); GameRegistry.registerItem(goldHead, "goldHead"); LiquidCasting basinCasting = TConstruct.getBasinCasting(); materialWood = EnumHelper.addArmorMaterial("WOOD", 2, new int[] { 1, 2, 2, 1 }, 3); helmetWood = new ArmorBasic(PHConstruct.woodHelmet, materialWood, 0, "wood").setUnlocalizedName("tconstruct.helmetWood"); chestplateWood = new ArmorBasic(PHConstruct.woodChestplate, materialWood, 1, "wood").setUnlocalizedName("tconstruct.chestplateWood"); leggingsWood = new ArmorBasic(PHConstruct.woodPants, materialWood, 2, "wood").setUnlocalizedName("tconstruct.leggingsWood"); bootsWood = new ArmorBasic(PHConstruct.woodBoots, materialWood, 3, "wood").setUnlocalizedName("tconstruct.bootsWood"); GameRegistry.registerItem(helmetWood, "helmetWood"); GameRegistry.registerItem(chestplateWood, "chestplateWood"); GameRegistry.registerItem(leggingsWood, "leggingsWood"); GameRegistry.registerItem(bootsWood, "bootsWood"); exoGoggles = new ExoArmor(PHConstruct.exoGoggles, EnumArmorPart.HELMET, "exosuit").setUnlocalizedName("tconstruct.exoGoggles"); exoChest = new ExoArmor(PHConstruct.exoChest, EnumArmorPart.CHEST, "exosuit").setUnlocalizedName("tconstruct.exoChest"); exoPants = new ExoArmor(PHConstruct.exoPants, EnumArmorPart.PANTS, "exosuit").setUnlocalizedName("tconstruct.exoPants"); exoShoes = new ExoArmor(PHConstruct.exoShoes, EnumArmorPart.SHOES, "exosuit").setUnlocalizedName("tconstruct.exoShoes"); String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper", "ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper", "nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze", "nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" }; for (int i = 0; i < materialStrings.length; i++) { TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(materials, 1, i)); } String[] oreberries = { "Iron", "Gold", "Copper", "Tin", "Aluminum", "Essence" }; for (int i = 0; i < oreberries.length; i++) { TConstructRegistry.addItemStackToDirectory("oreberry" + oreberries[i], new ItemStack(oreBerries, 1, i)); } TConstructRegistry.addItemStackToDirectory("diamondApple", new ItemStack(diamondApple, 1, 0)); TConstructRegistry.addItemStackToDirectory("blueSlimeFood", new ItemStack(strangeFood, 1, 0)); TConstructRegistry.addItemStackToDirectory("canisterEmpty", new ItemStack(heartCanister, 1, 0)); TConstructRegistry.addItemStackToDirectory("miniRedHeart", new ItemStack(heartCanister, 1, 1)); TConstructRegistry.addItemStackToDirectory("canisterRedHeart", new ItemStack(heartCanister, 1, 2)); //Vanilla stack sizes Item.doorWood.setMaxStackSize(16); Item.doorIron.setMaxStackSize(16); Item.snowball.setMaxStackSize(64); Item.boat.setMaxStackSize(16); Item.minecartEmpty.setMaxStackSize(3); Item.minecartCrate.setMaxStackSize(3); Item.minecartPowered.setMaxStackSize(3); Item.itemsList[Block.cake.blockID].setMaxStackSize(16); //Block.torchWood.setTickRandomly(false); } void registerMaterials () { TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 0, 59, 200, 0, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "Stonebound"); TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", ""); TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", ""); TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "Jagged"); TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", ""); TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", ""); TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "Writable"); TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1100, 3, 1.75F, 2, 0f, "\u00A73", ""); TConstructRegistry.addToolMaterial(11, "Ardite", 4, 600, 800, 3, 2.0F, 0, 2f, "\u00A74", "Stonebound"); TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", ""); TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", ""); TConstructRegistry.addToolMaterial(14, "Bronze", 2, 350, 700, 2, 1.3F, 1, 0f, "\u00A76", ""); TConstructRegistry.addToolMaterial(15, "Alumite", 4, 550, 800, 3, 1.3F, 2, 0f, "\u00A7d", ""); TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 800, 3, 1.3F, 2, 0f, "", ""); TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", ""); TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", "Tasty"); TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); //Wood TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); //Stone TConstructRegistry.addBowMaterial(2, 576, 40, 1.2f); //Iron TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); //Flint TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); //Cactus TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); //Bone TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); //Obsidian TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); //Netherrack TConstructRegistry.addBowMaterial(8, 1536, 20, 1.2f); //Slime TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); //Paper TConstructRegistry.addBowMaterial(10, 1152, 40, 1.2f); //Cobalt TConstructRegistry.addBowMaterial(11, 960, 40, 1.2f); //Ardite TConstructRegistry.addBowMaterial(12, 1536, 40, 1.2f); //Manyullyn TConstructRegistry.addBowMaterial(13, 384, 40, 1.2f); //Copper TConstructRegistry.addBowMaterial(14, 576, 40, 1.2f); //Bronze TConstructRegistry.addBowMaterial(15, 768, 40, 1.2f); //Alumite TConstructRegistry.addBowMaterial(16, 768, 40, 1.2f); //Steel TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); //Blue Slime TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); //Slime //Material ID, mass, fragility TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood TConstructRegistry.addArrowMaterial(1, 2.5F, 5.0F, 100F); //Stone TConstructRegistry.addArrowMaterial(2, 7.2F, 0.5F, 100F); //Iron TConstructRegistry.addArrowMaterial(3, 2.65F, 1.0F, 100F); //Flint TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian TConstructRegistry.addArrowMaterial(7, 3.5F, 1.0F, 100F); //Netherrack TConstructRegistry.addArrowMaterial(8, 0.42F, 0.0F, 100F); //Slime TConstructRegistry.addArrowMaterial(9, 1.1F, 3.0F, 90F); //Paper TConstructRegistry.addArrowMaterial(10, 8.9F, 0.25F, 100F); //Cobalt TConstructRegistry.addArrowMaterial(11, 7.2F, 0.25F, 100F); //Ardite TConstructRegistry.addArrowMaterial(12, 10.6F, 0.1F, 100F); //Manyullyn TConstructRegistry.addArrowMaterial(13, 8.96F, 0.5F, 100F); //Copper TConstructRegistry.addArrowMaterial(14, 7.9F, 0.25F, 100F); //Bronze TConstructRegistry.addArrowMaterial(15, 4.7F, 0.25F, 100F); //Alumite TConstructRegistry.addArrowMaterial(16, 7.6F, 0.25F, 100F); //Steel TConstructRegistry.addArrowMaterial(17, 0.42F, 0.0F, 100F); //Blue Slime TConstructRegistry.addArrowMaterial(18, 6.8F, 0.5F, 100F); //Iron TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Item.silk), new ItemStack(bowstring, 1, 0), 1F, 1F, 1f); //String TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Item.feather), new ItemStack(fletching, 1, 0), 100F, 0F, 0.05F); //Feather for (int i = 0; i < 4; i++) TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Block.leaves, 1, i), new ItemStack(fletching, 1, 1), 75F, 0F, 0.2F); //All four vanialla Leaves TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(materials, 1, 1), new ItemStack(fletching, 1, 2), 100F, 0F, 0.12F); //Slime TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(materials, 1, 17), new ItemStack(fletching, 1, 3), 100F, 0F, 0.12F); //BlueSlime PatternBuilder pb = PatternBuilder.instance; if (PHConstruct.enableTWood) pb.registerFullMaterial(Block.planks, 2, "Wood", new ItemStack(Item.stick), new ItemStack(Item.stick), 0); else pb.registerMaterialSet("Wood", new ItemStack(Item.stick, 2), new ItemStack(Item.stick), 0); if (PHConstruct.enableTStone) { pb.registerFullMaterial(Block.stone, 2, "Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 1); pb.registerMaterial(Block.cobblestone, 2, "Stone"); } else pb.registerMaterialSet("Stone", new ItemStack(TContent.toolShard, 1, 1), new ItemStack(TContent.toolRod, 1, 1), 0); pb.registerFullMaterial(Item.ingotIron, 2, "Iron", new ItemStack(TContent.toolShard, 1, 2), new ItemStack(TContent.toolRod, 1, 2), 2); if (PHConstruct.enableTFlint) pb.registerFullMaterial(Item.flint, 2, "Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); else pb.registerMaterialSet("Flint", new ItemStack(TContent.toolShard, 1, 3), new ItemStack(TContent.toolRod, 1, 3), 3); if (PHConstruct.enableTCactus) pb.registerFullMaterial(Block.cactus, 2, "Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); else pb.registerMaterialSet("Cactus", new ItemStack(TContent.toolShard, 1, 4), new ItemStack(TContent.toolRod, 1, 4), 4); if (PHConstruct.enableTBone) pb.registerFullMaterial(Item.bone, 2, "Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); else pb.registerMaterialSet("Bone", new ItemStack(Item.dyePowder, 1, 15), new ItemStack(Item.bone), 5); pb.registerFullMaterial(Block.obsidian, 2, "Obsidian", new ItemStack(TContent.toolShard, 1, 6), new ItemStack(TContent.toolRod, 1, 6), 6); pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian"); if (PHConstruct.enableTNetherrack) pb.registerFullMaterial(Block.netherrack, 2, "Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); else pb.registerMaterialSet("Netherrack", new ItemStack(TContent.toolShard, 1, 7), new ItemStack(TContent.toolRod, 1, 7), 7); if (PHConstruct.enableTSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8); else pb.registerMaterialSet("Slime", new ItemStack(TContent.toolShard, 1, 8), new ItemStack(TContent.toolRod, 1, 17), 8); if (PHConstruct.enableTPaper) pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Item.paper, 2), new ItemStack(toolRod, 1, 9), 9); else pb.registerMaterialSet("BlueSlime", new ItemStack(Item.paper, 2), new ItemStack(TContent.toolRod, 1, 9), 9); pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10); pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11); pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12); pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13); pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14); pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15); pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16); if (PHConstruct.enableTBlueSlime) pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17); else pb.registerMaterialSet("BlueSlime", new ItemStack(TContent.toolShard, 1, 17), new ItemStack(TContent.toolRod, 1, 17), 17); pb.registerFullMaterial(new ItemStack(materials, 1, 34), 2, "PigIron", new ItemStack(toolShard, 1, 18), new ItemStack(toolRod, 1, 18), 18); pb.addToolPattern((IPattern) woodPattern); } public static Item[] patternOutputs; public static FluidStack[] liquids; void addCraftingRecipes () { addPartMapping(); addRecipesForToolBuilder(); addRecipesForTableCasting(); addRecipesForBasinCasting(); addRecipesForSmeltery(); addRecipesForChisel(); addRecipesForFurnace(); addRecipesForCraftingTable(); addRecipesForDryingRack(); } private void addRecipesForCraftingTable () { String[] patBlock = { "###", "###", "###" }; String[] patSurround = { "###", "#m#", "###" }; Object[] toolForgeBlocks = { "blockIron", "blockGold", Block.blockDiamond, Block.blockEmerald, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin", "blockAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" }; // ToolForge Recipes (Metal Version) for (int sc = 0; sc < toolForgeBlocks.length; sc++) { GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(toolStationWood, 1, 0), 'm', toolForgeBlocks[sc])); // adding slab version recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(smeltery, 1, 2), 's', new ItemStack(craftingSlabWood, 1, 1), 'm', toolForgeBlocks[sc])); } // ToolStation Recipes (Wooden Version) GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "craftingTableWood")); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(craftingSlabWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', Block.chest); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "logWood")); if (PHConstruct.stencilTableCrafting) { GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 0)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 1)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 2)); GameRegistry.addRecipe(new ItemStack(toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', new ItemStack(Block.planks, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(blankPattern, 1, 0), 'w', "plankWood")); } GameRegistry.addRecipe(new ItemStack(furnaceSlab, 1, 0), "###", "# #", "###", '#', new ItemStack(Block.stoneSingleSlab, 1, 3)); // Blank Pattern Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(blankPattern, 1, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood")); // Manual Book Recipes GameRegistry.addRecipe(new ItemStack(manualBook), "wp", 'w', new ItemStack(blankPattern, 1, 0), 'p', Item.paper); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 0), new ItemStack(manualBook, 1, 0), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 1), new ItemStack(manualBook, 1, 0)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 1), new ItemStack(manualBook, 1, 1), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 2), new ItemStack(manualBook, 1, 1)); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 2, 2), new ItemStack(manualBook, 1, 2), Item.book); GameRegistry.addShapelessRecipe(new ItemStack(manualBook, 1, 3), new ItemStack(manualBook, 1, 2)); // alternative Vanilla Book Recipe GameRegistry.addShapelessRecipe(new ItemStack(Item.book), Item.paper, Item.paper, Item.paper, Item.silk, blankPattern, blankPattern); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.nameTag), "P~ ", "~O ", " ~", '~', Item.silk, 'P', Item.paper, 'O', "slimeball")); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt)); // Paperstack Recipe GameRegistry.addRecipe(new ItemStack(materials, 1, 0), "pp", "pp", 'p', Item.paper); // Mossball Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 6), patBlock, '#', "stoneMossy")); // LavaCrystal Recipes -Auto-smelt GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'c', Item.fireballCharge, 'x', Item.blazeRod); GameRegistry.addRecipe(new ItemStack(materials, 1, 7), "xcx", "cbc", "xcx", 'b', Item.bucketLava, 'x', Item.fireballCharge, 'c', Item.blazeRod); // Slimy sand Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 0), Item.slimeBall, Item.slimeBall, Item.slimeBall, Item.slimeBall, Block.sand, Block.dirt); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 2), strangeFood, strangeFood, strangeFood, strangeFood, Block.sand, Block.dirt); // Grout Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 1), Item.clay, Block.sand, Block.gravel); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 8, 1), new ItemStack(Block.blockClay, 1, Short.MAX_VALUE), Block.sand, Block.sand, Block.sand, Block.sand, Block.gravel, Block.gravel, Block.gravel, Block.gravel); GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 6), Item.netherStalkSeeds, Block.slowSand, Block.gravel); // Graveyard Soil Recipes GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 1, 3), Block.dirt, Item.rottenFlesh, new ItemStack(Item.dyePowder, 1, 15)); // Silky Cloth Recipes GameRegistry.addRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', new ItemStack(materials, 1, 24), '#', new ItemStack(Item.silk)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Item.silk))); // Silky Jewel Recipes GameRegistry.addRecipe(new ItemStack(materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(materials, 1, 25), 'e', new ItemStack(Item.emerald)); // Armor Recipes Object[] helm = new String[] { "www", "w w" }; Object[] chest = new String[] { "w w", "www", "www" }; Object[] pants = new String[] { "www", "w w", "w w" }; Object[] shoes = new String[] { "w w", "w w" }; GameRegistry.addRecipe(new ShapedOreRecipe(helmetWood, helm, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(chestplateWood, chest, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(leggingsWood, pants, 'w', "logWood")); GameRegistry.addRecipe(new ShapedOreRecipe(bootsWood, shoes, 'w', "logWood")); ItemStack exoGoggleStack = new ItemStack(exoGoggles); ItemStack exoChestStack = new ItemStack(exoChest); ItemStack exoPantsStack = new ItemStack(exoPants); ItemStack exoShoesStack = new ItemStack(exoShoes); ToolBuilder.instance.addArmorTag(exoGoggleStack); ToolBuilder.instance.addArmorTag(exoChestStack); ToolBuilder.instance.addArmorTag(exoPantsStack); ToolBuilder.instance.addArmorTag(exoShoesStack); GameRegistry.addShapedRecipe(exoGoggleStack, helm, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoChestStack, chest, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoPantsStack, pants, 'w', new ItemStack(largePlate, 1, 14)); GameRegistry.addShapedRecipe(exoShoesStack, shoes, 'w', new ItemStack(largePlate, 1, 14)); // Metal conversion Recipes GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 3), patBlock, '#', new ItemStack(materials, 1, 9)); // Copper GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 5), patBlock, '#', new ItemStack(materials, 1, 10)); // Tin GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 6), patBlock, '#', new ItemStack(materials, 1, 11)); // Aluminum //GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 6), patBlock, '#', new ItemStack(materials, 1, 12)); // Aluminum GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 4), patBlock, '#', new ItemStack(materials, 1, 13)); // Bronze GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 7), patBlock, '#', new ItemStack(materials, 1, 14)); // AluBrass GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 0), patBlock, '#', new ItemStack(materials, 1, 3)); // Cobalt GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 1), patBlock, '#', new ItemStack(materials, 1, 4)); // Ardite GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 2), patBlock, '#', new ItemStack(materials, 1, 5)); // Manyullyn GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 8), patBlock, '#', new ItemStack(materials, 1, 15)); // Alumite GameRegistry.addRecipe(new ItemStack(metalBlock, 1, 9), patBlock, '#', new ItemStack(materials, 1, 16)); // Steel GameRegistry.addRecipe(new ItemStack(materials, 1, 11), patBlock, '#', new ItemStack(materials, 1, 12)); //Aluminum raw -> ingot GameRegistry.addRecipe(new ItemStack(materials, 9, 9), "m", 'm', new ItemStack(metalBlock, 1, 3)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 10), "m", 'm', new ItemStack(metalBlock, 1, 5)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 11), "m", 'm', new ItemStack(metalBlock, 1, 6)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 13), "m", 'm', new ItemStack(metalBlock, 1, 4)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 14), "m", 'm', new ItemStack(metalBlock, 1, 7)); //AluBrass GameRegistry.addRecipe(new ItemStack(materials, 9, 3), "m", 'm', new ItemStack(metalBlock, 1, 0)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 4), "m", 'm', new ItemStack(metalBlock, 1, 1)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 5), "m", 'm', new ItemStack(metalBlock, 1, 2)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 15), "m", 'm', new ItemStack(metalBlock, 1, 8)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 16), "m", 'm', new ItemStack(metalBlock, 1, 9)); //Steel GameRegistry.addRecipe(new ItemStack(Item.ingotIron), patBlock, '#', new ItemStack(materials, 1, 19)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 1, 9), patBlock, '#', new ItemStack(materials, 1, 20)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 1, 10), patBlock, '#', new ItemStack(materials, 1, 21)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 1, 11), patBlock, '#', new ItemStack(materials, 1, 22)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 1, 14), patBlock, '#', new ItemStack(materials, 1, 24)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 1, 18), patBlock, '#', new ItemStack(materials, 1, 27)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 1, 3), patBlock, '#', new ItemStack(materials, 1, 28)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 1, 4), patBlock, '#', new ItemStack(materials, 1, 29)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 1, 5), patBlock, '#', new ItemStack(materials, 1, 30)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 1, 13), patBlock, '#', new ItemStack(materials, 1, 31)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 1, 15), patBlock, '#', new ItemStack(materials, 1, 32)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 1, 16), patBlock, '#', new ItemStack(materials, 1, 33)); //Steel GameRegistry.addRecipe(new ItemStack(materials, 9, 19), "m", 'm', new ItemStack(Item.ingotIron)); //Iron GameRegistry.addRecipe(new ItemStack(materials, 9, 20), "m", 'm', new ItemStack(materials, 1, 9)); //Copper GameRegistry.addRecipe(new ItemStack(materials, 9, 21), "m", 'm', new ItemStack(materials, 1, 10)); //Tin GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 11)); //Aluminum //GameRegistry.addRecipe(new ItemStack(materials, 9, 22), "m", 'm', new ItemStack(materials, 1, 12)); //Aluminum GameRegistry.addRecipe(new ItemStack(materials, 9, 24), "m", 'm', new ItemStack(materials, 1, 14)); //Aluminum Brass GameRegistry.addRecipe(new ItemStack(materials, 9, 27), "m", 'm', new ItemStack(materials, 1, 18)); //Obsidian GameRegistry.addRecipe(new ItemStack(materials, 9, 28), "m", 'm', new ItemStack(materials, 1, 3)); //Cobalt GameRegistry.addRecipe(new ItemStack(materials, 9, 29), "m", 'm', new ItemStack(materials, 1, 4)); //Ardite GameRegistry.addRecipe(new ItemStack(materials, 9, 30), "m", 'm', new ItemStack(materials, 1, 5)); //Manyullyn GameRegistry.addRecipe(new ItemStack(materials, 9, 31), "m", 'm', new ItemStack(materials, 1, 13)); //Bronze GameRegistry.addRecipe(new ItemStack(materials, 9, 32), "m", 'm', new ItemStack(materials, 1, 15)); //Alumite GameRegistry.addRecipe(new ItemStack(materials, 9, 33), "m", 'm', new ItemStack(materials, 1, 16)); //Steel // stained Glass Recipes String[] dyeTypes = { "dyeBlack", "dyeRed", "dyeGreen", "dyeBrown", "dyeBlue", "dyePurple", "dyeCyan", "dyeLightGray", "dyeGray", "dyePink", "dyeLime", "dyeYellow", "dyeLightBlue", "dyeMagenta", "dyeOrange", "dyeWhite" }; String color = ""; for (int i = 0; i < 16; i++) { color = dyeTypes[15 - i]; GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.cloth, 8, i), patSurround, 'm', color, '#', new ItemStack(Block.cloth, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', clearGlass)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, clearGlass)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClear, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClear, 1, i), color, new ItemStack(stainedGlassClear, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', glassPane)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, glassPane)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stainedGlassClearPane, 8, i), patSurround, 'm', color, '#', new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(stainedGlassClearPane, 1, i), color, new ItemStack(stainedGlassClearPane, 1, Short.MAX_VALUE))); } // Glass Recipes GameRegistry.addRecipe(new ItemStack(Item.glassBottle, 3), new Object[] { "# #", " # ", '#', clearGlass }); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Block.daylightSensor), new Object[] { "GGG", "QQQ", "WWW", 'G', "glass", 'Q', Item.netherQuartz, 'W', "slabWood" })); GameRegistry.addRecipe(new ItemStack(Block.beacon, 1), new Object[] { "GGG", "GSG", "OOO", 'G', clearGlass, 'S', Item.netherStar, 'O', Block.obsidian }); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(glassPane, 16, 0), "GGG", "GGG", 'G', clearGlass)); // Smeltery Components Recipes ItemStack searedBrick = new ItemStack(materials, 1, 2); GameRegistry.addRecipe(new ItemStack(smeltery, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smeltery, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smeltery, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTank, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlock, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel searedBrick = new ItemStack(materials, 1, 37); GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 0), "bbb", "b b", "bbb", 'b', searedBrick); //Controller GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 1), "b b", "b b", "b b", 'b', searedBrick); //Drain GameRegistry.addRecipe(new ItemStack(smelteryNether, 1, 2), "bb", "bb", 'b', searedBrick); //Bricks GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 0), patSurround, '#', searedBrick, 'm', "glass")); //Tank GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 1), "bgb", "ggg", "bgb", 'b', searedBrick, 'g', "glass")); //Glass GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(lavaTankNether, 1, 2), "bgb", "bgb", "bgb", 'b', searedBrick, 'g', "glass")); //Window GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 0), "bbb", "b b", "b b", 'b', searedBrick); //Table GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 1), "b b", " b ", 'b', searedBrick); //Faucet GameRegistry.addRecipe(new ItemStack(searedBlockNether, 1, 2), "b b", "b b", "bbb", 'b', searedBrick); //Basin GameRegistry.addRecipe(new ItemStack(castingChannel, 4, 0), "b b", "bbb", 'b', searedBrick); //Channel // Jack o'Latern Recipe - Stone Torch GameRegistry.addRecipe(new ItemStack(Block.pumpkinLantern, 1, 0), "p", "s", 'p', new ItemStack(Block.pumpkin), 's', new ItemStack(stoneTorch)); // Stone Torch Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneTorch, 4), "p", "w", 'p', new ItemStack(Item.coal, 1, Short.MAX_VALUE), 'w', "stoneRod")); // Stone Ladder Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(stoneLadder, 3), "w w", "www", "w w", 'w', "stoneRod")); // Wooden Rail Recipe GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(woodenRail, 4, 0), "b b", "bxb", "b b", 'b', "plankWood", 'x', "stickWood")); // Stonesticks Recipes GameRegistry.addRecipe(new ItemStack(toolRod, 4, 1), "c", "c", 'c', new ItemStack(Block.stone)); GameRegistry.addRecipe(new ItemStack(toolRod, 2, 1), "c", "c", 'c', new ItemStack(Block.cobblestone)); // ItemStack aluBrass = new ItemStack(materials, 1, 14); // Clock Recipe - Vanilla alternativ GameRegistry.addRecipe(new ItemStack(Item.pocketSundial), " i ", "iri", " i ", 'i', aluBrass, 'r', new ItemStack(Item.redstone)); // Gold Pressure Plate - Vanilla alternativ GameRegistry.addRecipe(new ItemStack(Block.pressurePlateGold), "ii", 'i', aluBrass); //Accessories GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotAluminium")); //GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), "##", "##", '#', "ingotNaturalAluminum")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(heartCanister, 1, 0), " # ", "#B#", " # ", '#', "ingotTin", 'B', Item.bone)); GameRegistry.addRecipe(new ItemStack(diamondApple), " d ", "d#d", " d ", 'd', new ItemStack(Item.diamond), '#', new ItemStack(Item.appleRed)); GameRegistry.addShapelessRecipe(new ItemStack(heartCanister, 1, 2), new ItemStack(diamondApple), new ItemStack(materials, 1, 8), new ItemStack(heartCanister, 1, 0), new ItemStack( heartCanister, 1, 1)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', "ingotGold")); GameRegistry.addRecipe(new ItemStack(knapsack, 1, 0), "###", "rmr", "###", '#', new ItemStack(Item.leather), 'r', new ItemStack(toughRod, 1, 2), 'm', aluBrass); // Drying Rack Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(dryingRack, 1, 0), "bbb", 'b', "slabWood")); //Landmine Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 0), "mcm", "rpr", 'm', "plankWood", 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 1), "mcm", "rpr", 'm', Block.stone, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 2), "mcm", "rpr", 'm', Block.obsidian, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(landmine, 1, 3), "mcm", "rpr", 'm', Item.redstoneRepeater, 'c', new ItemStack(blankPattern, 1, 1), 'r', Item.redstone, 'p', Block.pressurePlateStone)); //Ultra hardcore recipes GameRegistry.addRecipe(new ItemStack(goldHead), patSurround, '#', new ItemStack(Item.ingotGold), 'm', new ItemStack(Item.skull, 1, 3)); // Slab Smeltery Components Recipes for (int i = 0; i < 7; i++) { GameRegistry.addRecipe(new ItemStack(speedSlab, 6, i), "bbb", 'b', new ItemStack(speedBlock, 1, i)); } GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 0), "bbb", 'b', new ItemStack(smeltery, 1, 2)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 1), "bbb", 'b', new ItemStack(smeltery, 1, 4)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 2), "bbb", 'b', new ItemStack(smeltery, 1, 5)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 3), "bbb", 'b', new ItemStack(smeltery, 1, 6)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 4), "bbb", 'b', new ItemStack(smeltery, 1, 8)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 5), "bbb", 'b', new ItemStack(smeltery, 1, 9)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 6), "bbb", 'b', new ItemStack(smeltery, 1, 10)); GameRegistry.addRecipe(new ItemStack(searedSlab, 6, 7), "bbb", 'b', new ItemStack(smeltery, 1, 11)); // Wool Slab Recipes for (int sc = 0; sc <= 7; sc++) { GameRegistry.addRecipe(new ItemStack(woolSlab1, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc)); GameRegistry.addRecipe(new ItemStack(woolSlab2, 6, sc), "www", 'w', new ItemStack(Block.cloth, 1, sc + 8)); GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc), new ItemStack(woolSlab1, 1, sc), new ItemStack(woolSlab1, 1, sc)); GameRegistry.addShapelessRecipe(new ItemStack(Block.cloth, 1, sc + 8), new ItemStack(woolSlab2, 1, sc), new ItemStack(woolSlab2, 1, sc)); } GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.cloth, 1, 0), "slabCloth", "slabCloth")); //Trap Recipes GameRegistry.addRecipe(new ItemStack(punji, 5, 0), "b b", " b ", "b b", 'b', new ItemStack(Item.reed)); GameRegistry.addRecipe(new ItemStack(barricadeSpruce, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 1)); GameRegistry.addRecipe(new ItemStack(barricadeBirch, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 2)); GameRegistry.addRecipe(new ItemStack(barricadeJungle, 1, 0), "b", "b", 'b', new ItemStack(Block.wood, 1, 3)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(barricadeOak, 1, 0), "b", "b", 'b', "logWood")); // Advanced WorkBench Recipes GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingStationWood, 1, 0), "b", 'b', "craftingTableWood")); //Slab crafters GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood")); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(craftingSlabWood, 6, 0), "bbb", 'b', "craftingTableWood")); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 0), "b", 'b', new ItemStack(craftingStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 1), "b", 'b', new ItemStack(toolStationWood, 1, 0)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 1)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 2)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 3)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 2), "b", 'b', new ItemStack(toolStationWood, 1, 4)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 4), "b", 'b', new ItemStack(toolStationWood, 1, 5)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 10)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 11)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 12)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 3), "b", 'b', new ItemStack(toolStationWood, 1, 13)); GameRegistry.addRecipe(new ItemStack(craftingSlabWood, 1, 5), "b", 'b', new ItemStack(toolForge, 1, Short.MAX_VALUE)); // EssenceExtractor Recipe //Slime Recipes GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 0), "##", "##", '#', strangeFood); GameRegistry.addRecipe(new ItemStack(strangeFood, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 0)); GameRegistry.addRecipe(new ItemStack(slimeGel, 1, 1), "##", "##", '#', Item.slimeBall); GameRegistry.addRecipe(new ItemStack(Item.slimeBall, 4, 0), "#", '#', new ItemStack(slimeGel, 1, 1)); //slimeExplosive GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 0), Item.slimeBall, Block.tnt); GameRegistry.addShapelessRecipe(new ItemStack(slimeExplosive, 1, 2), strangeFood, Block.tnt); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeExplosive, 1, 0), "slimeball", Block.tnt)); GameRegistry.addShapelessRecipe(new ItemStack(slimeChannel, 1, 0), new ItemStack(slimeGel, 1, Short.MAX_VALUE), new ItemStack(Item.redstone)); GameRegistry.addShapelessRecipe(new ItemStack(bloodChannel, 1, 0), new ItemStack(strangeFood, 1, 1), new ItemStack(strangeFood, 1, 1), new ItemStack(strangeFood, 1, 1), new ItemStack( strangeFood, 1, 1), new ItemStack(Item.redstone)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimeChannel, 1, 0), "slimeball", "slimeball", "slimeball", "slimeball", new ItemStack(Item.redstone))); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(slimePad, 1, 0), slimeChannel, "slimeball")); } private void addRecipesForFurnace () { FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 3, new ItemStack(craftedSoil, 1, 4), 0.2f); //Concecrated Soil FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 0, new ItemStack(materials, 1, 1), 2f); //Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 1, new ItemStack(materials, 1, 2), 2f); //Seared brick item FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 2, new ItemStack(materials, 1, 17), 2f); //Blue Slime FurnaceRecipes.smelting().addSmelting(craftedSoil.blockID, 6, new ItemStack(materials, 1, 37), 2f); //Nether seared brick //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 1, new ItemStack(materials, 1, 3), 3f); //FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 2, new ItemStack(materials, 1, 4), 3f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 3, new ItemStack(materials, 1, 9), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 4, new ItemStack(materials, 1, 10), 0.5f); FurnaceRecipes.smelting().addSmelting(oreSlag.blockID, 5, new ItemStack(materials, 1, 11), 0.5f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 0, new ItemStack(materials, 1, 19), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 1, new ItemStack(Item.goldNugget), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 2, new ItemStack(materials, 1, 20), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 3, new ItemStack(materials, 1, 21), 0.2f); FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 4, new ItemStack(materials, 1, 22), 0.2f); //FurnaceRecipes.smelting().addSmelting(oreBerries.itemID, 5, new ItemStack(materials, 1, 23), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 0, new ItemStack(Item.ingotIron), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 1, new ItemStack(Item.ingotGold), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 2, new ItemStack(materials, 1, 9), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 3, new ItemStack(materials, 1, 10), 0.2f); FurnaceRecipes.smelting().addSmelting(oreGravel.blockID, 4, new ItemStack(materials, 1, 11), 0.2f); FurnaceRecipes.smelting().addSmelting(speedBlock.blockID, 0, new ItemStack(speedBlock, 1, 2), 0.2f); } private void addPartMapping () { /* Tools */ patternOutputs = new Item[] { toolRod, pickaxeHead, shovelHead, hatchetHead, swordBlade, wideGuard, handGuard, crossbar, binding, frypanHead, signHead, knifeBlade, chiselHead, toughRod, toughBinding, largePlate, broadAxeHead, scytheBlade, excavatorHead, largeSwordBlade, hammerHead, fullGuard, null, null, arrowhead, null }; int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 }; if (PHConstruct.craftMetalTools) { for (int mat = 0; mat < 18; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, mat, new ItemStack(patternOutputs[meta], 1, mat)); } } } else { for (int mat = 0; mat < nonMetals.length; mat++) { for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, nonMetals[mat], new ItemStack(patternOutputs[meta], 1, nonMetals[mat])); } } } } private void addRecipesForToolBuilder () { ToolBuilder tb = ToolBuilder.instance; tb.addNormalToolRecipe(pickaxe, pickaxeHead, toolRod, binding); tb.addNormalToolRecipe(broadsword, swordBlade, toolRod, wideGuard); tb.addNormalToolRecipe(hatchet, hatchetHead, toolRod); tb.addNormalToolRecipe(shovel, shovelHead, toolRod); tb.addNormalToolRecipe(longsword, swordBlade, toolRod, handGuard); tb.addNormalToolRecipe(rapier, swordBlade, toolRod, crossbar); tb.addNormalToolRecipe(frypan, frypanHead, toolRod); tb.addNormalToolRecipe(battlesign, signHead, toolRod); tb.addNormalToolRecipe(mattock, hatchetHead, toolRod, shovelHead); tb.addNormalToolRecipe(dagger, knifeBlade, toolRod, crossbar); tb.addNormalToolRecipe(cutlass, swordBlade, toolRod, fullGuard); tb.addNormalToolRecipe(chisel, chiselHead, toolRod); tb.addNormalToolRecipe(scythe, scytheBlade, toughRod, toughBinding, toughRod); tb.addNormalToolRecipe(lumberaxe, broadAxeHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(cleaver, largeSwordBlade, toughRod, largePlate, toughRod); tb.addNormalToolRecipe(excavator, excavatorHead, toughRod, largePlate, toughBinding); tb.addNormalToolRecipe(hammer, hammerHead, toughRod, largePlate, largePlate); tb.addNormalToolRecipe(battleaxe, broadAxeHead, toughRod, broadAxeHead, toughBinding); //tb.addNormalToolRecipe(shortbow, toolRod, bowstring, toolRod); BowRecipe recipe = new BowRecipe(toolRod, bowstring, toolRod, shortbow); tb.addCustomToolRecipe(recipe); tb.addNormalToolRecipe(arrow, arrowhead, toolRod, fletching); ItemStack diamond = new ItemStack(Item.diamond); tb.registerToolMod(new ModRepair()); tb.registerToolMod(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7bDurability +500", "\u00a7b")); tb.registerToolMod(new ModDurability(new ItemStack[] { new ItemStack(Item.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72Durability +50%", "\u00a72")); modFlux = new ModFlux(); tb.registerToolMod(modFlux); ItemStack redstoneItem = new ItemStack(Item.redstone); ItemStack redstoneBlock = new ItemStack(Block.blockRedstone); tb.registerToolMod(new ModRedstone(2, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 })); ItemStack lapisItem = new ItemStack(Item.dyePowder, 1, 4); ItemStack lapisBlock = new ItemStack(Block.blockLapis); this.modLapis = new ModLapis(10, new ItemStack[] { lapisItem, lapisBlock }, new int[] { 1, 9 }); tb.registerToolMod(this.modLapis); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(this.materials, 1, 6) }, 4, "Moss", 3, "\u00a72", "Auto-Repair")); ItemStack blazePowder = new ItemStack(Item.blazePowder); tb.registerToolMod(new ModBlaze(7, new ItemStack[] { blazePowder }, new int[] { 1 })); tb.registerToolMod(new ModAutoSmelt(new ItemStack[] { new ItemStack(this.materials, 1, 7) }, 6, "Lava", "\u00a74", "Auto-Smelt")); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(this.materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", "Life Steal")); this.modAttack = new ModAttack("Quartz", 11, new ItemStack[] { new ItemStack(Item.netherQuartz), new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE) }, new int[] { 1, 4 }); tb.registerToolMod(this.modAttack); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Block.blockGold) }, "Tier1Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Block.blockDiamond), new ItemStack(Item.appleGold, 1, 1) }, "Tier1.5Free")); tb.registerToolMod(new ModExtraModifier(new ItemStack[] { new ItemStack(Item.netherStar) }, "Tier2Free")); ItemStack silkyJewel = new ItemStack(this.materials, 1, 26); tb.registerToolMod(new ModButtertouch(new ItemStack[] { silkyJewel }, 12)); ItemStack piston = new ItemStack(Block.pistonBase); tb.registerToolMod(new ModPiston(3, new ItemStack[] { piston }, new int[] { 1 })); tb.registerToolMod(new ModInteger(new ItemStack[] { new ItemStack(Block.obsidian), new ItemStack(Item.enderPearl) }, 13, "Beheading", 1, "\u00a7d", "Beheading")); ItemStack holySoil = new ItemStack(this.craftedSoil, 1, 4); tb.registerToolMod(new ModSmite("Smite", 14, new ItemStack[] { holySoil }, new int[] { 1 })); ItemStack spidereyeball = new ItemStack(Item.fermentedSpiderEye); tb.registerToolMod(new ModAntiSpider("Anti-Spider", 15, new ItemStack[] { spidereyeball }, new int[] { 1 })); ItemStack obsidianPlate = new ItemStack(this.largePlate, 1, 6); tb.registerToolMod(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1)); EnumSet<EnumArmorPart> allArmors = EnumSet.of(EnumArmorPart.HELMET, EnumArmorPart.CHEST, EnumArmorPart.PANTS, EnumArmorPart.SHOES); EnumSet<EnumArmorPart> chest = EnumSet.of(EnumArmorPart.CHEST); tb.registerArmorMod(new AModMoveSpeed(0, allArmors, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 }, false)); tb.registerArmorMod(new AModKnockbackResistance(1, allArmors, new ItemStack[] { new ItemStack(Item.ingotGold), new ItemStack(Block.blockGold) }, new int[] { 1, 9 }, false)); tb.registerArmorMod(new AModHealthBoost(2, allArmors, new ItemStack[] { new ItemStack(heartCanister, 1, 2) }, new int[] { 2 }, true)); tb.registerArmorMod(new AModDamageBoost(3, allArmors, new ItemStack[] { new ItemStack(Item.diamond), new ItemStack(Block.blockDiamond) }, new int[] { 1, 9 }, false, 3, 0.05)); tb.registerArmorMod(new AModDamageBoost(4, chest, new ItemStack[] { new ItemStack(Block.blockNetherQuartz, 1, Short.MAX_VALUE) }, new int[] { 1 }, true, 5, 1)); tb.registerArmorMod(new AModProtection(5, allArmors, new ItemStack[] { new ItemStack(largePlate, 1, 2) }, new int[] { 2 } )); TConstructRegistry.registerActiveToolMod(new TActiveOmniMod()); } private void addRecipesForTableCasting () { /* Smeltery */ ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); ItemStack gemcast = new ItemStack(metalPattern, 1, 26); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); //Blank tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 1), new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), 80); tableCasting.addCastingRecipe(new ItemStack(blankPattern, 1, 2), new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), 80); tableCasting.addCastingRecipe(gemcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(Item.emerald), 80); tableCasting.addCastingRecipe(gemcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(Item.emerald), 80); //Ingots tableCasting.addCastingRecipe(new ItemStack(materials, 1, 2), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 4), ingotcast, 80); //stone //Misc tableCasting.addCastingRecipe(new ItemStack(Item.emerald), new FluidStack(moltenEmeraldFluid, 640), gemcast, 80); tableCasting.addCastingRecipe(new ItemStack(materials, 1, 36), new FluidStack(glueFluid, TConstruct.ingotLiquidValue), null, 50); tableCasting.addCastingRecipe(new ItemStack(strangeFood, 1, 1), new FluidStack(bloodFluid, 160), null, 50); //Buckets ItemStack bucket = new ItemStack(Item.bucketEmpty); for (int sc = 0; sc < 24; sc++) { tableCasting.addCastingRecipe(new ItemStack(buckets, 1, sc), new FluidStack(fluids[sc], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); } tableCasting.addCastingRecipe(new ItemStack(buckets, 1, 26), new FluidStack(fluids[26], FluidContainerRegistry.BUCKET_VOLUME), bucket, true, 10); // Clear glass pane casting tableCasting.addCastingRecipe(new ItemStack(glassPane), new FluidStack(moltenGlassFluid, 250), null, 80); // Metal toolpart casting liquids = new FluidStack[] { new FluidStack(moltenIronFluid, 1), new FluidStack(moltenCopperFluid, 1), new FluidStack(moltenCobaltFluid, 1), new FluidStack(moltenArditeFluid, 1), new FluidStack(moltenManyullynFluid, 1), new FluidStack(moltenBronzeFluid, 1), new FluidStack(moltenAlumiteFluid, 1), new FluidStack(moltenObsidianFluid, 1), new FluidStack(moltenSteelFluid, 1), new FluidStack(pigIronFluid, 1) }; int[] liquidDamage = new int[] { 2, 13, 10, 11, 12, 14, 15, 6, 16, 18 }; //ItemStack damage value int fluidAmount = 0; Fluid fs = null; for (int iter = 0; iter < patternOutputs.length; iter++) { if (patternOutputs[iter] != null) { ItemStack cast = new ItemStack(metalPattern, 1, iter + 1); tableCasting.addCastingRecipe(cast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(cast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(patternOutputs[iter], 1, Short.MAX_VALUE), false, 50); for (int iterTwo = 0; iterTwo < liquids.length; iterTwo++) { fs = liquids[iterTwo].getFluid(); fluidAmount = ((IPattern) metalPattern).getPatternCost(cast) * TConstruct.ingotLiquidValue / 2; ItemStack metalCast = new ItemStack(patternOutputs[iter], 1, liquidDamage[iterTwo]); tableCasting.addCastingRecipe(metalCast, new FluidStack(fs, fluidAmount), cast, 50); Smeltery.addMelting(FluidType.getFluidType(fs), metalCast, 0, fluidAmount); } } } ItemStack[] ingotShapes = { new ItemStack(Item.brick), new ItemStack(Item.netherrackBrick), new ItemStack(materials, 1, 2), new ItemStack(materials, 1, 37) }; for (int i = 0; i < ingotShapes.length; i++) { tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), ingotShapes[i], false, 50); tableCasting.addCastingRecipe(ingotcast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), ingotShapes[i], false, 50); } ItemStack fullguardCast = new ItemStack(metalPattern, 1, 22); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); tableCasting.addCastingRecipe(fullguardCast, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2), new ItemStack(fullGuard, 1, Short.MAX_VALUE), false, 50); // Golden Food Stuff FluidStack goldAmount = null; if (PHConstruct.goldAppleRecipe) { goldAmount = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 8); } else { goldAmount = new FluidStack(moltenGoldFluid, TConstruct.nuggetLiquidValue * 8); } tableCasting.addCastingRecipe(new ItemStack(Item.appleGold, 1), goldAmount, new ItemStack(Item.appleRed), true, 50); tableCasting.addCastingRecipe(new ItemStack(Item.goldenCarrot, 1), goldAmount, new ItemStack(Item.carrot), true, 50); tableCasting.addCastingRecipe(new ItemStack(Item.speckledMelon, 1), goldAmount, new ItemStack(Item.melon), true, 50); tableCasting.addCastingRecipe(new ItemStack(goldHead), goldAmount, new ItemStack(Item.skull, 1, 3), true, 50); } private void addRecipesForBasinCasting () { LiquidCasting basinCasting = TConstructRegistry.getBasinCasting(); // Block Casting basinCasting.addCastingRecipe(new ItemStack(Block.blockIron), new FluidStack(moltenIronFluid, TConstruct.blockLiquidValue), null, true, 100); //Iron basinCasting.addCastingRecipe(new ItemStack(Block.blockGold), new FluidStack(moltenGoldFluid, TConstruct.blockLiquidValue), null, true, 100); //gold basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 3), new FluidStack(moltenCopperFluid, TConstruct.blockLiquidValue), null, true, 100); //copper basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 5), new FluidStack(moltenTinFluid, TConstruct.blockLiquidValue), null, true, 100); //tin basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 6), new FluidStack(moltenAluminumFluid, TConstruct.blockLiquidValue), null, true, 100); //aluminum basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 0), new FluidStack(moltenCobaltFluid, TConstruct.blockLiquidValue), null, true, 100); //cobalt basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 1), new FluidStack(moltenArditeFluid, TConstruct.blockLiquidValue), null, true, 100); //ardite basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 4), new FluidStack(moltenBronzeFluid, TConstruct.blockLiquidValue), null, true, 100); //bronze basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 7), new FluidStack(moltenAlubrassFluid, TConstruct.blockLiquidValue), null, true, 100); //albrass basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 2), new FluidStack(moltenManyullynFluid, TConstruct.blockLiquidValue), null, true, 100); //manyullyn basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 8), new FluidStack(moltenAlumiteFluid, TConstruct.blockLiquidValue), null, true, 100); //alumite basinCasting.addCastingRecipe(new ItemStack(Block.obsidian), new FluidStack(moltenObsidianFluid, TConstruct.oreLiquidValue), null, true, 100);// obsidian basinCasting.addCastingRecipe(new ItemStack(metalBlock, 1, 9), new FluidStack(moltenSteelFluid, TConstruct.blockLiquidValue), null, true, 100); //steel basinCasting.addCastingRecipe(new ItemStack(clearGlass, 1, 0), new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //glass basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 4), new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue), null, true, 100); //seared stone basinCasting.addCastingRecipe(new ItemStack(smeltery, 1, 5), new FluidStack(moltenStoneFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.cobblestone), true, 100); basinCasting.addCastingRecipe(new ItemStack(Block.blockEmerald), new FluidStack(moltenEmeraldFluid, 640 * 9), null, true, 100); //emerald basinCasting.addCastingRecipe(new ItemStack(speedBlock, 1, 0), new FluidStack(moltenTinFluid, TConstruct.nuggetLiquidValue), new ItemStack(Block.gravel), true, 100); //brownstone if (PHConstruct.craftEndstone) basinCasting.addCastingRecipe(new ItemStack(Block.whiteStone), new FluidStack(moltenEnderFluid, TConstruct.chunkLiquidValue), new ItemStack(Block.obsidian), true, 100); //endstone basinCasting.addCastingRecipe(new ItemStack(metalBlock.blockID, 1, 10), new FluidStack(moltenEnderFluid, 1000), null, true, 100); //ender basinCasting.addCastingRecipe(new ItemStack(glueBlock), new FluidStack(glueFluid, TConstruct.blockLiquidValue), null, true, 100); //glue // basinCasting.addCastingRecipe(new ItemStack(slimeGel, 1, 0), new FluidStack(blueSlimeFluid, FluidContainerRegistry.BUCKET_VOLUME), null, true, 100); //Armor casts /*FluidRenderProperties frp = new FluidRenderProperties(Applications.BASIN.minHeight, 0.65F, Applications.BASIN); FluidStack aluFlu = new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * 10); FluidStack gloFlu = new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 10); ItemStack[] armor = { new ItemStack(helmetWood), new ItemStack(chestplateWood), new ItemStack(leggingsWood), new ItemStack(bootsWood) }; for (int sc = 0; sc < armor.length; sc++) { basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), aluFlu, armor[sc], 50, frp); basinCasting.addCastingRecipe(new ItemStack(armorPattern, 1, sc), gloFlu, armor[sc], 50, frp); }*/ } private void addRecipesForSmeltery () { //Alloy Smelting Smeltery.addAlloyMixing(new FluidStack(moltenBronzeFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsBronzeAlloy), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(moltenTinFluid, TConstruct.ingotLiquidValue)); //Bronze Smeltery.addAlloyMixing(new FluidStack(moltenAlubrassFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsAluminumBrassAlloy), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 3), new FluidStack(moltenCopperFluid, TConstruct.ingotLiquidValue * 1)); //Aluminum Brass Smeltery.addAlloyMixing(new FluidStack(moltenAlumiteFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsAlumiteAlloy), new FluidStack(moltenAluminumFluid, TConstruct.ingotLiquidValue * 5), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2), new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); //Alumite Smeltery.addAlloyMixing(new FluidStack(moltenManyullynFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsManyullynAlloy), new FluidStack(moltenCobaltFluid, TConstruct.ingotLiquidValue), new FluidStack(moltenArditeFluid, TConstruct.ingotLiquidValue)); //Manyullyn Smeltery.addAlloyMixing(new FluidStack(pigIronFluid, TConstruct.ingotLiquidValue * PHConstruct.ingotsPigironAlloy), new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue), new FluidStack(moltenEmeraldFluid, 640), new FluidStack(bloodFluid, 80)); //Pigiron // Stone parts for (int sc = 0; sc < patternOutputs.length; sc++) { if (patternOutputs[sc] != null) { Smeltery.addMelting(FluidType.Stone, new ItemStack(patternOutputs[sc], 1, 1), 1, (8 * ((IPattern) woodPattern).getPatternCost(new ItemStack(woodPattern, 1, sc + 1))) / 2); } } // Chunks Smeltery.addMelting(FluidType.Stone, new ItemStack(toolShard, 1, 1), 0, 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(toolShard, 1, 2), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Obsidian, new ItemStack(toolShard, 1, 6), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Cobalt, new ItemStack(toolShard, 1, 10), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Ardite, new ItemStack(toolShard, 1, 11), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Manyullyn, new ItemStack(toolShard, 1, 12), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Copper, new ItemStack(toolShard, 1, 13), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Bronze, new ItemStack(toolShard, 1, 14), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Alumite, new ItemStack(toolShard, 1, 15), 0, TConstruct.chunkLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(toolShard, 1, 16), 0, TConstruct.chunkLiquidValue); // Items Smeltery.addMelting(FluidType.AluminumBrass, new ItemStack(blankPattern, 4, 1), -50, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(blankPattern, 4, 2), -50, TConstruct.ingotLiquidValue * 2); Smeltery.addMelting(FluidType.Glue, new ItemStack(materials, 1, 36), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Ender, new ItemStack(Item.enderPearl, 4), 0, 250); Smeltery.addMelting(metalBlock, 10, 50, new FluidStack(moltenEnderFluid, 1000)); Smeltery.addMelting(FluidType.Water, new ItemStack(Item.snowball, 1, 0), 0, 125); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.flintAndSteel, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.compass, 1, 0), 0, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bucketEmpty), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartEmpty), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartCrate), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartPowered), 0, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.minecartHopper), 50, TConstruct.ingotLiquidValue * 10); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.doorIron), 0, TConstruct.ingotLiquidValue * 6); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.cauldron), 0, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shears), 0, TConstruct.ingotLiquidValue * 2); Smeltery.addMelting(FluidType.Emerald, new ItemStack(Item.emerald), -50, 640); //Blocks melt as themselves! //Ore Smeltery.addMelting(Block.oreIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.oreGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(oreGravel, 1, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 2)); //Blocks Smeltery.addMelting(Block.blockIron, 0, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.blockGold, 0, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue * 9)); Smeltery.addMelting(Block.obsidian, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(Block.ice, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 1000)); Smeltery.addMelting(Block.blockSnow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 500)); Smeltery.addMelting(Block.snow, 0, 75, new FluidStack(FluidRegistry.getFluid("water"), 250)); Smeltery.addMelting(Block.sand, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.glass, 0, 625, new FluidStack(moltenGlassFluid, FluidContainerRegistry.BUCKET_VOLUME)); Smeltery.addMelting(Block.thinGlass, 0, 625, new FluidStack(moltenGlassFluid, 250)); Smeltery.addMelting(Block.stone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.cobblestone, 0, 800, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 18)); Smeltery.addMelting(Block.blockEmerald, 0, 800, new FluidStack(moltenEmeraldFluid, 640 * 9)); Smeltery.addMelting(glueBlock, 0, 250, new FluidStack(glueFluid, TConstruct.blockLiquidValue)); Smeltery.addMelting(craftedSoil, 1, 600, new FluidStack(moltenStoneFluid, TConstruct.ingotLiquidValue / 4)); Smeltery.addMelting(clearGlass, 0, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(glassPane, 0, 350, new FluidStack(moltenGlassFluid, 250)); for (int i = 0; i < 16; i++) { Smeltery.addMelting(stainedGlassClear, i, 500, new FluidStack(moltenGlassFluid, 1000)); Smeltery.addMelting(stainedGlassClearPane, i, 350, new FluidStack(moltenGlassFluid, 250)); } //Bricks Smeltery.addMelting(multiBrick, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrickFancy, 4, 600, new FluidStack(moltenIronFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrick, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrickFancy, 5, 400, new FluidStack(moltenGoldFluid, TConstruct.ingotLiquidValue)); Smeltery.addMelting(multiBrick, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); Smeltery.addMelting(multiBrickFancy, 0, 800, new FluidStack(moltenObsidianFluid, TConstruct.ingotLiquidValue * 2)); //Vanilla blocks Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.fenceIron), 0, TConstruct.ingotLiquidValue * 6 / 16); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.pressurePlateIron), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.pressurePlateGold, 4), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.rail), 0, TConstruct.ingotLiquidValue * 6 / 16); Smeltery.addMelting(FluidType.Gold, new ItemStack(Block.railPowered), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railDetector), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.railActivator), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Obsidian, new ItemStack(Block.enchantmentTable), 0, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.cauldron), 0, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 0), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 1), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.anvil, 1, 2), 200, TConstruct.ingotLiquidValue * 31); Smeltery.addMelting(FluidType.Iron, new ItemStack(Block.hopperBlock), 0, TConstruct.ingotLiquidValue * 5); //Vanilla Armor Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.helmetIron, 1, 0), 50, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.plateIron, 1, 0), 50, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.legsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.bootsIron, 1, 0), 50, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.helmetGold, 1, 0), 50, TConstruct.ingotLiquidValue * 5); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.plateGold, 1, 0), 50, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.legsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 7); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.bootsGold, 1, 0), 50, TConstruct.ingotLiquidValue * 4); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.helmetChain, 1, 0), 25, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.plateChain, 1, 0), 50, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.legsChain, 1, 0), 50, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Steel, new ItemStack(Item.bootsChain, 1, 0), 25, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.horseArmorIron, 1), 100, TConstruct.ingotLiquidValue * 8); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.horseArmorGold, 1), 100, TConstruct.ingotLiquidValue * 8); //Vanilla tools Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.hoeIron, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.swordIron, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.shovelIron, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.pickaxeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Iron, new ItemStack(Item.axeIron, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.hoeGold, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.swordGold, 1, 0), 0, TConstruct.oreLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.shovelGold, 1, 0), 0, TConstruct.ingotLiquidValue); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.pickaxeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3); Smeltery.addMelting(FluidType.Gold, new ItemStack(Item.axeGold, 1, 0), 0, TConstruct.ingotLiquidValue * 3); } private void addRecipesForDryingRack () { //Drying rack DryingRackRecipes.addDryingRecipe(Item.beefRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 0)); DryingRackRecipes.addDryingRecipe(Item.chickenRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 1)); DryingRackRecipes.addDryingRecipe(Item.porkRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 2)); //DryingRackRecipes.addDryingRecipe(Item.muttonRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 3)); DryingRackRecipes.addDryingRecipe(Item.fishRaw, 20 * 60 * 5, new ItemStack(jerky, 1, 4)); DryingRackRecipes.addDryingRecipe(Item.rottenFlesh, 20 * 60 * 5, new ItemStack(jerky, 1, 5)); DryingRackRecipes.addDryingRecipe(new ItemStack(strangeFood, 1, 0), 20 * 60 * 5, new ItemStack(jerky, 1, 6)); DryingRackRecipes.addDryingRecipe(new ItemStack(strangeFood, 1, 1), 20 * 60 * 5, new ItemStack(jerky, 1, 7)); //DryingRackRecipes.addDryingRecipe(new ItemStack(jerky, 1, 5), 20 * 60 * 10, Item.leather); } private void addRecipesForChisel () { /* Detailing */ Detailing chiseling = TConstructRegistry.getChiselDetailing(); chiseling.addDetailing(Block.stone, 0, Block.stoneBrick, 0, chisel); chiseling.addDetailing(speedBlock, 0, speedBlock, 1, chisel); chiseling.addDetailing(speedBlock, 2, speedBlock, 3, chisel); chiseling.addDetailing(speedBlock, 3, speedBlock, 4, chisel); chiseling.addDetailing(speedBlock, 4, speedBlock, 5, chisel); chiseling.addDetailing(speedBlock, 5, speedBlock, 6, chisel); chiseling.addDetailing(Block.obsidian, 0, multiBrick, 0, chisel); chiseling.addDetailing(Block.sandStone, 0, Block.sandStone, 2, chisel); chiseling.addDetailing(Block.sandStone, 2, Block.sandStone, 1, chisel); chiseling.addDetailing(Block.sandStone, 1, multiBrick, 1, chisel); //chiseling.addDetailing(Block.netherrack, 0, multiBrick, 2, chisel); //chiseling.addDetailing(Block.stone_refined, 0, multiBrick, 3, chisel); chiseling.addDetailing(Item.ingotIron, 0, multiBrick, 4, chisel); chiseling.addDetailing(Item.ingotGold, 0, multiBrick, 5, chisel); chiseling.addDetailing(Item.dyePowder, 4, multiBrick, 6, chisel); chiseling.addDetailing(Item.diamond, 0, multiBrick, 7, chisel); chiseling.addDetailing(Item.redstone, 0, multiBrick, 8, chisel); chiseling.addDetailing(Item.bone, 0, multiBrick, 9, chisel); chiseling.addDetailing(Item.slimeBall, 0, multiBrick, 10, chisel); chiseling.addDetailing(strangeFood, 0, multiBrick, 11, chisel); chiseling.addDetailing(Block.whiteStone, 0, multiBrick, 12, chisel); chiseling.addDetailing(materials, 18, multiBrick, 13, chisel); // adding multiBrick / multiBrickFanxy meta 0-13 to list for (int sc = 0; sc < 14; sc++) { chiseling.addDetailing(multiBrick, sc, multiBrickFancy, sc, chisel); } chiseling.addDetailing(Block.stoneBrick, 0, multiBrickFancy, 15, chisel); chiseling.addDetailing(multiBrickFancy, 15, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrickFancy, 14, Block.stoneBrick, 3, chisel); /*chiseling.addDetailing(multiBrick, 14, multiBrickFancy, 14, chisel); chiseling.addDetailing(multiBrick, 15, multiBrickFancy, 15, chisel);*/ chiseling.addDetailing(smeltery, 4, smeltery, 6, chisel); chiseling.addDetailing(smeltery, 6, smeltery, 11, chisel); chiseling.addDetailing(smeltery, 11, smeltery, 2, chisel); chiseling.addDetailing(smeltery, 2, smeltery, 8, chisel); chiseling.addDetailing(smeltery, 8, smeltery, 9, chisel); chiseling.addDetailing(smeltery, 9, smeltery, 10, chisel); } void setupToolTabs () { TConstructRegistry.materialTab.init(new ItemStack(titleIcon, 1, 255)); TConstructRegistry.blockTab.init(new ItemStack(toolStationWood)); ItemStack tool = new ItemStack(longsword, 1, 0); NBTTagCompound compound = new NBTTagCompound(); compound.setCompoundTag("InfiTool", new NBTTagCompound()); compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2); compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0); compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10); tool.setTagCompound(compound); //TConstruct. TConstructRegistry.toolTab.init(tool); } public void addLoot () { //Item, min, max, weight ChestGenHooks.getInfo(ChestGenHooks.DUNGEON_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 5)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_DESERT_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); ChestGenHooks.getInfo(ChestGenHooks.PYRAMID_JUNGLE_CHEST).addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 10)); tinkerHouseChest = new ChestGenHooks("TinkerHouse", new WeightedRandomChestContent[0], 3, 27); tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(heartCanister, 1, 1), 1, 1, 1)); int[] validTypes = { 0, 1, 2, 3, 4, 5, 6, 8, 9, 13, 14, 17 }; Item[] partTypes = { pickaxeHead, shovelHead, hatchetHead, binding, swordBlade, wideGuard, handGuard, crossbar, knifeBlade, frypanHead, signHead, chiselHead }; for (int partIter = 0; partIter < partTypes.length; partIter++) { for (int typeIter = 0; typeIter < validTypes.length; typeIter++) { tinkerHouseChest.addItem(new WeightedRandomChestContent(new ItemStack(partTypes[partIter], 1, validTypes[typeIter]), 1, 1, 15)); } } tinkerHousePatterns = new ChestGenHooks("TinkerPatterns", new WeightedRandomChestContent[0], 5, 30); for (int i = 0; i < 13; i++) { tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, i + 1), 1, 3, 20)); } tinkerHousePatterns.addItem(new WeightedRandomChestContent(new ItemStack(woodPattern, 1, 22), 1, 3, 40)); } public static String[] liquidNames; public void oreRegistry () { OreDictionary.registerOre("oreCobalt", new ItemStack(oreSlag, 1, 1)); OreDictionary.registerOre("oreArdite", new ItemStack(oreSlag, 1, 2)); OreDictionary.registerOre("oreCopper", new ItemStack(oreSlag, 1, 3)); OreDictionary.registerOre("oreTin", new ItemStack(oreSlag, 1, 4)); OreDictionary.registerOre("oreAluminum", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreAluminium", new ItemStack(oreSlag, 1, 5)); OreDictionary.registerOre("oreIron", new ItemStack(oreGravel, 1, 0)); OreDictionary.registerOre("oreGold", new ItemStack(oreGravel, 1, 1)); OreDictionary.registerOre("oreCobalt", new ItemStack(oreGravel, 1, 5)); OreDictionary.registerOre("oreCopper", new ItemStack(oreGravel, 1, 2)); OreDictionary.registerOre("oreTin", new ItemStack(oreGravel, 1, 3)); OreDictionary.registerOre("oreAluminum", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("oreAluminium", new ItemStack(oreGravel, 1, 4)); OreDictionary.registerOre("ingotCobalt", new ItemStack(materials, 1, 3)); OreDictionary.registerOre("ingotArdite", new ItemStack(materials, 1, 4)); OreDictionary.registerOre("ingotManyullyn", new ItemStack(materials, 1, 5)); OreDictionary.registerOre("ingotCopper", new ItemStack(materials, 1, 9)); OreDictionary.registerOre("ingotTin", new ItemStack(materials, 1, 10)); OreDictionary.registerOre("ingotAluminum", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("ingotAluminium", new ItemStack(materials, 1, 11)); OreDictionary.registerOre("ingotBronze", new ItemStack(materials, 1, 13)); OreDictionary.registerOre("ingotAluminumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAluminiumBrass", new ItemStack(materials, 1, 14)); OreDictionary.registerOre("ingotAlumite", new ItemStack(materials, 1, 15)); OreDictionary.registerOre("ingotSteel", new ItemStack(materials, 1, 16)); ensureOreIsRegistered("ingotIron", new ItemStack(Item.ingotIron)); ensureOreIsRegistered("ingotGold", new ItemStack(Item.ingotGold)); OreDictionary.registerOre("ingotObsidian", new ItemStack(materials, 1, 18)); OreDictionary.registerOre("ingotPigIron", new ItemStack(materials, 1, 34)); OreDictionary.registerOre("itemRawRubber", new ItemStack(materials, 1, 36)); OreDictionary.registerOre("blockCobalt", new ItemStack(metalBlock, 1, 0)); OreDictionary.registerOre("blockArdite", new ItemStack(metalBlock, 1, 1)); OreDictionary.registerOre("blockManyullyn", new ItemStack(metalBlock, 1, 2)); OreDictionary.registerOre("blockCopper", new ItemStack(metalBlock, 1, 3)); OreDictionary.registerOre("blockBronze", new ItemStack(metalBlock, 1, 4)); OreDictionary.registerOre("blockTin", new ItemStack(metalBlock, 1, 5)); OreDictionary.registerOre("blockAluminum", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminium", new ItemStack(metalBlock, 1, 6)); OreDictionary.registerOre("blockAluminumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAluminiumBrass", new ItemStack(metalBlock, 1, 7)); OreDictionary.registerOre("blockAlumite", new ItemStack(metalBlock, 1, 8)); OreDictionary.registerOre("blockSteel", new ItemStack(metalBlock, 1, 9)); ensureOreIsRegistered("blockIron", new ItemStack(Block.blockIron)); ensureOreIsRegistered("blockGold", new ItemStack(Block.blockGold)); OreDictionary.registerOre("nuggetIron", new ItemStack(materials, 1, 19)); OreDictionary.registerOre("nuggetIron", new ItemStack(oreBerries, 1, 0)); OreDictionary.registerOre("nuggetCopper", new ItemStack(materials, 1, 20)); OreDictionary.registerOre("nuggetCopper", new ItemStack(oreBerries, 1, 2)); OreDictionary.registerOre("nuggetTin", new ItemStack(materials, 1, 21)); OreDictionary.registerOre("nuggetTin", new ItemStack(oreBerries, 1, 3)); OreDictionary.registerOre("nuggetAluminum", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminum", new ItemStack(oreBerries, 1, 4)); OreDictionary.registerOre("nuggetAluminium", new ItemStack(materials, 1, 22)); OreDictionary.registerOre("nuggetAluminium", new ItemStack(oreBerries, 1, 4)); OreDictionary.registerOre("nuggetAluminumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetAluminiumBrass", new ItemStack(materials, 1, 24)); OreDictionary.registerOre("nuggetObsidian", new ItemStack(materials, 1, 27)); OreDictionary.registerOre("nuggetCobalt", new ItemStack(materials, 1, 28)); OreDictionary.registerOre("nuggetArdite", new ItemStack(materials, 1, 29)); OreDictionary.registerOre("nuggetManyullyn", new ItemStack(materials, 1, 30)); OreDictionary.registerOre("nuggetBronze", new ItemStack(materials, 1, 31)); OreDictionary.registerOre("nuggetAlumite", new ItemStack(materials, 1, 32)); OreDictionary.registerOre("nuggetSteel", new ItemStack(materials, 1, 33)); OreDictionary.registerOre("nuggetGold", new ItemStack(oreBerries, 1, 1)); ensureOreIsRegistered("nuggetGold", new ItemStack(Item.goldNugget)); OreDictionary.registerOre("nuggetPigIron", new ItemStack(materials, 1, 35)); OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab1, 1, Short.MAX_VALUE)); OreDictionary.registerOre("slabCloth", new ItemStack(woolSlab2, 1, Short.MAX_VALUE)); ensureOreIsRegistered("stoneMossy", new ItemStack(Block.stoneBrick, 1, 1)); ensureOreIsRegistered("stoneMossy", new ItemStack(Block.cobblestoneMossy)); OreDictionary.registerOre("crafterWood", new ItemStack(Block.workbench, 1)); OreDictionary.registerOre("craftingTableWood", new ItemStack(Block.workbench, 1)); OreDictionary.registerOre("torchStone", new ItemStack(stoneTorch)); String[] matNames = { "wood", "stone", "iron", "flint", "cactus", "bone", "obsidian", "netherrack", "slime", "paper", "cobalt", "ardite", "manyullyn", "copper", "bronze", "alumite", "steel", "blueslime" }; for (int i = 0; i < matNames.length; i++) OreDictionary.registerOre(matNames[i] + "Rod", new ItemStack(toolRod, 1, i)); OreDictionary.registerOre("thaumiumRod", new ItemStack(toolRod, 1, 31)); String[] glassTypes = { "glassBlack", "glassRed", "glassGreen", "glassBrown", "glassBlue", "glassPurple", "glassCyan", "glassLightGray", "glassGray", "glassPink", "glassLime", "glassYellow", "glassLightBlue", "glassMagenta", "glassOrange", "glassWhite" }; for (int i = 0; i < 16; i++) { OreDictionary.registerOre(glassTypes[15 - i], new ItemStack(stainedGlassClear, 1, i)); } BlockDispenser.dispenseBehaviorRegistry.putObject(titleIcon, new TDispenserBehaviorSpawnEgg()); BlockDispenser.dispenseBehaviorRegistry.putObject(arrow, new TDispenserBehaviorArrow()); //Vanilla stuff OreDictionary.registerOre("slimeball", new ItemStack(Item.slimeBall)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 0)); OreDictionary.registerOre("slimeball", new ItemStack(strangeFood, 1, 1)); OreDictionary.registerOre("slimeball", new ItemStack(materials, 1, 36)); OreDictionary.registerOre("glass", new ItemStack(clearGlass)); OreDictionary.registerOre("glass", new ItemStack(Block.glass)); RecipeRemover.removeShapedRecipe(new ItemStack(Block.pistonStickyBase)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.magmaCream)); RecipeRemover.removeShapedRecipe(new ItemStack(Item.leash)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Block.pistonStickyBase), "slimeball", Block.pistonBase)); GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(Item.magmaCream), "slimeball", Item.blazePowder)); GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Item.leash, 2), "ss ", "sS ", " s", 's', Item.silk, 'S', "slimeball")); } private void ensureOreIsRegistered (String oreName, ItemStack is) { int oreId = OreDictionary.getOreID(is); if (oreId == -1) { OreDictionary.registerOre(oreName, is); } } public static boolean thaumcraftAvailable; public void intermodCommunication () { if (Loader.isModLoaded("Thaumcraft")) { FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 13)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 14)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerry, 1, 15)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 12)); FMLInterModComms.sendMessage("Thaumcraft", "harvestClickableCrop", new ItemStack(oreBerrySecond, 1, 13)); } if (Loader.isModLoaded("Mystcraft")) { MystImcHandler.blacklistFluids(); } if (Loader.isModLoaded("BuildCraft|Transport")) { BCImcHandler.registerFacades(); } /* FORESTRY * Edit these strings to change what items are added to the backpacks * Format info: "[backpack ID]@[item ID].[metadata or *]:[next item]" and so on * Avaliable backpack IDs: forester, miner, digger, hunter, adventurer, builder * May add more backpack items later - Spyboticsguy */ if (Loader.isModLoaded("Forestry")) { String builderItems = "builder@" + String.valueOf(stoneTorch.blockID) + ":*"; FMLInterModComms.sendMessage("Forestry", "add-backpack-items", builderItems); } if (!Loader.isModLoaded("AppliedEnergistics")) { AEImcHandler.registerForSpatialIO(); } } private static boolean initRecipes; public static void modRecipes () { if (!initRecipes) { initRecipes = true; if (PHConstruct.removeVanillaToolRecipes) { RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordWood)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordStone)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordIron)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordDiamond)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.pickaxeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.axeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.shovelGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.hoeGold)); RecipeRemover.removeAnyRecipe(new ItemStack(Item.swordGold)); } } } public static void addShapedRecipeFirst (List recipeList, ItemStack itemstack, Object... objArray) { String var3 = ""; int var4 = 0; int var5 = 0; int var6 = 0; if (objArray[var4] instanceof String[]) { String[] var7 = ((String[]) objArray[var4++]); for (int var8 = 0; var8 < var7.length; ++var8) { String var9 = var7[var8]; ++var6; var5 = var9.length(); var3 = var3 + var9; } } else { while (objArray[var4] instanceof String) { String var11 = (String) objArray[var4++]; ++var6; var5 = var11.length(); var3 = var3 + var11; } } HashMap var12; for (var12 = new HashMap(); var4 < objArray.length; var4 += 2) { Character var13 = (Character) objArray[var4]; ItemStack var14 = null; if (objArray[var4 + 1] instanceof Item) { var14 = new ItemStack((Item) objArray[var4 + 1]); } else if (objArray[var4 + 1] instanceof Block) { var14 = new ItemStack((Block) objArray[var4 + 1], 1, Short.MAX_VALUE); } else if (objArray[var4 + 1] instanceof ItemStack) { var14 = (ItemStack) objArray[var4 + 1]; } var12.put(var13, var14); } ItemStack[] var15 = new ItemStack[var5 * var6]; for (int var16 = 0; var16 < var5 * var6; ++var16) { char var10 = var3.charAt(var16); if (var12.containsKey(Character.valueOf(var10))) { var15[var16] = ((ItemStack) var12.get(Character.valueOf(var10))).copy(); } else { var15[var16] = null; } } ShapedRecipes var17 = new ShapedRecipes(var5, var6, var15, itemstack); recipeList.add(0, var17); } public void modIntegration () { ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TContent.pickaxeHead, 1, 6), new ItemStack(TContent.toolRod, 1, 2), new ItemStack(TContent.binding, 1, 6), ""); /* Natura */ Block taintedSoil = GameRegistry.findBlock("Natura", "soil.tainted"); Block heatSand = GameRegistry.findBlock("Natura", "heatsand"); if (taintedSoil != null && heatSand != null) GameRegistry.addShapelessRecipe(new ItemStack(craftedSoil, 2, 6), Item.netherStalkSeeds, taintedSoil, heatSand); /*TE3 Flux*/ ItemStack batHardened = GameRegistry.findItemStack("ThermalExpansion", "capacitorHardened", 1); if (batHardened != null) { modFlux.batteries.add(batHardened); } ItemStack basicCell = GameRegistry.findItemStack("ThermalExpansion", "cellBasic", 1); if (basicCell != null) { modFlux.batteries.add(basicCell); } if (batHardened != null) TConstructClientRegistry.registerManualModifier("fluxmod", ironpick.copy(), (ItemStack) batHardened); if (basicCell != null) TConstructClientRegistry.registerManualModifier("fluxmod2", ironpick.copy(), (ItemStack) basicCell); /* Thaumcraft */ Object obj = getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems"); if (obj != null) { TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools."); thaumcraftAvailable = true; TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true); TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "Thaumic"); PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, "Thaumium", new ItemStack(toolShard, 1, 31), new ItemStack(toolRod, 1, 31), 31); for (int meta = 0; meta < patternOutputs.length; meta++) { if (patternOutputs[meta] != null) TConstructRegistry.addPartMapping(woodPattern.itemID, meta + 1, 31, new ItemStack(patternOutputs[meta], 1, 31)); } TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(bowstring, 1, 1), 1F, 1F, 0.9f); TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f); TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F); } else { TConstruct.logger.warning("Thaumcraft not detected."); } if (Loader.isModLoaded("Natura")) { try { Object plantItem = getStaticItem("plantItem", "mods.natura.common.NContent"); TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(bowstring, 1, 2), 1.2F, 0.8F, 1.3f); } catch (Exception e) { } //No need to handle } ItemStack ingotcast = new ItemStack(metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); LiquidCasting basinCasting = TConstructRegistry.instance.getBasinCasting(); /* Thermal Expansion 3 Metals */ ArrayList<ItemStack> ores = OreDictionary.getOres("ingotNickel"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotLead"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotSilver"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotPlatinum"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.ingotLiquidValue), ingotcast, 80); } ores = OreDictionary.getOres("ingotInvar"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenInvarFluid, 24), new FluidStack(moltenIronFluid, 16), new FluidStack(moltenNickelFluid, 8)); //Invar } ores = OreDictionary.getOres("ingotElectrum"); if (ores.size() > 0) { tableCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.ingotLiquidValue), ingotcast, 80); Smeltery.addAlloyMixing(new FluidStack(moltenElectrumFluid, 16), new FluidStack(moltenGoldFluid, 8), new FluidStack(moltenSilverFluid, 8)); //Electrum } ores = OreDictionary.getOres("blockNickel"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenNickelFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockLead"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenLeadFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockSilver"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenSilverFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockPlatinum"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenShinyFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockInvar"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenInvarFluid, TConstruct.blockLiquidValue), null, 100); } ores = OreDictionary.getOres("blockElectrum"); if (ores.size() > 0) { basinCasting.addCastingRecipe(ores.get(0), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), null, 100); } /* Extra Utilities */ ores = OreDictionary.getOres("compressedGravel1x"); if (ores.size() > 0) { basinCasting.addCastingRecipe(new ItemStack(speedBlock, 9), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue), ores.get(0), 100); } ores = OreDictionary.getOres("compressedGravel2x"); //Higher won't save properly if (ores.size() > 0) { basinCasting.addCastingRecipe(new ItemStack(speedBlock, 81), new FluidStack(moltenElectrumFluid, TConstruct.blockLiquidValue * 9), ores.get(0), 100); } /* Rubber */ ores = OreDictionary.getOres("itemRubber"); if (ores.size() > 0) { FurnaceRecipes.smelting().addSmelting(materials.itemID, 36, ores.get(0), 0.2f); } } public static Object getStaticItem (String name, String classPackage) { try { Class clazz = Class.forName(classPackage); Field field = clazz.getDeclaredField(name); Object ret = field.get(null); if (ret != null && (ret instanceof ItemStack || ret instanceof Item)) return ret; return null; } catch (Exception e) { TConstruct.logger.warning("Could not find " + name); return null; } } @Override public int getBurnTime (ItemStack fuel) { if (fuel.itemID == materials.itemID && fuel.getItemDamage() == 7) return 26400; return 0; } public void addOreDictionarySmelteryRecipes () { List<FluidType> exceptions = Arrays.asList(new FluidType[] { FluidType.Water, FluidType.Stone, FluidType.Ender, FluidType.Glass, FluidType.Slime }); for (FluidType ft : FluidType.values()) { if (exceptions.contains(ft)) continue; // Nuggets Smeltery.addDictionaryMelting("nugget" + ft.toString(), ft, -100, TConstruct.nuggetLiquidValue); // Ingots, Dust registerIngotCasting(ft); Smeltery.addDictionaryMelting("ingot" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue); Smeltery.addDictionaryMelting("dust" + ft.toString(), ft, -75, TConstruct.ingotLiquidValue); // Factorization support Smeltery.addDictionaryMelting("crystalline" + ft.toString(), ft, -50, TConstruct.ingotLiquidValue); // Ores Smeltery.addDictionaryMelting("ore" + ft.toString(), ft, 0, TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre); // NetherOres support Smeltery.addDictionaryMelting("oreNether" + ft.toString(), ft, 75, TConstruct.ingotLiquidValue * PHConstruct.ingotsPerOre * 2); // Blocks Smeltery.addDictionaryMelting("block" + ft.toString(), ft, 100, TConstruct.blockLiquidValue); if (ft.isToolpart) { registerPatternMaterial("ingot" + ft.toString(), 2, ft.toString()); registerPatternMaterial("block" + ft.toString(), 18, ft.toString()); } } //Compressed materials for (int i = 1; i <= 8; i++) { Smeltery.addDictionaryMelting("compressedCobblestone" + i + "x", FluidType.Stone, 0, TConstruct.ingotLiquidValue / 18 * (9 ^ i)); } Smeltery.addDictionaryMelting("compressedSand1x", FluidType.Glass, 175, FluidContainerRegistry.BUCKET_VOLUME * 9); registerPatternMaterial("plankWood", 2, "Wood"); registerPatternMaterial("stickWood", 1, "Wood"); registerPatternMaterial("slabWood", 1, "Wood"); registerPatternMaterial("compressedCobblestone1x", 18, "Stone"); } private void registerPatternMaterial (String oreName, int value, String materialName) { for (ItemStack ore : OreDictionary.getOres(oreName)) { PatternBuilder.instance.registerMaterial(ore, value, materialName); } } private void registerIngotCasting (FluidType ft) { ItemStack pattern = new ItemStack(TContent.metalPattern, 1, 0); LiquidCasting tableCasting = TConstructRegistry.instance.getTableCasting(); for (ItemStack ore : OreDictionary.getOres("ingot" + ft.toString())) { tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenAlubrassFluid, TConstruct.ingotLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50); tableCasting.addCastingRecipe(pattern, new FluidStack(TContent.moltenGoldFluid, TConstruct.oreLiquidValue), new ItemStack(ore.itemID, 1, ore.getItemDamage()), false, 50); tableCasting.addCastingRecipe(new ItemStack(ore.itemID, 1, ore.getItemDamage()), new FluidStack(ft.fluid, TConstruct.ingotLiquidValue), pattern, 80); } } public void addAchievements () { HashMap<String, Achievement> achievements = TAchievements.achievements; achievements.put("tconstruct.beginner", new Achievement(2741, "tconstruct.beginner", 0, 0, manualBook, null).setIndependent().registerAchievement()); achievements.put("tconstruct.pattern", new Achievement(2742, "tconstruct.pattern", 2, 1, blankPattern, achievements.get("tconstruct.beginner")).registerAchievement()); achievements.put("tconstruct.tinkerer", new Achievement(2743, "tconstruct.tinkerer", 2, 2, new ItemStack(titleIcon, 1, 4096), achievements.get("tconstruct.pattern")).registerAchievement()); achievements.put("tconstruct.preparedFight", new Achievement(2744, "tconstruct.preparedFight", 1, 3, new ItemStack(titleIcon, 1, 4097), achievements.get("tconstruct.tinkerer")).registerAchievement()); achievements.put("tconstruct.proTinkerer", new Achievement(2745, "tconstruct.proTinkerer", 4, 4, new ItemStack(titleIcon, 1, 4098), achievements.get("tconstruct.tinkerer")).setSpecial() .registerAchievement()); achievements.put("tconstruct.smelteryMaker", new Achievement(2746, "tconstruct.smelteryMaker", -2, -1, smeltery, achievements.get("tconstruct.beginner")).registerAchievement()); achievements.put("tconstruct.enemySlayer", new Achievement(2747, "tconstruct.enemySlayer", 0, 5, new ItemStack(titleIcon, 1, 4099), achievements.get("tconstruct.preparedFight")).registerAchievement()); achievements.put("tconstruct.dualConvenience", new Achievement(2748, "tconstruct.dualConvenience", 0, 7, new ItemStack(titleIcon, 1, 4100), achievements.get("tconstruct.enemySlayer")) .setSpecial().registerAchievement()); } }
diff --git a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/LightWeightPlottingSystem.java b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/LightWeightPlottingSystem.java index faddc5a81..87353d171 100644 --- a/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/LightWeightPlottingSystem.java +++ b/org.dawb.workbench.plotting/src/org/dawb/workbench/plotting/system/LightWeightPlottingSystem.java @@ -1,1345 +1,1350 @@ /* * Copyright (c) 2012 European Synchrotron Radiation Facility, * Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.dawb.workbench.plotting.system; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.csstudio.swt.xygraph.figures.Annotation; import org.csstudio.swt.xygraph.figures.Axis; import org.csstudio.swt.xygraph.figures.Trace; import org.csstudio.swt.xygraph.figures.Trace.PointStyle; import org.csstudio.swt.xygraph.figures.XYGraphFlags; import org.csstudio.swt.xygraph.linearscale.AbstractScale.LabelSide; import org.csstudio.swt.xygraph.linearscale.LinearScale.Orientation; import org.csstudio.swt.xygraph.undo.AddAnnotationCommand; import org.csstudio.swt.xygraph.undo.RemoveAnnotationCommand; import org.dawb.common.ui.plot.AbstractPlottingSystem; import org.dawb.common.ui.plot.IAxis; import org.dawb.common.ui.plot.PlotType; import org.dawb.common.ui.plot.PlottingActionBarManager; import org.dawb.common.ui.plot.annotation.IAnnotation; import org.dawb.common.ui.plot.region.IRegion; import org.dawb.common.ui.plot.region.IRegion.RegionType; import org.dawb.common.ui.plot.region.IRegionContainer; import org.dawb.common.ui.plot.region.IRegionListener; import org.dawb.common.ui.plot.tool.IToolPage.ToolPageRole; import org.dawb.common.ui.plot.trace.IImageTrace; import org.dawb.common.ui.plot.trace.ILineTrace; import org.dawb.common.ui.plot.trace.ITrace; import org.dawb.common.ui.plot.trace.ITraceContainer; import org.dawb.common.ui.plot.trace.ITraceListener; import org.dawb.common.ui.plot.trace.TraceEvent; import org.dawb.gda.extensions.util.DatasetTitleUtils; import org.dawb.workbench.plotting.printing.PlotExportPrintUtil; import org.dawb.workbench.plotting.printing.PlotPrintPreviewDialog; import org.dawb.workbench.plotting.printing.PrintSettings; import org.dawb.workbench.plotting.system.swtxy.AspectAxis; import org.dawb.workbench.plotting.system.swtxy.ImageTrace; import org.dawb.workbench.plotting.system.swtxy.LineTrace; import org.dawb.workbench.plotting.system.swtxy.RegionArea; import org.dawb.workbench.plotting.system.swtxy.XYRegionGraph; import org.dawb.workbench.plotting.system.swtxy.selection.AbstractSelectionRegion; import org.dawb.workbench.plotting.system.swtxy.selection.SelectionRegionFactory; import org.dawb.workbench.plotting.util.ColorUtility; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.draw2d.FigureCanvas; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.LightweightSystem; import org.eclipse.jface.action.ActionContributionItem; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseWheelListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.printing.PrintDialog; import org.eclipse.swt.printing.Printer; import org.eclipse.swt.printing.PrinterData; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchPart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.diamond.scisoft.analysis.dataset.AbstractDataset; import uk.ac.diamond.scisoft.analysis.dataset.IntegerDataset; /** * Link between EDNA 1D plotting and csstudio plotter and fable plotter. * * * @author gerring * */ public class LightWeightPlottingSystem extends AbstractPlottingSystem { private Logger logger = LoggerFactory.getLogger(LightWeightPlottingSystem.class); private Composite parent; // Controls private Canvas xyCanvas; private XYRegionGraph xyGraph; // The plotting mode, used for updates to data private PlotType plottingMode; private LightWeightActionBarsManager lightWeightActionBarMan; public LightWeightPlottingSystem() { super(); this.lightWeightActionBarMan = (LightWeightActionBarsManager)this.actionBarManager; } public void createPlotPart(final Composite parent, final String plotName, final IActionBars bars, final PlotType hint, final IWorkbenchPart part) { super.createPlotPart(parent, plotName, bars, hint, part); this.parent = parent; createUI(); // TODO Preselect PAN for IMAGE PlotType? } @Override protected PlottingActionBarManager createActionBarManager() { return new LightWeightActionBarsManager(this); } @Override public Composite getPlotComposite() { if (xyCanvas!=null) return xyCanvas; return null; } private LightweightSystem lws; private void createUI() { if (xyCanvas!=null) return; this.xyCanvas = new FigureCanvas(parent, SWT.DOUBLE_BUFFERED|SWT.NO_REDRAW_RESIZE|SWT.NO_BACKGROUND); lws = new LightweightSystem(xyCanvas); // Stops a mouse wheel move corrupting the plotting area, but it wobbles a bit. xyCanvas.addMouseWheelListener(getMouseWheelListener()); xyCanvas.addKeyListener(getKeyListener()); lws.setControl(xyCanvas); xyCanvas.setBackground(xyCanvas.getDisplay().getSystemColor(SWT.COLOR_WHITE)); this.xyGraph = new XYRegionGraph(); xyGraph.setSelectionProvider(getSelectionProvider()); // We contain the action bars in an internal object // if the API user said they were null. This allows the API // user to say null for action bars and then use: // getPlotActionSystem().fillXXX() to add their own actions. if (bars==null) bars = lightWeightActionBarMan.createEmptyActionBars(); // bars.getMenuManager().removeAll(); // bars.getToolBarManager().removeAll(); lightWeightActionBarMan.init(); lightWeightActionBarMan.createConfigActions(); lightWeightActionBarMan.createAnnotationActions(); lightWeightActionBarMan.createRegionActions(); lightWeightActionBarMan.createToolDimensionalActions(ToolPageRole.ROLE_1D, "org.dawb.workbench.plotting.views.toolPageView.1D"); lightWeightActionBarMan.createToolDimensionalActions(ToolPageRole.ROLE_2D, "org.dawb.workbench.plotting.views.toolPageView.2D"); lightWeightActionBarMan.createToolDimensionalActions(ToolPageRole.ROLE_1D_AND_2D, "org.dawb.workbench.plotting.views.toolPageView.1D_and_2D"); lightWeightActionBarMan.createZoomActions(XYGraphFlags.COMBINED_ZOOM); lightWeightActionBarMan.createUndoRedoActions(); lightWeightActionBarMan.createExportActionsToolBar(); lightWeightActionBarMan.createAspectHistoAction(); lightWeightActionBarMan.createPalleteActions(); lightWeightActionBarMan.createOriginActions(); lightWeightActionBarMan.createExportActionsMenuBar(); lightWeightActionBarMan.createAdditionalActions(null); lws.setContents(xyGraph); xyGraph.primaryXAxis.setShowMajorGrid(true); xyGraph.primaryXAxis.setShowMinorGrid(true); xyGraph.primaryYAxis.setShowMajorGrid(true); xyGraph.primaryYAxis.setShowMinorGrid(true); xyGraph.primaryYAxis.setTitle(""); if (bars!=null) bars.updateActionBars(); if (bars!=null) bars.getToolBarManager().update(true); final MenuManager popupMenu = new MenuManager(); popupMenu.setRemoveAllWhenShown(true); // Remake menu each time xyCanvas.setMenu(popupMenu.createContextMenu(xyCanvas)); popupMenu.addMenuListener(getIMenuListener()); if (defaultPlotType!=null) { this.lightWeightActionBarMan.switchActions(defaultPlotType); } parent.layout(); } private IMenuListener popupListener; private IMenuListener getIMenuListener() { if (popupListener == null) { popupListener = new IMenuListener() { @Override public void menuAboutToShow(IMenuManager manager) { Point pnt = Display.getDefault().getCursorLocation(); Point par = xyCanvas.toDisplay(new Point(0,0)); final int xOffset = par.x+xyGraph.getLocation().x; final int yOffset = par.y+xyGraph.getLocation().y; final IFigure fig = xyGraph.findFigureAt(pnt.x-xOffset, pnt.y-yOffset); if (fig!=null) { if (fig instanceof IRegionContainer) { final IRegion region = ((IRegionContainer)fig).getRegion(); SelectionRegionFactory.fillActions(manager, region, xyGraph); } if (fig instanceof ITraceContainer) { final ITrace trace = ((ITraceContainer)fig).getTrace(); LightWeightActionBarsManager.fillTraceActions(manager, trace, LightWeightPlottingSystem.this); } if (fig instanceof Label && fig.getParent() instanceof Annotation) { LightWeightActionBarsManager.fillAnnotationConfigure(manager, (Annotation)fig.getParent(), LightWeightPlottingSystem.this); } } lightWeightActionBarMan.fillZoomActions(manager); manager.update(); } }; } return popupListener; } private MouseWheelListener mouseWheelListener; private MouseWheelListener getMouseWheelListener() { if (mouseWheelListener == null) mouseWheelListener = new MouseWheelListener() { @Override public void mouseScrolled(MouseEvent e) { if (xyGraph==null) return; if (e.count==0) return; int direction = e.count > 0 ? 1 : -1; xyGraph.setZoomLevel(e, direction*0.1d); xyGraph.repaint(); } }; return mouseWheelListener; } private KeyListener keyListener; private KeyListener getKeyListener() { if (keyListener==null) keyListener = new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (e.keyCode==16777230 || e.character=='h') { final IContributionItem action = bars.getToolBarManager().find("org.dawb.workbench.plotting.histo"); if (action!=null && action.isVisible() && action instanceof ActionContributionItem) { ActionContributionItem iaction = (ActionContributionItem)action; iaction.getAction().setChecked(!iaction.getAction().isChecked()); iaction.getAction().run(); } } else if (e.keyCode==16777217) {//Up Point point = Display.getDefault().getCursorLocation(); point.y-=1; Display.getDefault().setCursorLocation(point); } else if (e.keyCode==16777218) {//Down Point point = Display.getDefault().getCursorLocation(); point.y+=1; Display.getDefault().setCursorLocation(point); } else if (e.keyCode==16777219) {//Left Point point = Display.getDefault().getCursorLocation(); point.x-=1; Display.getDefault().setCursorLocation(point); } if (e.keyCode==16777220) {//Right Point point = Display.getDefault().getCursorLocation(); point.x+=1; Display.getDefault().setCursorLocation(point); } } }; return keyListener; } public void setFocus() { if (xyCanvas!=null) xyCanvas.setFocus(); } public void addTraceListener(final ITraceListener l) { super.addTraceListener(l); if (xyGraph!=null) ((RegionArea)xyGraph.getPlotArea()).addImageTraceListener(l); } public void removeTraceListener(final ITraceListener l) { super.removeTraceListener(l); if (xyGraph!=null) ((RegionArea)xyGraph.getPlotArea()).removeImageTraceListener(l); } public List<ITrace> updatePlot1D(AbstractDataset x, final List<AbstractDataset> ys, final IProgressMonitor monitor) { final List<ITrace> updatedAndCreated = new ArrayList<ITrace>(3); final List<AbstractDataset> unfoundYs = new ArrayList<AbstractDataset>(ys.size()); for (final AbstractDataset y : ys) { final ITrace trace = getTrace(y.getName()); if (trace!=null && trace instanceof ILineTrace) { if (x==null) x = IntegerDataset.arange(y.getSize(), IntegerDataset.INT32); final AbstractDataset finalX = x; final ILineTrace lineTrace = (ILineTrace)trace; updatedAndCreated.add(lineTrace); if (getDisplay().getThread()==Thread.currentThread()) { lineTrace.setData(finalX, y); fireTraceUpdated(new TraceEvent(lineTrace)); } else { getDisplay().syncExec(new Runnable() { public void run() { lineTrace.setData(finalX, y); fireTraceUpdated(new TraceEvent(lineTrace)); } }); } continue; } unfoundYs.add(y); } if (!unfoundYs.isEmpty()) { if (x==null) x = IntegerDataset.arange(unfoundYs.get(0).getSize(), IntegerDataset.INT32); final Collection<ITrace> news = createPlot1D(x, unfoundYs, monitor); updatedAndCreated.addAll(news); } return updatedAndCreated; } @Override public List<ITrace> createPlot1D(final AbstractDataset xIn, final List<AbstractDataset> ysIn, final IProgressMonitor monitor) { return this.createPlot1D(xIn, ysIn, null, monitor); } /** * Does not have to be called in UI thread. */ @Override public List<ITrace> createPlot1D(final AbstractDataset xIn, final List<AbstractDataset> ysIn, final String title, final IProgressMonitor monitor) { if (monitor!=null) monitor.worked(1); final Object[] oa = getIndexedDatasets(xIn, ysIn); final AbstractDataset x = (AbstractDataset)oa[0]; @SuppressWarnings("unchecked") final List<AbstractDataset> ys = (List<AbstractDataset>)oa[1]; final boolean createdIndices = (Boolean)oa[2]; final List<ITrace> traces = new ArrayList<ITrace>(7); if (getDisplay().getThread()==Thread.currentThread()) { List<ITrace> ts = createPlot1DInternal(x, ys, title, createdIndices, monitor); if (ts!=null) traces.addAll(ts); } else { getDisplay().syncExec(new Runnable() { @Override public void run() { List<ITrace> ts = createPlot1DInternal(x, ys, title, createdIndices, monitor); if (ts!=null) traces.addAll(ts); } }); } if (monitor!=null) monitor.worked(1); return traces; } private Display getDisplay() { if (part!=null) return part.getSite().getShell().getDisplay(); if (xyCanvas!=null) return xyCanvas.getDisplay(); if (parent!=null) parent.getDisplay(); return Display.getDefault(); } private Object[] getIndexedDatasets(AbstractDataset data, List<AbstractDataset> axes) { final AbstractDataset x; final List<AbstractDataset> ys; final boolean createdIndices; if (axes==null || axes.isEmpty()) { ys = new ArrayList<AbstractDataset>(1); ys.add(data); x = IntegerDataset.arange(ys.get(0).getSize()); x.setName("Index of "+data.getName()); createdIndices = true; } else { x = data; ys = axes; createdIndices = false; } return new Object[]{x,ys,createdIndices}; } @Override public void append( final String name, final Number xValue, final Number yValue, final IProgressMonitor monitor) throws Exception { if (!this.plottingMode.is1D()) throw new Exception("Can only add in 1D mode!"); if (name==null || "".equals(name)) throw new IllegalArgumentException("The dataset name must not be null or empty string!"); if (getDisplay().getThread()==Thread.currentThread()) { appendInternal(name, xValue, yValue, monitor); } else { getDisplay().syncExec(new Runnable() { @Override public void run() { appendInternal(name, xValue, yValue, monitor); } }); } } /** * Do not call before createPlotPart(...) */ public void setDefaultPlotType(PlotType mode) { this.defaultPlotType = mode; createUI(); } public ITrace updatePlot2D(final AbstractDataset data, final List<AbstractDataset> axes, final IProgressMonitor monitor) { final Collection<ITrace> traces = getTraces(IImageTrace.class); if (traces!=null && traces.size()>0) { final IImageTrace image = (IImageTrace)traces.iterator().next(); final int[] shape = image.getData()!=null ? image.getData().getShape() : null; if (shape!=null && Arrays.equals(shape, data.getShape())) { if (getDisplay().getThread()==Thread.currentThread()) { if (data.getName()!=null) xyGraph.setTitle(data.getName()); image.setData(data, image.getAxes(), false); fireTraceUpdated(new TraceEvent(image)); } else { Display.getDefault().syncExec(new Runnable() { public void run() { // This will keep the previous zoom level if there was one // and will be faster than createPlot2D(...) which autoscales. if (data.getName()!=null) xyGraph.setTitle(data.getName()); image.setData(data, image.getAxes(), false); fireTraceUpdated(new TraceEvent(image)); } }); } return image; } else { return createPlot2D(data, axes, monitor); } } else { return createPlot2D(data, axes, monitor); } } /** * Must be called in UI thread. Creates and updates image. * NOTE removes previous traces if any plotted. * * @param data * @param axes, x first. * @param monitor */ @Override public ITrace createPlot2D(final AbstractDataset data, final List<AbstractDataset> axes, final IProgressMonitor monitor) { final List<ITrace> traces = new ArrayList<ITrace>(7); if (getDisplay().getThread()==Thread.currentThread()) { ITrace ts = createPlot2DInternal(data, axes, monitor); if (ts!=null) traces.add(ts); } else { getDisplay().syncExec(new Runnable() { @Override public void run() { ITrace ts = createPlot2DInternal(data, axes, monitor); if (ts!=null) traces.add(ts); } }); } return traces.size()>0 ? traces.get(0) : null; } public ITrace createPlot2DInternal(final AbstractDataset data, List<AbstractDataset> axes, final IProgressMonitor monitor) { try { this.plottingMode = PlotType.IMAGE; this.lightWeightActionBarMan.switchActions(plottingMode); clearTraces(); // Only one image at a time! final Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); final Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); xAxis.setTitle(axes!=null&&axes.get(0).getName()!=null ? axes.get(0).getName() : ""); xAxis.setLogScale(false); yAxis.setTitle(axes!=null&&axes.get(1).getName()!=null ? axes.get(1).getName() : ""); yAxis.setLogScale(false); if (data.getName()!=null) xyGraph.setTitle(data.getName()); xyGraph.clearTraces(); if (traceMap==null) traceMap = new LinkedHashMap<String, ITrace>(31); traceMap.clear(); String traceName = data.getName(); if (part!=null&&(traceName==null||"".equals(traceName))) { traceName = part.getTitle(); } final ImageTrace trace = xyGraph.createImageTrace(traceName, xAxis, yAxis); trace.setData(data, axes, true); traceMap.put(trace.getName(), trace); xyGraph.addImageTrace(trace); fireTraceAdded(new TraceEvent(trace)); return trace; } catch (Throwable e) { logger.error("Cannot load file "+data.getName(), e); return null; } } @Override public IImageTrace createImageTrace(String traceName) { final Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); final Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); final ImageTrace trace = xyGraph.createImageTrace(traceName, xAxis, yAxis); fireTraceCreated(new TraceEvent(trace)); return trace; } /** * An IdentityHashMap used to map AbstractDataset to color used to plot it. * records keys for both strings and sets so that different models for the * file being plotted work. Sometimes dataset name is unique but the set is * not, sometimes the dataset is unique but its name is not. */ private Map<Object, Color> colorMap; // Warning can be mem leak /** * A map for recording traces to be used in the update method. * * Uses a map of abstract data set name to Trace to retrieve Trace on the * update. */ private Map<String, ITrace> traceMap; // Warning can be mem leak private List<ITrace> createPlot1DInternal( final AbstractDataset xIn, final List<AbstractDataset> ysIn, final String title, final boolean createdIndices, final IProgressMonitor monitor) { this.plottingMode = PlotType.PT1D; this.lightWeightActionBarMan.switchActions(plottingMode); Object[] oa = getOrderedDatasets(xIn, ysIn, createdIndices); final AbstractDataset x = (AbstractDataset)oa[0]; @SuppressWarnings("unchecked") final List<AbstractDataset> ys = (List<AbstractDataset>)oa[1]; if (colorMap == null && getColorOption()!=ColorOption.NONE) { if (getColorOption()==ColorOption.BY_NAME) { colorMap = new HashMap<Object,Color>(ys.size()); } else { colorMap = new IdentityHashMap<Object,Color>(ys.size()); } } if (traceMap==null) traceMap = new LinkedHashMap<String, ITrace>(31); if (xyGraph==null) return null; Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); xAxis.setVisible(true); yAxis.setVisible(true); if (title==null) { // TODO Fix titles for multiple calls to create1DPlot(...) xyGraph.setTitle(DatasetTitleUtils.getTitle(x, ys, true, rootName)); } else { xyGraph.setTitle(title); } xAxis.setTitle(DatasetTitleUtils.getName(x,rootName)); + if (!isXfirst() || createdIndices) { // Index mode, indices are integers! + xAxis.setFormatPattern("############"); + } else { + xAxis.setFormatPattern("############.##"); + } //create a trace data provider, which will provide the data to the trace. int iplot = 0; final List<ITrace> traces = new ArrayList<ITrace>(ys.size()); for (AbstractDataset y : ys) { LightWeightDataProvider traceDataProvider = new LightWeightDataProvider(x, y); //create the trace final LineTrace trace = new LineTrace(DatasetTitleUtils.getName(y,rootName), xAxis, yAxis, traceDataProvider); LineTraceImpl wrapper = new LineTraceImpl(this, trace); traces.add(wrapper); if (y.getName()!=null && !"".equals(y.getName())) { traceMap.put(y.getName(), wrapper); trace.setInternalName(y.getName()); } //set trace property trace.setPointStyle(PointStyle.NONE); int index = getTraces().size()+iplot-1; if (index<0) index=0; final Color plotColor = ColorUtility.getSwtColour(colorMap!=null?colorMap.values():null, index); if (colorMap!=null) { if (getColorOption()==ColorOption.BY_NAME) { colorMap.put(y.getName(),plotColor); } else { colorMap.put(y, plotColor); } } trace.setTraceColor(plotColor); //add the trace to xyGraph xyGraph.addTrace(trace); if (monitor!=null) monitor.worked(1); iplot++; } xyCanvas.redraw(); getDisplay().syncExec(new Runnable() { public void run() { autoscaleAxes(); autoscaleAxes(); } }); fireTracesPlotted(new TraceEvent(traces)); return traces; } public ILineTrace createLineTrace(String traceName) { Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); LightWeightDataProvider traceDataProvider = new LightWeightDataProvider(); final LineTrace trace = new LineTrace(traceName, xAxis, yAxis, traceDataProvider); final LineTraceImpl wrapper = new LineTraceImpl(this, trace); fireTraceCreated(new TraceEvent(wrapper)); return wrapper; } /** * Adds trace, makes visible * @param traceName * @return */ public void addTrace(ITrace trace) { if (traceMap==null) this.traceMap = new HashMap<String, ITrace>(7); traceMap.put(trace.getName(), trace); if (trace instanceof ImageTrace) { this.plottingMode = PlotType.IMAGE; this.lightWeightActionBarMan.switchActions(plottingMode); xyGraph.addImageTrace((ImageTrace)trace); fireTraceAdded(new TraceEvent(trace)); } else { this.plottingMode = PlotType.PT1D; this.lightWeightActionBarMan.switchActions(plottingMode); xyGraph.addTrace(((LineTraceImpl)trace).getTrace()); xyCanvas.redraw(); fireTraceAdded(new TraceEvent(trace)); } } /** * Removes a trace. * @param traceName * @return */ public void removeTrace(ITrace trace) { if (traceMap!=null) traceMap.remove(trace.getName()); if (trace instanceof LineTraceImpl) { xyGraph.removeTrace(((LineTraceImpl)trace).getTrace()); } else if (trace instanceof ImageTrace) { xyGraph.removeImageTrace((ImageTrace)trace); } xyCanvas.redraw(); fireTraceRemoved(new TraceEvent(trace)); } @Override public void renameTrace(final ITrace trace, String name) { if (traceMap!=null) traceMap.remove(trace.getName()); trace.setName(name); if (traceMap==null) traceMap = new LinkedHashMap<String, ITrace>(3); traceMap.put(name, trace); } public Collection<ITrace> getTraces() { if (traceMap==null) return Collections.emptyList(); return traceMap.values(); } @Override public ITrace getTrace(String name) { if (traceMap==null) return null; return traceMap.get(name); } private void appendInternal(final String name, Number xValue, final Number yValue, final IProgressMonitor monitor) { final ITrace wrapper = traceMap.get(name); if (wrapper==null) return; final Trace trace = ((LineTraceImpl)wrapper).getTrace(); LightWeightDataProvider prov = (LightWeightDataProvider)trace.getDataProvider(); if (prov==null) return; prov.append(xValue, yValue); } /** * Thread safe method */ @Override public AbstractDataset getData(String name) { final ITrace wrapper = traceMap.get(name); if (wrapper==null) return null; final Trace trace = ((LineTraceImpl)wrapper).getTrace(); if (trace==null) return null; return getData(name, trace, true); } /** * Thread safe method * @param name * @param trace * @param isY * @return */ protected AbstractDataset getData(String name, Trace trace, boolean isY) { if (trace==null) return null; LightWeightDataProvider prov = (LightWeightDataProvider)trace.getDataProvider(); if (prov==null) return null; return isY ? prov.getY() : prov.getX(); } private Object[] getOrderedDatasets(final AbstractDataset xIn, final List<AbstractDataset> ysIn, final boolean createdIndices) { final AbstractDataset x; final List<AbstractDataset> ys; if ((xfirst || createdIndices) && xIn!=null) { x = xIn; ys= ysIn; } else { ys = new ArrayList<AbstractDataset>(ysIn.size()+1); if (xIn!=null) ys.add(xIn); ys.addAll(ysIn); final int max = getMaxSize(ys); x = AbstractDataset.arange(0, max, 1, AbstractDataset.INT32); x.setName("Indices"); } return new Object[]{x,ys}; } /** * Override this method to provide an implementation of title setting. * @param title */ public void setTitle(final String title) { if (xyGraph!=null) { xyGraph.setTitle(title); xyGraph.repaint(); } else { throw new RuntimeException("Cannot set the plot title when the plotting system is not created or plotting something!"); } } public Color get1DPlotColor(Object object) { if (getColorOption()==ColorOption.NONE) return null; if (colorMap==null) return null; if (object==null) return null; if (colorOption==ColorOption.BY_DATA) { return colorMap.get(object); } else if (colorOption==ColorOption.BY_NAME) { return colorMap.get((String)object); } return null; } private int getMaxSize(List<AbstractDataset> sets) { int max = 1; // Cannot be less than one for (AbstractDataset set : sets) { try { max = Math.max(max, set.getSize()); } catch (NullPointerException npe) { continue; } } return max; } @Override public void reset() { if (getDisplay().getThread()==Thread.currentThread()) { resetInternal(); } else { getDisplay().syncExec(new Runnable() { @Override public void run() { resetInternal(); } }); } } private void resetInternal() { if (colorMap!=null) colorMap.clear(); if (xyGraph!=null) { try { clearTraces(); for (Axis axis : xyGraph.getAxisList()) axis.setRange(0,100); } catch (Throwable e) { logger.error("Cannot remove plots!", e); } } } @Override public void clear() { if (getDisplay().getThread()==Thread.currentThread()) { clearInternal(); } else { getDisplay().syncExec(new Runnable() { @Override public void run() { clearInternal(); } }); } } private void clearInternal() { if (xyGraph!=null) { try { clearTraces(); if (colorMap!=null) colorMap.clear(); } catch (Throwable e) { logger.error("Cannot remove traces!", e); } } } @Override public void dispose() { super.dispose(); if (colorMap!=null) { colorMap.clear(); colorMap = null; } clearTraces(); if (xyGraph!=null) { xyGraph.dispose(); xyGraph = null; } if (xyCanvas!=null && !xyCanvas.isDisposed()) { xyCanvas.removeMouseWheelListener(getMouseWheelListener()); xyCanvas.removeKeyListener(getKeyListener()); xyCanvas.dispose(); } } private void clearTraces() { if (xyGraph!=null) xyGraph.clearTraces(); if (traceMap!=null) traceMap.clear(); fireTracesCleared(new TraceEvent(this)); } public void repaint() { repaint(true); } public void repaint(final boolean autoScale) { if (getDisplay().getThread()==Thread.currentThread()) { if (xyCanvas!=null) { if (autoScale) LightWeightPlottingSystem.this.xyGraph.performAutoScale(); LightWeightPlottingSystem.this.xyCanvas.layout(xyCanvas.getChildren()); LightWeightPlottingSystem.this.xyGraph.revalidate(); LightWeightPlottingSystem.this.xyGraph.repaint(); } } else { getDisplay().syncExec(new Runnable() { public void run() { if (xyCanvas!=null) { if (autoScale)LightWeightPlottingSystem.this.xyGraph.performAutoScale(); LightWeightPlottingSystem.this.xyCanvas.layout(xyCanvas.getChildren()); LightWeightPlottingSystem.this.xyGraph.revalidate(); LightWeightPlottingSystem.this.xyGraph.repaint(); } } }); } } /** * Creates an image of the same size as the Rectangle passed in. * @param size * @return */ @Override public Image getImage(Rectangle size) { return xyGraph.getImage(size); } /** * Access to the XYGraph, may return null. Access discouraged, just for emergencies! * To use cast your IPlottingSystem to LightWeightPlottingSystem * * @return */ public XYRegionGraph getGraph() { return xyGraph; } /** * Use this method to create axes other than the default y and x axes. * * @param title * @param isYAxis, normally it is. * @param side - either SWT.LEFT, SWT.RIGHT, SWT.TOP, SWT.BOTTOM * @return */ public IAxis createAxis(final String title, final boolean isYAxis, int side) { if (xyGraph==null) createUI(); Axis axis = new AspectAxis(title, isYAxis); if (isYAxis) { axis.setOrientation(Orientation.VERTICAL); } else { axis.setOrientation(Orientation.HORIZONTAL); } if (side==SWT.LEFT||side==SWT.BOTTOM) { axis.setTickLableSide(LabelSide.Primary); } else { axis.setTickLableSide(LabelSide.Secondary); } axis.setAutoScaleThreshold(0.1); axis.setShowMajorGrid(true); axis.setShowMinorGrid(true); xyGraph.addAxis(axis); return new AxisWrapper(axis); } private IAxis selectedXAxis; private IAxis selectedYAxis; @Override public IAxis getSelectedXAxis() { if (selectedXAxis==null) { if (xyGraph==null) createUI(); return new AxisWrapper(xyGraph.primaryXAxis); } return selectedXAxis; } @Override public void setSelectedXAxis(IAxis selectedXAxis) { this.selectedXAxis = selectedXAxis; } @Override public IAxis getSelectedYAxis() { if (selectedYAxis==null) { if (xyGraph==null) createUI(); return new AxisWrapper(xyGraph.primaryYAxis); } return selectedYAxis; } @Override public void setSelectedYAxis(IAxis selectedYAxis) { this.selectedYAxis = selectedYAxis; } public boolean addRegionListener(final IRegionListener l) { if (xyGraph==null) createUI(); return xyGraph.addRegionListener(l); } public boolean removeRegionListener(final IRegionListener l) { if (xyGraph==null) return false; return xyGraph.removeRegionListener(l); } /** * Throws exception if region exists already. * @throws Exception */ public IRegion createRegion(final String name, final RegionType regionType) throws Exception { if (xyGraph==null) createUI(); final Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); final Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); return xyGraph.createRegion(name, xAxis, yAxis, regionType, true); } /** * Thread safe */ public void clearRegions() { if (xyGraph==null) return; xyGraph.clearRegions(); } protected void clearRegionTool() { if (xyGraph==null) return; xyGraph.clearRegionTool(); } /** * Add a selection region to the graph. * @param region */ public void addRegion(final IRegion region) { if (xyGraph==null) createUI(); final AbstractSelectionRegion r = (AbstractSelectionRegion)region; xyGraph.addRegion(r); } /** * Remove a selection region to the graph. * @param region */ public void removeRegion(final IRegion region) { if (xyGraph==null) createUI(); final AbstractSelectionRegion r = (AbstractSelectionRegion)region; xyGraph.removeRegion(r); } @Override public void renameRegion(final IRegion region, String name) { if (xyGraph==null) return; xyGraph.renameRegion((AbstractSelectionRegion)region, name); } /** * Get a region by name. * @param name * @return */ public IRegion getRegion(final String name) { if (xyGraph==null) return null; return xyGraph.getRegion(name); } /** * Get regions * @param name * @return */ public Collection<IRegion> getRegions() { if (xyGraph==null) return null; List<AbstractSelectionRegion> regions = xyGraph.getRegions(); return new ArrayList<IRegion>(regions); } public IAnnotation createAnnotation(final String name) throws Exception { if (xyGraph==null) createUI(); final List<Annotation>anns = xyGraph.getPlotArea().getAnnotationList(); for (Annotation annotation : anns) { if (annotation.getName()!=null&&annotation.getName().equals(name)) { throw new Exception("The annotation name '"+name+"' is already taken."); } } final Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); final Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); return new AnnotationWrapper(name, xAxis, yAxis); } /** * Add an annotation to the graph. * @param region */ public void addAnnotation(final IAnnotation annotation) { final AnnotationWrapper wrapper = (AnnotationWrapper)annotation; xyGraph.addAnnotation(wrapper.getAnnotation()); xyGraph.getOperationsManager().addCommand(new AddAnnotationCommand(xyGraph, wrapper.getAnnotation())); } /** * Remove an annotation to the graph. * @param region */ public void removeAnnotation(final IAnnotation annotation) { final AnnotationWrapper wrapper = (AnnotationWrapper)annotation; xyGraph.removeAnnotation(wrapper.getAnnotation()); xyGraph.getOperationsManager().addCommand(new RemoveAnnotationCommand(xyGraph, wrapper.getAnnotation())); } @Override public void renameAnnotation(final IAnnotation annotation, String name) { final AnnotationWrapper wrapper = (AnnotationWrapper)annotation; wrapper.getAnnotation().setName(name); } /** * Get an annotation by name. * @param name * @return */ public IAnnotation getAnnotation(final String name) { final List<Annotation>anns = xyGraph.getPlotArea().getAnnotationList(); for (Annotation annotation : anns) { if (annotation.getName()!=null&&annotation.getName().equals(name)) { return new AnnotationWrapper(annotation); } } return null; } /** * Remove all annotations */ public void clearAnnotations(){ final List<Annotation>anns = new ArrayList<Annotation>(xyGraph.getPlotArea().getAnnotationList()); for (Annotation annotation : anns) { xyGraph.getPlotArea().removeAnnotation(annotation); } } @Override public void autoscaleAxes() { if (xyGraph==null) return; xyGraph.performAutoScale(); } /** * Override this method to provide an implementation of axis visibility. * @param isVisible * @param title */ public void setAxisAndTitleVisibility(boolean isVisible, String title) { if (xyGraph!=null) { xyGraph.primaryXAxis.setVisible(isVisible); xyGraph.primaryYAxis.setVisible(isVisible); xyGraph.setTitle(title); xyGraph.repaint(); } else { throw new RuntimeException("Cannot set the axis visibility when the plotting system is not created or plotting something!"); } } // Print / Export methods private PrintSettings settings; @Override public void printPlotting(){ if (settings==null) settings = new PrintSettings(); PlotPrintPreviewDialog dialog = new PlotPrintPreviewDialog(xyGraph, Display.getCurrent(), settings); settings=dialog.open(); } /** * Print scaled plotting to printer * TODO to be disable once this works in printPlotting */ public void printSnapshotPlotting(){ // Show the Choose Printer dialog PrintDialog dialog = new PrintDialog(Display.getCurrent().getActiveShell(), SWT.NULL); PrinterData printerData = dialog.open(); if (printerData != null) { // Create the printer object printerData.orientation = PrinterData.LANDSCAPE; // force landscape Printer printer = new Printer(printerData); // Calculate the scale factor between the screen resolution and printer // resolution in order to correctly size the image for the printer Point screenDPI = Display.getCurrent().getDPI(); Point printerDPI = printer.getDPI(); int scaleFactorX = printerDPI.x / screenDPI.x; // Determine the bounds of the entire area of the printer Rectangle size = printer.getClientArea(); Rectangle trim = printer.computeTrim(0, 0, 0, 0); Rectangle imageSize = new Rectangle(size.x/scaleFactorX, size.y/scaleFactorX, size.width/scaleFactorX, size.height/scaleFactorX); if (printer.startJob("Print Plot")) { if (printer.startPage()) { GC gc = new GC(printer); Image xyImage = xyGraph.getImage(imageSize); Image printerImage = new Image(printer, xyImage.getImageData()); xyImage.dispose(); // Draw the image gc.drawImage(printerImage, imageSize.x, imageSize.y, imageSize.width, imageSize.height, -trim.x, -trim.y, size.width-trim.width, size.height-trim.height); // Clean up printerImage.dispose(); gc.dispose(); printer.endPage(); } } // End the job and dispose the printer printer.endJob(); printer.dispose(); } } @Override public void copyPlotting(){ PlotExportPrintUtil.copyGraph(xyGraph.getImage()); } @Override public void savePlotting(String filename){ FileDialog dialog = new FileDialog (Display.getCurrent().getActiveShell(), SWT.SAVE); String [] filterExtensions = new String [] {"*.jpg;*.JPG;*.jpeg;*.JPEG;*.png;*.PNG", "*.ps;*.eps"}; // TODO ,"*.svg;*.SVG"}; if (filename!=null) { dialog.setFilterPath((new File(filename)).getParent()); } else { String filterPath = "/"; String platform = SWT.getPlatform(); if (platform.equals("win32") || platform.equals("wpf")) { filterPath = "c:\\"; } dialog.setFilterPath (filterPath); } dialog.setFilterNames (PlotExportPrintUtil.FILE_TYPES); dialog.setFilterExtensions (filterExtensions); filename = dialog.open(); if (filename == null) return; try { PlotExportPrintUtil.saveGraph(filename, PlotExportPrintUtil.FILE_TYPES[dialog.getFilterIndex()], xyGraph.getImage()); logger.debug("Plotting saved"); } catch (Exception e) { logger.error("Could not save the plotting", e); } } @Override public void savePlotting(String filename, String filetype){ if (filename == null) return; try { PlotExportPrintUtil.saveGraph(filename, filetype, xyGraph.getImage()); logger.debug("Plotting saved"); } catch (Exception e) { logger.error("Could not save the plotting", e); } } }
true
true
private List<ITrace> createPlot1DInternal( final AbstractDataset xIn, final List<AbstractDataset> ysIn, final String title, final boolean createdIndices, final IProgressMonitor monitor) { this.plottingMode = PlotType.PT1D; this.lightWeightActionBarMan.switchActions(plottingMode); Object[] oa = getOrderedDatasets(xIn, ysIn, createdIndices); final AbstractDataset x = (AbstractDataset)oa[0]; @SuppressWarnings("unchecked") final List<AbstractDataset> ys = (List<AbstractDataset>)oa[1]; if (colorMap == null && getColorOption()!=ColorOption.NONE) { if (getColorOption()==ColorOption.BY_NAME) { colorMap = new HashMap<Object,Color>(ys.size()); } else { colorMap = new IdentityHashMap<Object,Color>(ys.size()); } } if (traceMap==null) traceMap = new LinkedHashMap<String, ITrace>(31); if (xyGraph==null) return null; Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); xAxis.setVisible(true); yAxis.setVisible(true); if (title==null) { // TODO Fix titles for multiple calls to create1DPlot(...) xyGraph.setTitle(DatasetTitleUtils.getTitle(x, ys, true, rootName)); } else { xyGraph.setTitle(title); } xAxis.setTitle(DatasetTitleUtils.getName(x,rootName)); //create a trace data provider, which will provide the data to the trace. int iplot = 0; final List<ITrace> traces = new ArrayList<ITrace>(ys.size()); for (AbstractDataset y : ys) { LightWeightDataProvider traceDataProvider = new LightWeightDataProvider(x, y); //create the trace final LineTrace trace = new LineTrace(DatasetTitleUtils.getName(y,rootName), xAxis, yAxis, traceDataProvider); LineTraceImpl wrapper = new LineTraceImpl(this, trace); traces.add(wrapper); if (y.getName()!=null && !"".equals(y.getName())) { traceMap.put(y.getName(), wrapper); trace.setInternalName(y.getName()); } //set trace property trace.setPointStyle(PointStyle.NONE); int index = getTraces().size()+iplot-1; if (index<0) index=0; final Color plotColor = ColorUtility.getSwtColour(colorMap!=null?colorMap.values():null, index); if (colorMap!=null) { if (getColorOption()==ColorOption.BY_NAME) { colorMap.put(y.getName(),plotColor); } else { colorMap.put(y, plotColor); } } trace.setTraceColor(plotColor); //add the trace to xyGraph xyGraph.addTrace(trace); if (monitor!=null) monitor.worked(1); iplot++; } xyCanvas.redraw(); getDisplay().syncExec(new Runnable() { public void run() { autoscaleAxes(); autoscaleAxes(); } }); fireTracesPlotted(new TraceEvent(traces)); return traces; }
private List<ITrace> createPlot1DInternal( final AbstractDataset xIn, final List<AbstractDataset> ysIn, final String title, final boolean createdIndices, final IProgressMonitor monitor) { this.plottingMode = PlotType.PT1D; this.lightWeightActionBarMan.switchActions(plottingMode); Object[] oa = getOrderedDatasets(xIn, ysIn, createdIndices); final AbstractDataset x = (AbstractDataset)oa[0]; @SuppressWarnings("unchecked") final List<AbstractDataset> ys = (List<AbstractDataset>)oa[1]; if (colorMap == null && getColorOption()!=ColorOption.NONE) { if (getColorOption()==ColorOption.BY_NAME) { colorMap = new HashMap<Object,Color>(ys.size()); } else { colorMap = new IdentityHashMap<Object,Color>(ys.size()); } } if (traceMap==null) traceMap = new LinkedHashMap<String, ITrace>(31); if (xyGraph==null) return null; Axis xAxis = ((AxisWrapper)getSelectedXAxis()).getWrappedAxis(); Axis yAxis = ((AxisWrapper)getSelectedYAxis()).getWrappedAxis(); xAxis.setVisible(true); yAxis.setVisible(true); if (title==null) { // TODO Fix titles for multiple calls to create1DPlot(...) xyGraph.setTitle(DatasetTitleUtils.getTitle(x, ys, true, rootName)); } else { xyGraph.setTitle(title); } xAxis.setTitle(DatasetTitleUtils.getName(x,rootName)); if (!isXfirst() || createdIndices) { // Index mode, indices are integers! xAxis.setFormatPattern("############"); } else { xAxis.setFormatPattern("############.##"); } //create a trace data provider, which will provide the data to the trace. int iplot = 0; final List<ITrace> traces = new ArrayList<ITrace>(ys.size()); for (AbstractDataset y : ys) { LightWeightDataProvider traceDataProvider = new LightWeightDataProvider(x, y); //create the trace final LineTrace trace = new LineTrace(DatasetTitleUtils.getName(y,rootName), xAxis, yAxis, traceDataProvider); LineTraceImpl wrapper = new LineTraceImpl(this, trace); traces.add(wrapper); if (y.getName()!=null && !"".equals(y.getName())) { traceMap.put(y.getName(), wrapper); trace.setInternalName(y.getName()); } //set trace property trace.setPointStyle(PointStyle.NONE); int index = getTraces().size()+iplot-1; if (index<0) index=0; final Color plotColor = ColorUtility.getSwtColour(colorMap!=null?colorMap.values():null, index); if (colorMap!=null) { if (getColorOption()==ColorOption.BY_NAME) { colorMap.put(y.getName(),plotColor); } else { colorMap.put(y, plotColor); } } trace.setTraceColor(plotColor); //add the trace to xyGraph xyGraph.addTrace(trace); if (monitor!=null) monitor.worked(1); iplot++; } xyCanvas.redraw(); getDisplay().syncExec(new Runnable() { public void run() { autoscaleAxes(); autoscaleAxes(); } }); fireTracesPlotted(new TraceEvent(traces)); return traces; }
diff --git a/src/me/libraryaddict/Hungergames/Managers/GenerationManager.java b/src/me/libraryaddict/Hungergames/Managers/GenerationManager.java index a979835..12849e3 100644 --- a/src/me/libraryaddict/Hungergames/Managers/GenerationManager.java +++ b/src/me/libraryaddict/Hungergames/Managers/GenerationManager.java @@ -1,357 +1,360 @@ package me.libraryaddict.Hungergames.Managers; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import me.libraryaddict.Hungergames.Hungergames; import me.libraryaddict.Hungergames.Configs.LoggerConfig; import me.libraryaddict.Hungergames.Types.CordPair; import me.libraryaddict.Hungergames.Types.HungergamesApi; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.scheduler.BukkitRunnable; public class GenerationManager { private class BlockInfo { byte data; Material id; @SuppressWarnings("unused") public BlockInfo(int id, byte data) { this.id = Material.getMaterial(id); this.data = data; } public BlockInfo(Material id, byte data) { this.id = id; this.data = data; } } private BukkitRunnable chunkGeneratorRunnable; private ArrayList<CordPair> chunksToGenerate = new ArrayList<CordPair>(); private List<BlockFace> faces = new ArrayList<BlockFace>(); private List<BlockFace> jungleFaces = new ArrayList<BlockFace>(); private LoggerConfig loggerConfig = HungergamesApi.getConfigManager().getLoggerConfig(); private LinkedList<Block> processedBlocks = new LinkedList<Block>(); private HashMap<Block, BlockInfo> queued = new HashMap<Block, BlockInfo>(); private BukkitRunnable setBlocksRunnable; public GenerationManager() { faces.add(BlockFace.UP); faces.add(BlockFace.DOWN); faces.add(BlockFace.SOUTH); faces.add(BlockFace.NORTH); faces.add(BlockFace.WEST); faces.add(BlockFace.EAST); faces.add(BlockFace.SELF); jungleFaces.add(BlockFace.UP); jungleFaces.add(BlockFace.SELF); jungleFaces.add(BlockFace.DOWN); } public void addToProcessedBlocks(Block block) { processedBlocks.add(block); } public void generateChunks() { if (!isChunkGeneratorRunning()) { // Get the measurements I need int chunks1 = Bukkit.getViewDistance() + 3; int chunks2 = 0; Hungergames hungergames = HungergamesApi.getHungergames(); YamlConfiguration mapConfig = YamlConfiguration.loadConfiguration(new File(hungergames.getDataFolder(), "map.yml")); // Load the map configs to find out generation range if (mapConfig.getBoolean("GenerateChunks")) { chunks2 = (int) Math.ceil(HungergamesApi.getConfigManager().getMainConfig().getBorderSize() / 16) + Bukkit.getViewDistance(); } // Does the chunk generation run while players are online final boolean runInBackground = mapConfig.getBoolean("GenerateChunksBackground"); // Get the max chunk distance int chunksDistance = Math.max(chunks1, chunks2); Chunk spawn = hungergames.world.getSpawnLocation().getChunk(); for (int x = -chunksDistance; x <= chunksDistance; x++) { for (int z = -chunksDistance; z <= chunksDistance; z++) { CordPair pair = new CordPair(spawn.getX() + x, spawn.getZ() + z); chunksToGenerate.add(pair); } } final double totalChunks = chunksToGenerate.size(); final World world = hungergames.world; + final boolean doLogging = mapConfig.getBoolean("GenerateChunks"); chunkGeneratorRunnable = new BukkitRunnable() { private double chunksGenerated; private long lastLogged; public void run() { - if (lastLogged + 5000 < System.currentTimeMillis()) { + if (doLogging && lastLogged + 5000 < System.currentTimeMillis()) { System.out.print(String.format(loggerConfig.getGeneratingChunks(), (int) Math.floor((chunksGenerated / totalChunks) * 100)) + "%"); lastLogged = System.currentTimeMillis(); } long startedGeneration = System.currentTimeMillis(); Iterator<CordPair> cordsItel = chunksToGenerate.iterator(); while (cordsItel.hasNext() && startedGeneration + (runInBackground ? 50 : 5000) > System.currentTimeMillis()) { CordPair pair = cordsItel.next(); world.loadChunk(pair.getX(), pair.getZ()); world.unloadChunk(pair.getX(), pair.getZ()); cordsItel.remove(); chunksGenerated++; } if (!cordsItel.hasNext()) { - System.out.print(String.format(HungergamesApi.getConfigManager().getLoggerConfig().getChunksGenerated(), - (int) chunksGenerated)); + if (doLogging) { + System.out.print(String.format(HungergamesApi.getConfigManager().getLoggerConfig() + .getChunksGenerated(), (int) chunksGenerated)); + } chunkGeneratorRunnable = null; cancel(); } } }; chunkGeneratorRunnable.runTaskTimer(hungergames, 1, 3); } } /** * Generate pillars.. */ public void generatePillars(Location loc, int radius, int pillarCornerId, int pillarCornerData, int pillarInsideId, int pillarInsideData) { int[] cords = new int[] { (int) (-radius / 2.5), (int) (radius / 2.5) }; int pillarRadius = Math.round(radius / 8); for (int px = 0; px <= 1; px++) for (int pz = 0; pz <= 1; pz++) for (int x = -pillarRadius; x <= pillarRadius; x++) { for (int z = -pillarRadius; z <= pillarRadius; z++) { Block b = loc.getWorld().getBlockAt(x + loc.getBlockX() + cords[px], loc.getBlockY() - 2, z + loc.getBlockZ() + cords[pz]); while (!isSolid(b)) { if (Math.abs(x) == pillarRadius && Math.abs(z) == pillarRadius) setBlockFast(b, pillarCornerId, (short) pillarCornerData); else setBlockFast(b, pillarInsideId, (short) pillarInsideData); b = b.getRelative(BlockFace.DOWN); } } } } /** * Generates a feast * * @param loc * @param lowestLevel * @param radius */ public void generatePlatform(Location loc, int lowestLevel, int radius, int yHeight, int platformGround, short platformDurability) { loc.setY(lowestLevel + 1); double radiusSquared = radius * radius; // Sets to air and generates to stand on yHeight = Math.min(loc.getBlockY() + yHeight, loc.getWorld().getMaxHeight()); for (int radiusX = -radius; radiusX <= radius; radiusX++) { for (int radiusZ = -radius; radiusZ <= radius; radiusZ++) { if ((radiusX * radiusX) + (radiusZ * radiusZ) <= radiusSquared) { for (int y = yHeight; y >= loc.getBlockY() - 1; y--) { Block b = loc.getWorld().getBlockAt(radiusX + loc.getBlockX(), y, radiusZ + loc.getBlockZ()); removeLeaves(b); if (y >= loc.getBlockY()) {// If its less then 0 setBlockFast(b, 0, (byte) 0); } else { // Generates to stand on setBlockFast(b, platformGround, platformDurability); } } } } } } /** * Generates a feast * * @param loc * @param lowestLevel * @param radius */ public void generatePlatform(Location loc, int lowestLevel, int radius, Material groundType, int groundDurability) { int yHeight = radius; if (yHeight < 4) yHeight = 4; generatePlatform(loc, lowestLevel, radius, yHeight, groundType.getId(), (short) groundDurability); } public int getHeight(ArrayList<Integer> heights, int radius) { List<List<Integer>> commons = new ArrayList<List<Integer>>(); for (int i = 0; i < heights.size(); i++) { List<Integer> numbers = new ArrayList<Integer>(); numbers.add(heights.get(i)); for (int a = i; a < heights.size(); a++) { if (heights.get(i) - heights.get(a) >= -radius) numbers.add(heights.get(a)); else break; } commons.add(numbers); } int highest = 0; List<Integer> found = new ArrayList<Integer>(); for (List l : commons) { if (l.size() > highest) { highest = l.size(); found = l; } } if (found.size() == 0) return 0; return found.get((int) Math.round(found.size() / 3)); } private Block getHighest(Block b) { while (b.getY() > 0 && !isSolid(b)) b = b.getRelative(BlockFace.DOWN); return b; } /** * Gets the best Y level to spawn the feast at This also modifies the Location fed to it for use by feast generation * * @param loc * @param radius * @return Best Y Level */ public int getSpawnHeight(Location loc, int radius) { ArrayList<Integer> heightLevels = new ArrayList<Integer>(); for (double degree = 0; degree <= 360; degree += 1) { double angle = degree * Math.PI / 180; int x = (int) (loc.getX() + .5 + radius * Math.cos(angle)); int z = (int) (loc.getZ() + radius * Math.sin(angle)); Block b = getHighest(loc.getWorld().getHighestBlockAt(x, z)); if (isBlockValid(b)) heightLevels.add(b.getY()); /* * // Do it again but at 2/3 the radius angle = degree * Math.PI / * 180; x = (int) (loc.getX() + .5 + ((radius / 3) * 2) * * Math.cos(angle)); z = (int) (loc.getZ() + ((radius / 3) * 2) * * Math.sin(angle)); b = * getHighest(loc.getWorld().getHighestBlockAt(x, z)); if * (!b.getChunk().isLoaded()) b.getChunk().load(true); if * (isBlockValid(b)) heightLevels.add(b.getY()); */ } Block b = getHighest(loc.getBlock()); if (isBlockValid(b)) heightLevels.add(b.getY()); Collections.sort(heightLevels); int y = getHeight(heightLevels, 5); if (y == -1) y = b.getY(); loc = new Location(loc.getWorld(), loc.getBlockX(), y + 1, loc.getBlockZ()); return y; } private boolean isBlockValid(Block b) { if (b.isLiquid() || b.getRelative(BlockFace.UP).isLiquid()) return false; return true; } public boolean isChunkGeneratorRunning() { return chunkGeneratorRunnable != null; } private boolean isSolid(Block b) { return (!(b.getType() == Material.AIR || b.isLiquid() || b.getType() == Material.VINE || b.getType() == Material.LOG || b.getType() == Material.LEAVES || b.getType() == Material.SNOW || b.getType() == Material.LONG_GRASS || b.getType() == Material.WOOD || b.getType() == Material.COBBLESTONE || b.getType().name().contains("FLOWER") || b .getType().name().contains("MUSHROOM"))); } private void removeLeaves(Block b) { for (BlockFace face : ((b.getBiome() == Biome.JUNGLE || b.getBiome() == Biome.JUNGLE_HILLS) ? jungleFaces : faces)) { Block newB = b.getRelative(face); if ((newB.getType() == Material.LEAVES || newB.getType() == Material.LOG || newB.getType() == Material.VINE)) { if (!queued.containsKey(newB) && !processedBlocks.contains(newB)) { setBlockFast(newB, 0, (byte) 0); if (newB.getRelative(BlockFace.DOWN).getType() == Material.DIRT) { newB = newB.getRelative(BlockFace.DOWN); if (!queued.containsKey(newB) && !processedBlocks.contains(newB)) { setBlockFast(newB, Material.GRASS.getId(), (byte) 0); } } } } else if (newB.getType() == Material.SNOW && face == BlockFace.UP) { if (!queued.containsKey(newB) && !processedBlocks.contains(newB)) { setBlockFast(newB, 0, (byte) 0); } } } } public void setBlockFast(Block b, int typeId, short s) { setBlockFast(b, Material.getMaterial(typeId), s); } public void setBlockFast(Block b, Material type, short s) { try { if (b.getType() != type || b.getData() != (byte) s) { queued.put(b, new BlockInfo(type, (byte) s)); if (setBlocksRunnable == null) { setBlocksRunnable = new BukkitRunnable() { public void run() { if (queued.size() == 0) { setBlocksRunnable = null; processedBlocks.clear(); cancel(); } int i = 0; HashMap<Block, BlockInfo> toDo = new HashMap<Block, BlockInfo>(); for (Block b : queued.keySet()) { if (i++ >= 200) break; if (b.getType() == queued.get(b).id && b.getData() == queued.get(b).data) i--; toDo.put(b, queued.get(b)); b = b.getRelative(BlockFace.UP); while (b != null && queued.containsKey(b) && (b.isLiquid() || b.getType() == Material.SAND || b.getType() == Material.ANVIL || b .getType() == Material.GRAVEL)) { toDo.put(b, queued.get(b)); b = b.getRelative(BlockFace.UP); } } for (Block b : toDo.keySet()) { if (!processedBlocks.contains(b)) processedBlocks.add(b); queued.remove(b); removeLeaves(b); if (!b.getChunk().isLoaded()) b.getChunk().load(); b.setTypeIdAndData(toDo.get(b).id.getId(), toDo.get(b).data, true); } } }; setBlocksRunnable.runTaskTimer(HungergamesApi.getHungergames(), 2, 1); } // return ((CraftChunk) b.getChunk()).getHandle().a(b.getX() & 15, // b.getY(), b.getZ() & 15, typeId, data); } } catch (Exception ex) { ex.printStackTrace(); } } }
false
true
public void generateChunks() { if (!isChunkGeneratorRunning()) { // Get the measurements I need int chunks1 = Bukkit.getViewDistance() + 3; int chunks2 = 0; Hungergames hungergames = HungergamesApi.getHungergames(); YamlConfiguration mapConfig = YamlConfiguration.loadConfiguration(new File(hungergames.getDataFolder(), "map.yml")); // Load the map configs to find out generation range if (mapConfig.getBoolean("GenerateChunks")) { chunks2 = (int) Math.ceil(HungergamesApi.getConfigManager().getMainConfig().getBorderSize() / 16) + Bukkit.getViewDistance(); } // Does the chunk generation run while players are online final boolean runInBackground = mapConfig.getBoolean("GenerateChunksBackground"); // Get the max chunk distance int chunksDistance = Math.max(chunks1, chunks2); Chunk spawn = hungergames.world.getSpawnLocation().getChunk(); for (int x = -chunksDistance; x <= chunksDistance; x++) { for (int z = -chunksDistance; z <= chunksDistance; z++) { CordPair pair = new CordPair(spawn.getX() + x, spawn.getZ() + z); chunksToGenerate.add(pair); } } final double totalChunks = chunksToGenerate.size(); final World world = hungergames.world; chunkGeneratorRunnable = new BukkitRunnable() { private double chunksGenerated; private long lastLogged; public void run() { if (lastLogged + 5000 < System.currentTimeMillis()) { System.out.print(String.format(loggerConfig.getGeneratingChunks(), (int) Math.floor((chunksGenerated / totalChunks) * 100)) + "%"); lastLogged = System.currentTimeMillis(); } long startedGeneration = System.currentTimeMillis(); Iterator<CordPair> cordsItel = chunksToGenerate.iterator(); while (cordsItel.hasNext() && startedGeneration + (runInBackground ? 50 : 5000) > System.currentTimeMillis()) { CordPair pair = cordsItel.next(); world.loadChunk(pair.getX(), pair.getZ()); world.unloadChunk(pair.getX(), pair.getZ()); cordsItel.remove(); chunksGenerated++; } if (!cordsItel.hasNext()) { System.out.print(String.format(HungergamesApi.getConfigManager().getLoggerConfig().getChunksGenerated(), (int) chunksGenerated)); chunkGeneratorRunnable = null; cancel(); } } }; chunkGeneratorRunnable.runTaskTimer(hungergames, 1, 3); } }
public void generateChunks() { if (!isChunkGeneratorRunning()) { // Get the measurements I need int chunks1 = Bukkit.getViewDistance() + 3; int chunks2 = 0; Hungergames hungergames = HungergamesApi.getHungergames(); YamlConfiguration mapConfig = YamlConfiguration.loadConfiguration(new File(hungergames.getDataFolder(), "map.yml")); // Load the map configs to find out generation range if (mapConfig.getBoolean("GenerateChunks")) { chunks2 = (int) Math.ceil(HungergamesApi.getConfigManager().getMainConfig().getBorderSize() / 16) + Bukkit.getViewDistance(); } // Does the chunk generation run while players are online final boolean runInBackground = mapConfig.getBoolean("GenerateChunksBackground"); // Get the max chunk distance int chunksDistance = Math.max(chunks1, chunks2); Chunk spawn = hungergames.world.getSpawnLocation().getChunk(); for (int x = -chunksDistance; x <= chunksDistance; x++) { for (int z = -chunksDistance; z <= chunksDistance; z++) { CordPair pair = new CordPair(spawn.getX() + x, spawn.getZ() + z); chunksToGenerate.add(pair); } } final double totalChunks = chunksToGenerate.size(); final World world = hungergames.world; final boolean doLogging = mapConfig.getBoolean("GenerateChunks"); chunkGeneratorRunnable = new BukkitRunnable() { private double chunksGenerated; private long lastLogged; public void run() { if (doLogging && lastLogged + 5000 < System.currentTimeMillis()) { System.out.print(String.format(loggerConfig.getGeneratingChunks(), (int) Math.floor((chunksGenerated / totalChunks) * 100)) + "%"); lastLogged = System.currentTimeMillis(); } long startedGeneration = System.currentTimeMillis(); Iterator<CordPair> cordsItel = chunksToGenerate.iterator(); while (cordsItel.hasNext() && startedGeneration + (runInBackground ? 50 : 5000) > System.currentTimeMillis()) { CordPair pair = cordsItel.next(); world.loadChunk(pair.getX(), pair.getZ()); world.unloadChunk(pair.getX(), pair.getZ()); cordsItel.remove(); chunksGenerated++; } if (!cordsItel.hasNext()) { if (doLogging) { System.out.print(String.format(HungergamesApi.getConfigManager().getLoggerConfig() .getChunksGenerated(), (int) chunksGenerated)); } chunkGeneratorRunnable = null; cancel(); } } }; chunkGeneratorRunnable.runTaskTimer(hungergames, 1, 3); } }
diff --git a/src/com/android/email/activity/MessageCompose.java b/src/com/android/email/activity/MessageCompose.java index 123ac9a8..d7b2c47a 100644 --- a/src/com/android/email/activity/MessageCompose.java +++ b/src/com/android/email/activity/MessageCompose.java @@ -1,2323 +1,2323 @@ /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.email.activity; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.Activity; import android.app.ActivityManager; import android.app.FragmentTransaction; import android.content.ActivityNotFoundException; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import android.provider.OpenableColumns; import android.text.InputFilter; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextUtils; import android.text.TextWatcher; import android.text.util.Rfc822Tokenizer; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageButton; import android.widget.MultiAutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import com.android.common.contacts.DataUsageStatUpdater; import com.android.email.Controller; import com.android.email.Email; import com.android.email.EmailAddressAdapter; import com.android.email.EmailAddressValidator; import com.android.email.R; import com.android.email.RecipientAdapter; import com.android.email.mail.internet.EmailHtmlUtil; import com.android.emailcommon.Logging; import com.android.emailcommon.internet.MimeUtility; import com.android.emailcommon.mail.Address; import com.android.emailcommon.provider.Account; import com.android.emailcommon.provider.EmailContent; import com.android.emailcommon.provider.EmailContent.Attachment; import com.android.emailcommon.provider.EmailContent.Body; import com.android.emailcommon.provider.EmailContent.BodyColumns; import com.android.emailcommon.provider.EmailContent.Message; import com.android.emailcommon.provider.EmailContent.MessageColumns; import com.android.emailcommon.provider.EmailContent.QuickResponseColumns; import com.android.emailcommon.provider.Mailbox; import com.android.emailcommon.provider.QuickResponse; import com.android.emailcommon.utility.AttachmentUtilities; import com.android.emailcommon.utility.EmailAsyncTask; import com.android.emailcommon.utility.Utility; import com.android.ex.chips.AccountSpecifier; import com.android.ex.chips.ChipsUtil; import com.android.ex.chips.RecipientEditTextView; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Objects; import com.google.common.collect.Lists; import java.io.File; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; /** * Activity to compose a message. * * TODO Revive shortcuts command for removed menu options. * C: add cc/bcc * N: add attachment */ public class MessageCompose extends Activity implements OnClickListener, OnFocusChangeListener, DeleteMessageConfirmationDialog.Callback, InsertQuickResponseDialog.Callback { private static final String ACTION_REPLY = "com.android.email.intent.action.REPLY"; private static final String ACTION_REPLY_ALL = "com.android.email.intent.action.REPLY_ALL"; private static final String ACTION_FORWARD = "com.android.email.intent.action.FORWARD"; private static final String ACTION_EDIT_DRAFT = "com.android.email.intent.action.EDIT_DRAFT"; private static final String EXTRA_ACCOUNT_ID = "account_id"; private static final String EXTRA_MESSAGE_ID = "message_id"; /** If the intent is sent from the email app itself, it should have this boolean extra. */ private static final String EXTRA_FROM_WITHIN_APP = "from_within_app"; private static final String STATE_KEY_CC_SHOWN = "com.android.email.activity.MessageCompose.ccShown"; private static final String STATE_KEY_QUOTED_TEXT_SHOWN = "com.android.email.activity.MessageCompose.quotedTextShown"; private static final String STATE_KEY_DRAFT_ID = "com.android.email.activity.MessageCompose.draftId"; private static final String STATE_KEY_LAST_SAVE_TASK_ID = "com.android.email.activity.MessageCompose.requestId"; private static final String STATE_KEY_ACTION = "com.android.email.activity.MessageCompose.action"; private static final int ACTIVITY_REQUEST_PICK_ATTACHMENT = 1; private static final String[] ATTACHMENT_META_SIZE_PROJECTION = { OpenableColumns.SIZE }; private static final int ATTACHMENT_META_SIZE_COLUMN_SIZE = 0; /** * A registry of the active tasks used to save messages. */ private static final ConcurrentHashMap<Long, SendOrSaveMessageTask> sActiveSaveTasks = new ConcurrentHashMap<Long, SendOrSaveMessageTask>(); private static long sNextSaveTaskId = 1; /** * The ID of the latest save or send task requested by this Activity. */ private long mLastSaveTaskId = -1; private Account mAccount; /** * The contents of the current message being edited. This is not always in sync with what's * on the UI. {@link #updateMessage(Message, Account, boolean, boolean)} must be called to sync * the UI values into this object. */ private Message mDraft = new Message(); /** * A collection of attachments the user is currently wanting to attach to this message. */ private final ArrayList<Attachment> mAttachments = new ArrayList<Attachment>(); /** * The source message for a reply, reply all, or forward. This is asynchronously loaded. */ private Message mSource; /** * The attachments associated with the source attachments. Usually included in a forward. */ private ArrayList<Attachment> mSourceAttachments = new ArrayList<Attachment>(); /** * The action being handled by this activity. This is initially populated from the * {@link Intent}, but can switch between reply/reply all/forward where appropriate. * This value is nullable (a null value indicating a regular "compose"). */ private String mAction; private TextView mFromView; private MultiAutoCompleteTextView mToView; private MultiAutoCompleteTextView mCcView; private MultiAutoCompleteTextView mBccView; private View mCcBccContainer; private EditText mSubjectView; private EditText mMessageContentView; private View mAttachmentContainer; private ViewGroup mAttachmentContentView; private View mQuotedTextBar; private CheckBox mIncludeQuotedTextCheckBox; private WebView mQuotedText; private ActionSpinnerAdapter mActionSpinnerAdapter; private Controller mController; private boolean mDraftNeedsSaving; private boolean mMessageLoaded; private boolean mInitiallyEmpty; private boolean mPickingAttachment = false; private Boolean mQuickResponsesAvailable = true; private final EmailAsyncTask.Tracker mTaskTracker = new EmailAsyncTask.Tracker(); private AccountSpecifier mAddressAdapterTo; private AccountSpecifier mAddressAdapterCc; private AccountSpecifier mAddressAdapterBcc; /** * Watches the to, cc, bcc, subject, and message body fields. */ private final TextWatcher mWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int before, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { setMessageChanged(true); } @Override public void afterTextChanged(android.text.Editable s) { } }; private static Intent getBaseIntent(Context context) { Intent i = new Intent(context, MessageCompose.class); i.putExtra(EXTRA_FROM_WITHIN_APP, true); return i; } /** * Create an {@link Intent} that can start the message compose activity. If accountId -1, * the default account will be used; otherwise, the specified account is used. */ public static Intent getMessageComposeIntent(Context context, long accountId) { Intent i = getBaseIntent(context); i.putExtra(EXTRA_ACCOUNT_ID, accountId); return i; } /** * Compose a new message using the given account. If account is -1 the default account * will be used. * @param context * @param accountId */ public static void actionCompose(Context context, long accountId) { try { Intent i = getMessageComposeIntent(context, accountId); context.startActivity(i); } catch (ActivityNotFoundException anfe) { // Swallow it - this is usually a race condition, especially under automated test. // (The message composer might have been disabled) Email.log(anfe.toString()); } } /** * Compose a new message using a uri (mailto:) and a given account. If account is -1 the * default account will be used. * @param context * @param uriString * @param accountId * @return true if startActivity() succeeded */ public static boolean actionCompose(Context context, String uriString, long accountId) { try { Intent i = getMessageComposeIntent(context, accountId); i.setAction(Intent.ACTION_SEND); i.setData(Uri.parse(uriString)); context.startActivity(i); return true; } catch (ActivityNotFoundException anfe) { // Swallow it - this is usually a race condition, especially under automated test. // (The message composer might have been disabled) Email.log(anfe.toString()); return false; } } /** * Compose a new message as a reply to the given message. If replyAll is true the function * is reply all instead of simply reply. * @param context * @param messageId * @param replyAll */ public static void actionReply(Context context, long messageId, boolean replyAll) { startActivityWithMessage(context, replyAll ? ACTION_REPLY_ALL : ACTION_REPLY, messageId); } /** * Compose a new message as a forward of the given message. * @param context * @param messageId */ public static void actionForward(Context context, long messageId) { startActivityWithMessage(context, ACTION_FORWARD, messageId); } /** * Continue composition of the given message. This action modifies the way this Activity * handles certain actions. * Save will attempt to replace the message in the given folder with the updated version. * Discard will delete the message from the given folder. * @param context * @param messageId the message id. */ public static void actionEditDraft(Context context, long messageId) { startActivityWithMessage(context, ACTION_EDIT_DRAFT, messageId); } /** * Starts a compose activity with a message as a reference message (e.g. for reply or forward). */ private static void startActivityWithMessage(Context context, String action, long messageId) { Intent i = getBaseIntent(context); i.putExtra(EXTRA_MESSAGE_ID, messageId); i.setAction(action); context.startActivity(i); } private void setAccount(Intent intent) { long accountId = intent.getLongExtra(EXTRA_ACCOUNT_ID, -1); if (accountId == Account.NO_ACCOUNT) { accountId = Account.getDefaultAccountId(this); } if (accountId == Account.NO_ACCOUNT) { // There are no accounts set up. This should not have happened. Prompt the // user to set up an account as an acceptable bailout. Welcome.actionStart(this); finish(); } else { setAccount(Account.restoreAccountWithId(this, accountId)); } } private void setAccount(Account account) { if (account == null) { throw new IllegalArgumentException(); } mAccount = account; mFromView.setText(account.mEmailAddress); mAddressAdapterTo .setAccount(new android.accounts.Account(account.mEmailAddress, "unknown")); mAddressAdapterCc .setAccount(new android.accounts.Account(account.mEmailAddress, "unknown")); mAddressAdapterBcc .setAccount(new android.accounts.Account(account.mEmailAddress, "unknown")); new QuickResponseChecker(mTaskTracker).executeParallel((Void) null); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityHelper.debugSetWindowFlags(this); setContentView(R.layout.message_compose); mController = Controller.getInstance(getApplication()); initViews(); // Show the back arrow on the action bar. getActionBar().setDisplayOptions( ActionBar.DISPLAY_HOME_AS_UP, ActionBar.DISPLAY_HOME_AS_UP); if (savedInstanceState != null) { long draftId = savedInstanceState.getLong(STATE_KEY_DRAFT_ID, Message.NOT_SAVED); long existingSaveTaskId = savedInstanceState.getLong(STATE_KEY_LAST_SAVE_TASK_ID, -1); setAction(savedInstanceState.getString(STATE_KEY_ACTION)); SendOrSaveMessageTask existingSaveTask = sActiveSaveTasks.get(existingSaveTaskId); if ((draftId != Message.NOT_SAVED) || (existingSaveTask != null)) { // Restoring state and there was an existing message saved or in the process of // being saved. resumeDraft(draftId, existingSaveTask, false /* don't restore views */); } else { // Restoring state but there was nothing saved - probably means the user rotated // the device immediately - just use the Intent. resolveIntent(getIntent()); } } else { Intent intent = getIntent(); setAction(intent.getAction()); resolveIntent(intent); } } private void resolveIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(mAction) || Intent.ACTION_SENDTO.equals(mAction) || Intent.ACTION_SEND.equals(mAction) || Intent.ACTION_SEND_MULTIPLE.equals(mAction)) { initFromIntent(intent); setMessageChanged(true); setMessageLoaded(true); } else if (ACTION_REPLY.equals(mAction) || ACTION_REPLY_ALL.equals(mAction) || ACTION_FORWARD.equals(mAction)) { long sourceMessageId = getIntent().getLongExtra(EXTRA_MESSAGE_ID, Message.NOT_SAVED); loadSourceMessage(sourceMessageId, true); } else if (ACTION_EDIT_DRAFT.equals(mAction)) { // Assert getIntent.hasExtra(EXTRA_MESSAGE_ID) long draftId = getIntent().getLongExtra(EXTRA_MESSAGE_ID, Message.NOT_SAVED); resumeDraft(draftId, null, true /* restore views */); } else { // Normal compose flow for a new message. setAccount(intent); setInitialComposeText(null, getAccountSignature(mAccount)); setMessageLoaded(true); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { // Temporarily disable onTextChanged listeners while restoring the fields removeListeners(); super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.getBoolean(STATE_KEY_CC_SHOWN)) { showCcBccFields(); } mQuotedTextBar.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE); mQuotedText.setVisibility(savedInstanceState.getBoolean(STATE_KEY_QUOTED_TEXT_SHOWN) ? View.VISIBLE : View.GONE); addListeners(); } // needed for unit tests @Override public void setIntent(Intent intent) { super.setIntent(intent); setAction(intent.getAction()); } private void setQuickResponsesAvailable(boolean quickResponsesAvailable) { if (mQuickResponsesAvailable != quickResponsesAvailable) { mQuickResponsesAvailable = quickResponsesAvailable; invalidateOptionsMenu(); } } /** * Given an accountId and context, finds if the database has any QuickResponse * entries and returns the result to the Callback. */ private class QuickResponseChecker extends EmailAsyncTask<Void, Void, Boolean> { public QuickResponseChecker(EmailAsyncTask.Tracker tracker) { super(tracker); } @Override protected Boolean doInBackground(Void... params) { return EmailContent.count(MessageCompose.this, QuickResponse.CONTENT_URI, QuickResponseColumns.ACCOUNT_KEY + "=?", new String[] {Long.toString(mAccount.mId)}) > 0; } @Override protected void onSuccess(Boolean quickResponsesAvailable) { setQuickResponsesAvailable(quickResponsesAvailable); } } @Override public void onResume() { super.onResume(); // Exit immediately if the accounts list has changed (e.g. externally deleted) if (Email.getNotifyUiAccountsChanged()) { Welcome.actionStart(this); finish(); return; } // If activity paused and quick responses are removed/added, possibly update options menu if (mAccount != null) { new QuickResponseChecker(mTaskTracker).executeParallel((Void) null); } } @Override public void onPause() { super.onPause(); saveIfNeeded(); } /** * We override onDestroy to make sure that the WebView gets explicitly destroyed. * Otherwise it can leak native references. */ @Override public void onDestroy() { super.onDestroy(); mQuotedText.destroy(); mQuotedText = null; mTaskTracker.cancellAllInterrupt(); if (mAddressAdapterTo != null && mAddressAdapterTo instanceof EmailAddressAdapter) { ((EmailAddressAdapter) mAddressAdapterTo).close(); } if (mAddressAdapterCc != null && mAddressAdapterCc instanceof EmailAddressAdapter) { ((EmailAddressAdapter) mAddressAdapterCc).close(); } if (mAddressAdapterBcc != null && mAddressAdapterBcc instanceof EmailAddressAdapter) { ((EmailAddressAdapter) mAddressAdapterBcc).close(); } } /** * The framework handles most of the fields, but we need to handle stuff that we * dynamically show and hide: * Cc field, * Bcc field, * Quoted text, */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); long draftId = mDraft.mId; if (draftId != Message.NOT_SAVED) { outState.putLong(STATE_KEY_DRAFT_ID, draftId); } outState.putBoolean(STATE_KEY_CC_SHOWN, mCcBccContainer.getVisibility() == View.VISIBLE); outState.putBoolean(STATE_KEY_QUOTED_TEXT_SHOWN, mQuotedTextBar.getVisibility() == View.VISIBLE); outState.putString(STATE_KEY_ACTION, mAction); // If there are any outstanding save requests, ensure that it's noted in case it hasn't // finished by the time the activity is restored. outState.putLong(STATE_KEY_LAST_SAVE_TASK_ID, mLastSaveTaskId); } /** * Whether or not the current message being edited has a source message (i.e. is a reply, * or forward) that is loaded. */ private boolean hasSourceMessage() { return mSource != null; } /** * @return true if the activity was opened by the email app itself. */ private boolean isOpenedFromWithinApp() { Intent i = getIntent(); return (i != null && i.getBooleanExtra(EXTRA_FROM_WITHIN_APP, false)); } /** * Sets message as loaded and then initializes the TextWatchers. * @param isLoaded - value to which to set mMessageLoaded */ private void setMessageLoaded(boolean isLoaded) { if (mMessageLoaded != isLoaded) { mMessageLoaded = isLoaded; addListeners(); mInitiallyEmpty = areViewsEmpty(); } } private void setMessageChanged(boolean messageChanged) { boolean needsSaving = messageChanged && !(mInitiallyEmpty && areViewsEmpty()); if (mDraftNeedsSaving != needsSaving) { mDraftNeedsSaving = needsSaving; invalidateOptionsMenu(); } } /** * @return whether or not all text fields are empty (i.e. the entire compose message is empty) */ private boolean areViewsEmpty() { return (mToView.length() == 0) && (mCcView.length() == 0) && (mBccView.length() == 0) && (mSubjectView.length() == 0) && isBodyEmpty() && mAttachments.isEmpty(); } private boolean isBodyEmpty() { return (mMessageContentView.length() == 0) || mMessageContentView.getText() .toString().equals("\n" + getAccountSignature(mAccount)); } public void setFocusShifter(int fromViewId, final int targetViewId) { View label = findViewById(fromViewId); // xlarge only if (label != null) { final View target = UiUtilities.getView(this, targetViewId); label.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { target.requestFocus(); } }); } } /** * An {@link InputFilter} that implements special address cleanup rules. * The first space key entry following an "@" symbol that is followed by any combination * of letters and symbols, including one+ dots and zero commas, should insert an extra * comma (followed by the space). */ @VisibleForTesting static final InputFilter RECIPIENT_FILTER = new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { // Quick check - did they enter a single space? if (end-start != 1 || source.charAt(start) != ' ') { return null; } // determine if the characters before the new space fit the pattern // follow backwards and see if we find a comma, dot, or @ int scanBack = dstart; boolean dotFound = false; while (scanBack > 0) { char c = dest.charAt(--scanBack); switch (c) { case '.': dotFound = true; // one or more dots are req'd break; case ',': return null; case '@': if (!dotFound) { return null; } // we have found a comma-insert case. now just do it // in the least expensive way we can. if (source instanceof Spanned) { SpannableStringBuilder sb = new SpannableStringBuilder(","); sb.append(source); return sb; } else { return ", "; } default: // just keep going } } // no termination cases were found, so don't edit the input return null; } }; private void initViews() { ViewGroup toParent = UiUtilities.getViewOrNull(this, R.id.to_content); if (toParent != null) { - mToView = (MultiAutoCompleteTextView) toParent.findViewById(R.id.address_field); + mToView = (MultiAutoCompleteTextView) toParent.findViewById(R.id.to_address_field); ((TextView) toParent.findViewById(R.id.label)) .setText(R.string.message_compose_to_hint); ViewGroup ccParent, bccParent; ccParent = (ViewGroup) findViewById(R.id.cc_content); - mCcView = (MultiAutoCompleteTextView) ccParent.findViewById(R.id.address_field); + mCcView = (MultiAutoCompleteTextView) ccParent.findViewById(R.id.cc_address_field); ((TextView) ccParent.findViewById(R.id.label)) .setText(R.string.message_compose_cc_hint); bccParent = (ViewGroup) findViewById(R.id.bcc_content); - mBccView = (MultiAutoCompleteTextView) bccParent.findViewById(R.id.address_field); + mBccView = (MultiAutoCompleteTextView) bccParent.findViewById(R.id.bcc_address_field); ((TextView) bccParent.findViewById(R.id.label)) .setText(R.string.message_compose_bcc_hint); } else { mToView = UiUtilities.getView(this, R.id.to); mCcView = UiUtilities.getView(this, R.id.cc); mBccView = UiUtilities.getView(this, R.id.bcc); // add hints only when no labels exist if (UiUtilities.getViewOrNull(this, R.id.to_label) == null) { mToView.setHint(R.string.message_compose_to_hint); mCcView.setHint(R.string.message_compose_cc_hint); mBccView.setHint(R.string.message_compose_bcc_hint); } } mFromView = UiUtilities.getView(this, R.id.from); mCcBccContainer = UiUtilities.getView(this, R.id.cc_bcc_container); mSubjectView = UiUtilities.getView(this, R.id.subject); mMessageContentView = UiUtilities.getView(this, R.id.message_content); mAttachmentContentView = UiUtilities.getView(this, R.id.attachments); mAttachmentContainer = UiUtilities.getView(this, R.id.attachment_container); mQuotedTextBar = UiUtilities.getView(this, R.id.quoted_text_bar); mIncludeQuotedTextCheckBox = UiUtilities.getView(this, R.id.include_quoted_text); mQuotedText = UiUtilities.getView(this, R.id.quoted_text); InputFilter[] recipientFilters = new InputFilter[] { RECIPIENT_FILTER }; // NOTE: assumes no other filters are set mToView.setFilters(recipientFilters); mCcView.setFilters(recipientFilters); mBccView.setFilters(recipientFilters); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ mQuotedTextBar.setVisibility(View.GONE); setIncludeQuotedText(false, false); mIncludeQuotedTextCheckBox.setOnClickListener(this); EmailAddressValidator addressValidator = new EmailAddressValidator(); setupAddressAdapters(); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(addressValidator); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(addressValidator); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(addressValidator); final View addCcBccView = UiUtilities.getViewOrNull(this, R.id.add_cc_bcc); if (addCcBccView != null) { // Tablet view. addCcBccView.setOnClickListener(this); } final View addAttachmentView = UiUtilities.getViewOrNull(this, R.id.add_attachment); if (addAttachmentView != null) { // Tablet view. addAttachmentView.setOnClickListener(this); } setFocusShifter(R.id.to_label, R.id.to); setFocusShifter(R.id.cc_label, R.id.cc); setFocusShifter(R.id.bcc_label, R.id.bcc); setFocusShifter(R.id.subject_label, R.id.subject); setFocusShifter(R.id.tap_trap, R.id.message_content); mMessageContentView.setOnFocusChangeListener(this); updateAttachmentContainer(); mToView.requestFocus(); } /** * Initializes listeners. Should only be called once initializing of views is complete to * avoid unnecessary draft saving. */ private void addListeners() { mToView.addTextChangedListener(mWatcher); mCcView.addTextChangedListener(mWatcher); mBccView.addTextChangedListener(mWatcher); mSubjectView.addTextChangedListener(mWatcher); mMessageContentView.addTextChangedListener(mWatcher); } /** * Removes listeners from the user-editable fields. Can be used to temporarily disable them * while resetting fields (such as when changing from reply to reply all) to avoid * unnecessary saving. */ private void removeListeners() { mToView.removeTextChangedListener(mWatcher); mCcView.removeTextChangedListener(mWatcher); mBccView.removeTextChangedListener(mWatcher); mSubjectView.removeTextChangedListener(mWatcher); mMessageContentView.removeTextChangedListener(mWatcher); } /** * Set up address auto-completion adapters. */ private void setupAddressAdapters() { boolean supportsChips = ChipsUtil.supportsChipsUi(); if (supportsChips && mToView instanceof RecipientEditTextView) { mAddressAdapterTo = new RecipientAdapter(this, (RecipientEditTextView) mToView); mToView.setAdapter((RecipientAdapter) mAddressAdapterTo); } else { mAddressAdapterTo = new EmailAddressAdapter(this); mToView.setAdapter((EmailAddressAdapter) mAddressAdapterTo); } if (supportsChips && mCcView instanceof RecipientEditTextView) { mAddressAdapterCc = new RecipientAdapter(this, (RecipientEditTextView) mCcView); mCcView.setAdapter((RecipientAdapter) mAddressAdapterCc); } else { mAddressAdapterCc = new EmailAddressAdapter(this); mCcView.setAdapter((EmailAddressAdapter) mAddressAdapterCc); } if (supportsChips && mBccView instanceof RecipientEditTextView) { mAddressAdapterBcc = new RecipientAdapter(this, (RecipientEditTextView) mBccView); mBccView.setAdapter((RecipientAdapter) mAddressAdapterBcc); } else { mAddressAdapterBcc = new EmailAddressAdapter(this); mBccView.setAdapter((EmailAddressAdapter) mAddressAdapterBcc); } } /** * Asynchronously loads a draft message for editing. * This may or may not restore the view contents, depending on whether or not callers want, * since in the case of screen rotation, those are restored automatically. */ private void resumeDraft( long draftId, SendOrSaveMessageTask existingSaveTask, final boolean restoreViews) { // Note - this can be Message.NOT_SAVED if there is an existing save task in progress // for the draft we need to load. mDraft.mId = draftId; new LoadMessageTask(draftId, existingSaveTask, new OnMessageLoadHandler() { @Override public void onMessageLoaded(Message message, Body body) { message.mHtml = body.mHtmlContent; message.mText = body.mTextContent; message.mHtmlReply = body.mHtmlReply; message.mTextReply = body.mTextReply; message.mIntroText = body.mIntroText; message.mSourceKey = body.mSourceKey; mDraft = message; processDraftMessage(message, restoreViews); // Load attachments related to the draft. loadAttachments(message.mId, mAccount, new AttachmentLoadedCallback() { @Override public void onAttachmentLoaded(Attachment[] attachments) { for (Attachment attachment: attachments) { addAttachment(attachment); } } }); // If we're resuming an edit of a reply, reply-all, or forward, re-load the // source message if available so that we get more information. if (message.mSourceKey != Message.NOT_SAVED) { loadSourceMessage(message.mSourceKey, false /* restore views */); } } @Override public void onLoadFailed() { Utility.showToast(MessageCompose.this, R.string.error_loading_message_body); finish(); } }).executeParallel((Void[]) null); } @VisibleForTesting void processDraftMessage(Message message, boolean restoreViews) { if (restoreViews) { mSubjectView.setText(message.mSubject); addAddresses(mToView, Address.unpack(message.mTo)); Address[] cc = Address.unpack(message.mCc); if (cc.length > 0) { addAddresses(mCcView, cc); } Address[] bcc = Address.unpack(message.mBcc); if (bcc.length > 0) { addAddresses(mBccView, bcc); } mMessageContentView.setText(message.mText); showCcBccFieldsIfFilled(); setNewMessageFocus(); } setMessageChanged(false); // The quoted text must always be restored. displayQuotedText(message.mTextReply, message.mHtmlReply); setIncludeQuotedText( (mDraft.mFlags & Message.FLAG_NOT_INCLUDE_QUOTED_TEXT) == 0, false); } /** * Asynchronously loads a source message (to be replied or forwarded in this current view), * populating text fields and quoted text fields when the load finishes, if requested. */ private void loadSourceMessage(long sourceMessageId, final boolean restoreViews) { new LoadMessageTask(sourceMessageId, null, new OnMessageLoadHandler() { @Override public void onMessageLoaded(Message message, Body body) { message.mHtml = body.mHtmlContent; message.mText = body.mTextContent; message.mHtmlReply = null; message.mTextReply = null; message.mIntroText = null; mSource = message; mSourceAttachments = new ArrayList<Attachment>(); if (restoreViews) { processSourceMessage(mSource, mAccount); setInitialComposeText(null, getAccountSignature(mAccount)); } loadAttachments(message.mId, mAccount, new AttachmentLoadedCallback() { @Override public void onAttachmentLoaded(Attachment[] attachments) { final boolean supportsSmartForward = (mAccount.mFlags & Account.FLAGS_SUPPORTS_SMART_FORWARD) != 0; // Process the attachments to have the appropriate smart forward flags. for (Attachment attachment : attachments) { if (supportsSmartForward) { attachment.mFlags |= Attachment.FLAG_SMART_FORWARD; } mSourceAttachments.add(attachment); } if (isForward() && restoreViews) { if (processSourceMessageAttachments( mAttachments, mSourceAttachments, true)) { updateAttachmentUi(); setMessageChanged(true); } } } }); if (mAction.equals(ACTION_EDIT_DRAFT)) { // Resuming a draft may in fact be resuming a reply/reply all/forward. // Use a best guess and infer the action here. String inferredAction = inferAction(); if (inferredAction != null) { setAction(inferredAction); // No need to update the action selector as switching actions should do it. return; } } updateActionSelector(); } @Override public void onLoadFailed() { // The loading of the source message is only really required if it is needed // immediately to restore the view contents. In the case of resuming draft, it // is only needed to gather additional information. if (restoreViews) { Utility.showToast(MessageCompose.this, R.string.error_loading_message_body); finish(); } } }).executeParallel((Void[]) null); } /** * Infers whether or not the current state of the message best reflects either a reply, * reply-all, or forward. */ @VisibleForTesting String inferAction() { String subject = mSubjectView.getText().toString(); if (subject == null) { return null; } if (subject.toLowerCase().startsWith("fwd:")) { return ACTION_FORWARD; } else if (subject.toLowerCase().startsWith("re:")) { int numRecipients = getAddresses(mToView).length + getAddresses(mCcView).length + getAddresses(mBccView).length; if (numRecipients > 1) { return ACTION_REPLY_ALL; } else { return ACTION_REPLY; } } else { // Unsure. return null; } } private interface OnMessageLoadHandler { /** * Handles a load to a message (e.g. a draft message or a source message). */ void onMessageLoaded(Message message, Body body); /** * Handles a failure to load a message. */ void onLoadFailed(); } /** * Asynchronously loads a message and the account information. * This can be used to load a reference message (when replying) or when restoring a draft. */ private class LoadMessageTask extends EmailAsyncTask<Void, Void, Object[]> { /** * The message ID to load, if available. */ private long mMessageId; /** * A future-like reference to the save task which must complete prior to this load. */ private final SendOrSaveMessageTask mSaveTask; /** * A callback to pass the results of the load to. */ private final OnMessageLoadHandler mCallback; public LoadMessageTask( long messageId, SendOrSaveMessageTask saveTask, OnMessageLoadHandler callback) { super(mTaskTracker); mMessageId = messageId; mSaveTask = saveTask; mCallback = callback; } private long getIdToLoad() throws InterruptedException, ExecutionException { if (mMessageId == -1) { mMessageId = mSaveTask.get(); } return mMessageId; } @Override protected Object[] doInBackground(Void... params) { long messageId; try { messageId = getIdToLoad(); } catch (InterruptedException e) { // Don't have a good message ID to load - bail. Log.e(Logging.LOG_TAG, "Unable to load draft message since existing save task failed: " + e); return null; } catch (ExecutionException e) { // Don't have a good message ID to load - bail. Log.e(Logging.LOG_TAG, "Unable to load draft message since existing save task failed: " + e); return null; } Message message = Message.restoreMessageWithId(MessageCompose.this, messageId); if (message == null) { return null; } long accountId = message.mAccountKey; Account account = Account.restoreAccountWithId(MessageCompose.this, accountId); Body body; try { body = Body.restoreBodyWithMessageId(MessageCompose.this, message.mId); } catch (RuntimeException e) { Log.d(Logging.LOG_TAG, "Exception while loading message body: " + e); return null; } return new Object[] {message, body, account}; } @Override protected void onSuccess(Object[] results) { if ((results == null) || (results.length != 3)) { mCallback.onLoadFailed(); return; } final Message message = (Message) results[0]; final Body body = (Body) results[1]; final Account account = (Account) results[2]; if ((message == null) || (body == null) || (account == null)) { mCallback.onLoadFailed(); return; } setAccount(account); mCallback.onMessageLoaded(message, body); setMessageLoaded(true); } } private interface AttachmentLoadedCallback { /** * Handles completion of the loading of a set of attachments. * Callback will always happen on the main thread. */ void onAttachmentLoaded(Attachment[] attachment); } private void loadAttachments( final long messageId, final Account account, final AttachmentLoadedCallback callback) { new EmailAsyncTask<Void, Void, Attachment[]>(mTaskTracker) { @Override protected Attachment[] doInBackground(Void... params) { return Attachment.restoreAttachmentsWithMessageId(MessageCompose.this, messageId); } @Override protected void onSuccess(Attachment[] attachments) { if (attachments == null) { attachments = new Attachment[0]; } callback.onAttachmentLoaded(attachments); } }.executeParallel((Void[]) null); } @Override public void onFocusChange(View view, boolean focused) { if (focused) { switch (view.getId()) { case R.id.message_content: // When focusing on the message content via tabbing to it, or other means of // auto focusing, move the cursor to the end of the body (before the signature). if (mMessageContentView.getSelectionStart() == 0 && mMessageContentView.getSelectionEnd() == 0) { // There is no way to determine if the focus change was programmatic or due // to keyboard event, or if it was due to a tap/restore. Use a best-guess // by using the fact that auto-focus/keyboard tabs set the selection to 0. setMessageContentSelection(getAccountSignature(mAccount)); } } } } private static void addAddresses(MultiAutoCompleteTextView view, Address[] addresses) { if (addresses == null) { return; } for (Address address : addresses) { addAddress(view, address.toString()); } } private static void addAddresses(MultiAutoCompleteTextView view, String[] addresses) { if (addresses == null) { return; } for (String oneAddress : addresses) { addAddress(view, oneAddress); } } private static void addAddresses(MultiAutoCompleteTextView view, String addresses) { if (addresses == null) { return; } Address[] unpackedAddresses = Address.unpack(addresses); for (Address address : unpackedAddresses) { addAddress(view, address.toString()); } } private static void addAddress(MultiAutoCompleteTextView view, String address) { view.append(address + ", "); } private static String getPackedAddresses(TextView view) { Address[] addresses = Address.parse(view.getText().toString().trim()); return Address.pack(addresses); } private static Address[] getAddresses(TextView view) { Address[] addresses = Address.parse(view.getText().toString().trim()); return addresses; } /* * Computes a short string indicating the destination of the message based on To, Cc, Bcc. * If only one address appears, returns the friendly form of that address. * Otherwise returns the friendly form of the first address appended with "and N others". */ private String makeDisplayName(String packedTo, String packedCc, String packedBcc) { Address first = null; int nRecipients = 0; for (String packed: new String[] {packedTo, packedCc, packedBcc}) { Address[] addresses = Address.unpack(packed); nRecipients += addresses.length; if (first == null && addresses.length > 0) { first = addresses[0]; } } if (nRecipients == 0) { return ""; } String friendly = first.toFriendly(); if (nRecipients == 1) { return friendly; } return this.getString(R.string.message_compose_display_name, friendly, nRecipients - 1); } private ContentValues getUpdateContentValues(Message message) { ContentValues values = new ContentValues(); values.put(MessageColumns.TIMESTAMP, message.mTimeStamp); values.put(MessageColumns.FROM_LIST, message.mFrom); values.put(MessageColumns.TO_LIST, message.mTo); values.put(MessageColumns.CC_LIST, message.mCc); values.put(MessageColumns.BCC_LIST, message.mBcc); values.put(MessageColumns.SUBJECT, message.mSubject); values.put(MessageColumns.DISPLAY_NAME, message.mDisplayName); values.put(MessageColumns.FLAG_READ, message.mFlagRead); values.put(MessageColumns.FLAG_LOADED, message.mFlagLoaded); values.put(MessageColumns.FLAG_ATTACHMENT, message.mFlagAttachment); values.put(MessageColumns.FLAGS, message.mFlags); return values; } /** * Updates the given message using values from the compose UI. * * @param message The message to be updated. * @param account the account (used to obtain From: address). * @param hasAttachments true if it has one or more attachment. * @param sending set true if the message is about to sent, in which case we perform final * clean up; */ private void updateMessage(Message message, Account account, boolean hasAttachments, boolean sending) { if (message.mMessageId == null || message.mMessageId.length() == 0) { message.mMessageId = Utility.generateMessageId(); } message.mTimeStamp = System.currentTimeMillis(); message.mFrom = new Address(account.getEmailAddress(), account.getSenderName()).pack(); message.mTo = getPackedAddresses(mToView); message.mCc = getPackedAddresses(mCcView); message.mBcc = getPackedAddresses(mBccView); message.mSubject = mSubjectView.getText().toString(); message.mText = mMessageContentView.getText().toString(); message.mAccountKey = account.mId; message.mDisplayName = makeDisplayName(message.mTo, message.mCc, message.mBcc); message.mFlagRead = true; message.mFlagLoaded = Message.FLAG_LOADED_COMPLETE; message.mFlagAttachment = hasAttachments; // Use the Intent to set flags saying this message is a reply or a forward and save the // unique id of the source message if (mSource != null && mQuotedTextBar.getVisibility() == View.VISIBLE) { message.mSourceKey = mSource.mId; // If the quote bar is visible; this must either be a reply or forward // Get the body of the source message here message.mHtmlReply = mSource.mHtml; message.mTextReply = mSource.mText; String fromAsString = Address.unpackToString(mSource.mFrom); if (isForward()) { message.mFlags |= Message.FLAG_TYPE_FORWARD; String subject = mSource.mSubject; String to = Address.unpackToString(mSource.mTo); String cc = Address.unpackToString(mSource.mCc); message.mIntroText = getString(R.string.message_compose_fwd_header_fmt, subject, fromAsString, to != null ? to : "", cc != null ? cc : ""); } else { message.mFlags |= Message.FLAG_TYPE_REPLY; message.mIntroText = getString(R.string.message_compose_reply_header_fmt, fromAsString); } } if (includeQuotedText()) { message.mFlags &= ~Message.FLAG_NOT_INCLUDE_QUOTED_TEXT; } else { message.mFlags |= Message.FLAG_NOT_INCLUDE_QUOTED_TEXT; if (sending) { // If we are about to send a message, and not including the original message, // clear the related field. // We can't do this until the last minutes, so that the user can change their // mind later and want to include it again. mDraft.mIntroText = null; mDraft.mTextReply = null; mDraft.mHtmlReply = null; // Note that mSourceKey is not cleared out as this is still considered a // reply/forward. } } } private class SendOrSaveMessageTask extends EmailAsyncTask<Void, Void, Long> { private final boolean mSend; private final long mTaskId; /** A context that will survive even past activity destruction. */ private final Context mContext; public SendOrSaveMessageTask(long taskId, boolean send) { super(null /* DO NOT cancel in onDestroy */); if (send && ActivityManager.isUserAMonkey()) { Log.d(Logging.LOG_TAG, "Inhibiting send while monkey is in charge."); send = false; } mTaskId = taskId; mSend = send; mContext = getApplicationContext(); sActiveSaveTasks.put(mTaskId, this); } @Override protected Long doInBackground(Void... params) { synchronized (mDraft) { updateMessage(mDraft, mAccount, mAttachments.size() > 0, mSend); ContentResolver resolver = getContentResolver(); if (mDraft.isSaved()) { // Update the message Uri draftUri = ContentUris.withAppendedId(Message.SYNCED_CONTENT_URI, mDraft.mId); resolver.update(draftUri, getUpdateContentValues(mDraft), null, null); // Update the body ContentValues values = new ContentValues(); values.put(BodyColumns.TEXT_CONTENT, mDraft.mText); values.put(BodyColumns.TEXT_REPLY, mDraft.mTextReply); values.put(BodyColumns.HTML_REPLY, mDraft.mHtmlReply); values.put(BodyColumns.INTRO_TEXT, mDraft.mIntroText); values.put(BodyColumns.SOURCE_MESSAGE_KEY, mDraft.mSourceKey); Body.updateBodyWithMessageId(MessageCompose.this, mDraft.mId, values); } else { // mDraft.mId is set upon return of saveToMailbox() mController.saveToMailbox(mDraft, Mailbox.TYPE_DRAFTS); } // For any unloaded attachment, set the flag saying we need it loaded boolean hasUnloadedAttachments = false; for (Attachment attachment : mAttachments) { if (attachment.mContentUri == null && ((attachment.mFlags & Attachment.FLAG_SMART_FORWARD) == 0)) { attachment.mFlags |= Attachment.FLAG_DOWNLOAD_FORWARD; hasUnloadedAttachments = true; if (Email.DEBUG) { Log.d(Logging.LOG_TAG, "Requesting download of attachment #" + attachment.mId); } } // Make sure the UI version of the attachment has the now-correct id; we will // use the id again when coming back from picking new attachments if (!attachment.isSaved()) { // this attachment is new so save it to DB. attachment.mMessageKey = mDraft.mId; attachment.save(MessageCompose.this); } else if (attachment.mMessageKey != mDraft.mId) { // We clone the attachment and save it again; otherwise, it will // continue to point to the source message. From this point forward, // the attachments will be independent of the original message in the // database; however, we still need the message on the server in order // to retrieve unloaded attachments attachment.mMessageKey = mDraft.mId; ContentValues cv = attachment.toContentValues(); cv.put(Attachment.FLAGS, attachment.mFlags); cv.put(Attachment.MESSAGE_KEY, mDraft.mId); getContentResolver().insert(Attachment.CONTENT_URI, cv); } } if (mSend) { // Let the user know if message sending might be delayed by background // downlading of unloaded attachments if (hasUnloadedAttachments) { Utility.showToast(MessageCompose.this, R.string.message_view_attachment_background_load); } mController.sendMessage(mDraft); ArrayList<CharSequence> addressTexts = new ArrayList<CharSequence>(); addressTexts.add(mToView.getText()); addressTexts.add(mCcView.getText()); addressTexts.add(mBccView.getText()); DataUsageStatUpdater updater = new DataUsageStatUpdater(mContext); updater.updateWithRfc822Address(addressTexts); } return mDraft.mId; } } private boolean shouldShowSaveToast() { // Don't show the toast when rotating, or when opening an Activity on top of this one. return !isChangingConfigurations() && !mPickingAttachment; } @Override protected void onSuccess(Long draftId) { // Note that send or save tasks are always completed, even if the activity // finishes earlier. sActiveSaveTasks.remove(mTaskId); // Don't display the toast if the user is just changing the orientation if (!mSend && shouldShowSaveToast()) { Toast.makeText(mContext, R.string.message_saved_toast, Toast.LENGTH_LONG).show(); } } } /** * Send or save a message: * - out of the UI thread * - write to Drafts * - if send, invoke Controller.sendMessage() * - when operation is complete, display toast */ private void sendOrSaveMessage(boolean send) { if (!mMessageLoaded) { Log.w(Logging.LOG_TAG, "Attempted to save draft message prior to the state being fully loaded"); return; } synchronized (sActiveSaveTasks) { mLastSaveTaskId = sNextSaveTaskId++; SendOrSaveMessageTask task = new SendOrSaveMessageTask(mLastSaveTaskId, send); // Ensure the tasks are executed serially so that rapid scheduling doesn't result // in inconsistent data. task.executeSerial(); } } private void saveIfNeeded() { if (!mDraftNeedsSaving) { return; } setMessageChanged(false); sendOrSaveMessage(false); } /** * Checks whether all the email addresses listed in TO, CC, BCC are valid. */ @VisibleForTesting boolean isAddressAllValid() { boolean supportsChips = ChipsUtil.supportsChipsUi(); for (TextView view : new TextView[]{mToView, mCcView, mBccView}) { String addresses = view.getText().toString().trim(); if (!Address.isAllValid(addresses)) { // Don't show an error message if we're using chips as the chips have // their own error state. if (!supportsChips || !(view instanceof RecipientEditTextView)) { view.setError(getString(R.string.message_compose_error_invalid_email)); } return false; } } return true; } private void onSend() { if (!isAddressAllValid()) { Toast.makeText(this, getString(R.string.message_compose_error_invalid_email), Toast.LENGTH_LONG).show(); } else if (getAddresses(mToView).length == 0 && getAddresses(mCcView).length == 0 && getAddresses(mBccView).length == 0) { mToView.setError(getString(R.string.message_compose_error_no_recipients)); Toast.makeText(this, getString(R.string.message_compose_error_no_recipients), Toast.LENGTH_LONG).show(); } else { sendOrSaveMessage(true); setMessageChanged(false); finish(); } } private void showQuickResponseDialog() { InsertQuickResponseDialog.newInstance(null, mAccount) .show(getFragmentManager(), null); } /** * Inserts the selected QuickResponse into the message body at the current cursor position. */ @Override public void onQuickResponseSelected(CharSequence text) { int start = mMessageContentView.getSelectionStart(); int end = mMessageContentView.getSelectionEnd(); mMessageContentView.getEditableText().replace(start, end, text); } private void onDiscard() { DeleteMessageConfirmationDialog.newInstance(1, null).show(getFragmentManager(), "dialog"); } /** * Called when ok on the "discard draft" dialog is pressed. Actually delete the draft. */ @Override public void onDeleteMessageConfirmationDialogOkPressed() { if (mDraft.mId > 0) { // By the way, we can't pass the message ID from onDiscard() to here (using a // dialog argument or whatever), because you can rotate the screen when the dialog is // shown, and during rotation we save & restore the draft. If it's the // first save, we give it an ID at this point for the first time (and last time). // Which means it's possible for a draft to not have an ID in onDiscard(), // but here. mController.deleteMessage(mDraft.mId); } Utility.showToast(MessageCompose.this, R.string.message_discarded_toast); setMessageChanged(false); finish(); } /** * Handles an explicit user-initiated action to save a draft. */ private void onSave() { saveIfNeeded(); } private void showCcBccFieldsIfFilled() { if ((mCcView.length() > 0) || (mBccView.length() > 0)) { showCcBccFields(); } } private void showCcBccFields() { mCcBccContainer.setVisibility(View.VISIBLE); UiUtilities.setVisibilitySafe(this, R.id.add_cc_bcc, View.INVISIBLE); invalidateOptionsMenu(); } /** * Kick off a picker for whatever kind of MIME types we'll accept and let Android take over. */ private void onAddAttachment() { Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType(AttachmentUtilities.ACCEPTABLE_ATTACHMENT_SEND_UI_TYPES[0]); mPickingAttachment = true; startActivityForResult( Intent.createChooser(i, getString(R.string.choose_attachment_dialog_title)), ACTIVITY_REQUEST_PICK_ATTACHMENT); } private Attachment loadAttachmentInfo(Uri uri) { long size = -1; ContentResolver contentResolver = getContentResolver(); // Load name & size independently, because not all providers support both final String name = Utility.getContentFileName(this, uri); Cursor metadataCursor = contentResolver.query(uri, ATTACHMENT_META_SIZE_PROJECTION, null, null, null); if (metadataCursor != null) { try { if (metadataCursor.moveToFirst()) { size = metadataCursor.getLong(ATTACHMENT_META_SIZE_COLUMN_SIZE); } } finally { metadataCursor.close(); } } // When the size is not provided, we need to determine it locally. if (size < 0) { // if the URI is a file: URI, ask file system for its size if ("file".equalsIgnoreCase(uri.getScheme())) { String path = uri.getPath(); if (path != null) { File file = new File(path); size = file.length(); // Returns 0 for file not found } } if (size <= 0) { // The size was not measurable; This attachment is not safe to use. // Quick hack to force a relevant error into the UI // TODO: A proper announcement of the problem size = AttachmentUtilities.MAX_ATTACHMENT_UPLOAD_SIZE + 1; } } Attachment attachment = new Attachment(); attachment.mFileName = name; attachment.mContentUri = uri.toString(); attachment.mSize = size; attachment.mMimeType = AttachmentUtilities.inferMimeTypeForUri(this, uri); return attachment; } private void addAttachment(Attachment attachment) { // Before attaching the attachment, make sure it meets any other pre-attach criteria if (attachment.mSize > AttachmentUtilities.MAX_ATTACHMENT_UPLOAD_SIZE) { Toast.makeText(this, R.string.message_compose_attachment_size, Toast.LENGTH_LONG) .show(); return; } mAttachments.add(attachment); updateAttachmentUi(); } private void updateAttachmentUi() { mAttachmentContentView.removeAllViews(); for (Attachment attachment : mAttachments) { // Note: allowDelete is set in two cases: // 1. First time a message (w/ attachments) is forwarded, // where action == ACTION_FORWARD // 2. 1 -> Save -> Reopen // but FLAG_SMART_FORWARD is already set at 1. // Even if the account supports smart-forward, attachments added // manually are still removable. final boolean allowDelete = (attachment.mFlags & Attachment.FLAG_SMART_FORWARD) == 0; View view = getLayoutInflater().inflate(R.layout.message_compose_attachment, mAttachmentContentView, false); TextView nameView = UiUtilities.getView(view, R.id.attachment_name); ImageButton delete = UiUtilities.getView(view, R.id.attachment_delete); TextView sizeView = UiUtilities.getView(view, R.id.attachment_size); nameView.setText(attachment.mFileName); if (attachment.mSize > 0) { sizeView.setText(UiUtilities.formatSize(this, attachment.mSize)); } else { sizeView.setVisibility(View.GONE); } if (allowDelete) { delete.setOnClickListener(this); delete.setTag(view); } else { delete.setVisibility(View.INVISIBLE); } view.setTag(attachment); mAttachmentContentView.addView(view); } updateAttachmentContainer(); } private void updateAttachmentContainer() { mAttachmentContainer.setVisibility(mAttachmentContentView.getChildCount() == 0 ? View.GONE : View.VISIBLE); } private void addAttachmentFromUri(Uri uri) { addAttachment(loadAttachmentInfo(uri)); } /** * Same as {@link #addAttachmentFromUri}, but does the mime-type check against * {@link AttachmentUtilities#ACCEPTABLE_ATTACHMENT_SEND_INTENT_TYPES}. */ private void addAttachmentFromSendIntent(Uri uri) { final Attachment attachment = loadAttachmentInfo(uri); final String mimeType = attachment.mMimeType; if (!TextUtils.isEmpty(mimeType) && MimeUtility.mimeTypeMatches(mimeType, AttachmentUtilities.ACCEPTABLE_ATTACHMENT_SEND_INTENT_TYPES)) { addAttachment(attachment); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { mPickingAttachment = false; if (data == null) { return; } addAttachmentFromUri(data.getData()); setMessageChanged(true); } private boolean includeQuotedText() { return mIncludeQuotedTextCheckBox.isChecked(); } public void onClick(View view) { if (handleCommand(view.getId())) { return; } switch (view.getId()) { case R.id.attachment_delete: onDeleteAttachmentIconClicked(view); break; } } private void setIncludeQuotedText(boolean include, boolean updateNeedsSaving) { mIncludeQuotedTextCheckBox.setChecked(include); mQuotedText.setVisibility(mIncludeQuotedTextCheckBox.isChecked() ? View.VISIBLE : View.GONE); if (updateNeedsSaving) { setMessageChanged(true); } } private void onDeleteAttachmentIconClicked(View delButtonView) { View attachmentView = (View) delButtonView.getTag(); Attachment attachment = (Attachment) attachmentView.getTag(); deleteAttachment(mAttachments, attachment); updateAttachmentUi(); setMessageChanged(true); } /** * Removes an attachment from the current message. * If the attachment has previous been saved in the db (i.e. this is a draft message which * has previously been saved), then the draft is deleted from the db. * * This does not update the UI to remove the attachment view. * @param attachments the list of attachments to delete from. Injected for tests. * @param attachment the attachment to delete */ private void deleteAttachment(List<Attachment> attachments, Attachment attachment) { attachments.remove(attachment); if ((attachment.mMessageKey == mDraft.mId) && attachment.isSaved()) { final long attachmentId = attachment.mId; EmailAsyncTask.runAsyncParallel(new Runnable() { @Override public void run() { mController.deleteAttachment(attachmentId); } }); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (handleCommand(item.getItemId())) { return true; } return super.onOptionsItemSelected(item); } private boolean handleCommand(int viewId) { switch (viewId) { case android.R.id.home: onActionBarHomePressed(); return true; case R.id.send: onSend(); return true; case R.id.save: onSave(); return true; case R.id.show_quick_text_list_dialog: showQuickResponseDialog(); return true; case R.id.discard: onDiscard(); return true; case R.id.include_quoted_text: // The checkbox is already toggled at this point. setIncludeQuotedText(mIncludeQuotedTextCheckBox.isChecked(), true); return true; case R.id.add_cc_bcc: showCcBccFields(); return true; case R.id.add_attachment: onAddAttachment(); return true; } return false; } private void onActionBarHomePressed() { finish(); if (isOpenedFromWithinApp()) { // If opened from within the app, we just close it. } else { // Otherwise, need to open the main screen for the appropriate account. // Note that mAccount should always be set by the time the action bar is set up. startActivity(Welcome.createOpenAccountInboxIntent(this, mAccount.mId)); } } private void setAction(String action) { if (Objects.equal(action, mAction)) { return; } mAction = action; onActionChanged(); } /** * Handles changing from reply/reply all/forward states. Note: this activity cannot transition * from a standard compose state to any of the other three states. */ private void onActionChanged() { if (!hasSourceMessage()) { return; } // Temporarily remove listeners so that changing action does not invalidate and save message removeListeners(); processSourceMessage(mSource, mAccount); // Note that the attachments might not be loaded yet, but this will safely noop // if that's the case, and the attachments will be processed when they load. if (processSourceMessageAttachments(mAttachments, mSourceAttachments, isForward())) { updateAttachmentUi(); setMessageChanged(true); } updateActionSelector(); addListeners(); } /** * Updates UI components that allows the user to switch between reply/reply all/forward. */ private void updateActionSelector() { ActionBar actionBar = getActionBar(); if (shouldUseActionTabs()) { // Tab-based mode switching. if (actionBar.getTabCount() > 0) { actionBar.removeAllTabs(); } createAndAddTab(R.string.reply_action, ACTION_REPLY); createAndAddTab(R.string.reply_all_action, ACTION_REPLY_ALL); createAndAddTab(R.string.forward_action, ACTION_FORWARD); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); } else { // Spinner based mode switching. if (mActionSpinnerAdapter == null) { mActionSpinnerAdapter = new ActionSpinnerAdapter(this); actionBar.setListNavigationCallbacks( mActionSpinnerAdapter, ACTION_SPINNER_LISTENER); } actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setSelectedNavigationItem( ActionSpinnerAdapter.getActionPosition(mAction)); } actionBar.setDisplayShowTitleEnabled(false); } private final TabListener ACTION_TAB_LISTENER = new TabListener() { @Override public void onTabReselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) {} @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { String action = (String) tab.getTag(); setAction(action); } }; private final OnNavigationListener ACTION_SPINNER_LISTENER = new OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { setAction(ActionSpinnerAdapter.getAction(itemPosition)); return true; } }; private static class ActionSpinnerAdapter extends ArrayAdapter<String> { public ActionSpinnerAdapter(final Context context) { super(context, android.R.layout.simple_spinner_dropdown_item, android.R.id.text1, Lists.newArrayList(ACTION_REPLY, ACTION_REPLY_ALL, ACTION_FORWARD)); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View result = super.getDropDownView(position, convertView, parent); ((TextView) result.findViewById(android.R.id.text1)).setText(getDisplayValue(position)); return result; } @Override public View getView(int position, View convertView, ViewGroup parent) { View result = super.getView(position, convertView, parent); ((TextView) result.findViewById(android.R.id.text1)).setText(getDisplayValue(position)); return result; } private String getDisplayValue(int position) { switch (position) { case 0: return getContext().getString(R.string.reply_action); case 1: return getContext().getString(R.string.reply_all_action); case 2: return getContext().getString(R.string.forward_action); default: throw new IllegalArgumentException("Invalid action type for spinner"); } } public static String getAction(int position) { switch (position) { case 0: return ACTION_REPLY; case 1: return ACTION_REPLY_ALL; case 2: return ACTION_FORWARD; default: throw new IllegalArgumentException("Invalid action type for spinner"); } } public static int getActionPosition(String action) { if (ACTION_REPLY.equals(action)) { return 0; } else if (ACTION_REPLY_ALL.equals(action)) { return 1; } else if (ACTION_FORWARD.equals(action)) { return 2; } throw new IllegalArgumentException("Invalid action type for spinner"); } } private Tab createAndAddTab(int labelResource, final String action) { ActionBar.Tab tab = getActionBar().newTab(); boolean selected = mAction.equals(action); tab.setTag(action); tab.setText(getString(labelResource)); tab.setTabListener(ACTION_TAB_LISTENER); getActionBar().addTab(tab, selected); return tab; } private boolean shouldUseActionTabs() { return getResources().getBoolean(R.bool.message_compose_action_tabs); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); getMenuInflater().inflate(R.menu.message_compose_option, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.save).setEnabled(mDraftNeedsSaving); MenuItem addCcBcc = menu.findItem(R.id.add_cc_bcc); if (addCcBcc != null) { // Only available on phones. addCcBcc.setVisible( (mCcBccContainer == null) || (mCcBccContainer.getVisibility() != View.VISIBLE)); } MenuItem insertQuickResponse = menu.findItem(R.id.show_quick_text_list_dialog); insertQuickResponse.setVisible(mQuickResponsesAvailable); insertQuickResponse.setEnabled(mQuickResponsesAvailable); return true; } /** * Set a message body and a signature when the Activity is launched. * * @param text the message body */ @VisibleForTesting void setInitialComposeText(CharSequence text, String signature) { mMessageContentView.setText(""); int textLength = 0; if (text != null) { mMessageContentView.append(text); textLength = text.length(); } if (!TextUtils.isEmpty(signature)) { if (textLength == 0 || text.charAt(textLength - 1) != '\n') { mMessageContentView.append("\n"); } mMessageContentView.append(signature); // Reset cursor to right before the signature. mMessageContentView.setSelection(textLength); } } /** * Fill all the widgets with the content found in the Intent Extra, if any. * * Note that we don't actually check the intent action (typically VIEW, SENDTO, or SEND). * There is enough overlap in the definitions that it makes more sense to simply check for * all available data and use as much of it as possible. * * With one exception: EXTRA_STREAM is defined as only valid for ACTION_SEND. * * @param intent the launch intent */ @VisibleForTesting void initFromIntent(Intent intent) { setAccount(intent); // First, add values stored in top-level extras String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL); if (extraStrings != null) { addAddresses(mToView, extraStrings); } extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC); if (extraStrings != null) { addAddresses(mCcView, extraStrings); } extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC); if (extraStrings != null) { addAddresses(mBccView, extraStrings); } String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT); if (extraString != null) { mSubjectView.setText(extraString); } // Next, if we were invoked with a URI, try to interpret it // We'll take two courses here. If it's mailto:, there is a specific set of rules // that define various optional fields. However, for any other scheme, we'll simply // take the entire scheme-specific part and interpret it as a possible list of addresses. final Uri dataUri = intent.getData(); if (dataUri != null) { if ("mailto".equals(dataUri.getScheme())) { initializeFromMailTo(dataUri.toString()); } else { String toText = dataUri.getSchemeSpecificPart(); if (toText != null) { addAddresses(mToView, toText.split(",")); } } } // Next, fill in the plaintext (note, this will override mailto:?body=) CharSequence text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT); setInitialComposeText(text, getAccountSignature(mAccount)); // Next, convert EXTRA_STREAM into an attachment if (Intent.ACTION_SEND.equals(mAction) && intent.hasExtra(Intent.EXTRA_STREAM)) { Uri uri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (uri != null) { addAttachmentFromSendIntent(uri); } } if (Intent.ACTION_SEND_MULTIPLE.equals(mAction) && intent.hasExtra(Intent.EXTRA_STREAM)) { ArrayList<Parcelable> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); if (list != null) { for (Parcelable parcelable : list) { Uri uri = (Uri) parcelable; if (uri != null) { addAttachmentFromSendIntent(uri); } } } } // Finally - expose fields that were filled in but are normally hidden, and set focus showCcBccFieldsIfFilled(); setNewMessageFocus(); } /** * When we are launched with an intent that includes a mailto: URI, we can actually * gather quite a few of our message fields from it. * * @param mailToString the href (which must start with "mailto:"). */ private void initializeFromMailTo(String mailToString) { // Chop up everything between mailto: and ? to find recipients int index = mailToString.indexOf("?"); int length = "mailto".length() + 1; String to; try { // Extract the recipient after mailto: if (index == -1) { to = decode(mailToString.substring(length)); } else { to = decode(mailToString.substring(length, index)); } addAddresses(mToView, to.split(" ,")); } catch (UnsupportedEncodingException e) { Log.e(Logging.LOG_TAG, e.getMessage() + " while decoding '" + mailToString + "'"); } // Extract the other parameters // We need to disguise this string as a URI in order to parse it Uri uri = Uri.parse("foo://" + mailToString); List<String> cc = uri.getQueryParameters("cc"); addAddresses(mCcView, cc.toArray(new String[cc.size()])); List<String> otherTo = uri.getQueryParameters("to"); addAddresses(mCcView, otherTo.toArray(new String[otherTo.size()])); List<String> bcc = uri.getQueryParameters("bcc"); addAddresses(mBccView, bcc.toArray(new String[bcc.size()])); List<String> subject = uri.getQueryParameters("subject"); if (subject.size() > 0) { mSubjectView.setText(subject.get(0)); } List<String> body = uri.getQueryParameters("body"); if (body.size() > 0) { setInitialComposeText(body.get(0), getAccountSignature(mAccount)); } } private String decode(String s) throws UnsupportedEncodingException { return URLDecoder.decode(s, "UTF-8"); } /** * Displays quoted text from the original email */ private void displayQuotedText(String textBody, String htmlBody) { // Only use plain text if there is no HTML body boolean plainTextFlag = TextUtils.isEmpty(htmlBody); String text = plainTextFlag ? textBody : htmlBody; if (text != null) { text = plainTextFlag ? EmailHtmlUtil.escapeCharacterToDisplay(text) : text; // TODO: re-enable EmailHtmlUtil.resolveInlineImage() for HTML // EmailHtmlUtil.resolveInlineImage(getContentResolver(), mAccount, // text, message, 0); mQuotedTextBar.setVisibility(View.VISIBLE); if (mQuotedText != null) { mQuotedText.loadDataWithBaseURL("email://", text, "text/html", "utf-8", null); } } } /** * Given a packed address String, the address of our sending account, a view, and a list of * addressees already added to other addressing views, adds unique addressees that don't * match our address to the passed in view */ private static boolean safeAddAddresses(String addrs, String ourAddress, MultiAutoCompleteTextView view, ArrayList<Address> addrList) { boolean added = false; for (Address address : Address.unpack(addrs)) { // Don't send to ourselves or already-included addresses if (!address.getAddress().equalsIgnoreCase(ourAddress) && !addrList.contains(address)) { addrList.add(address); addAddress(view, address.toString()); added = true; } } return added; } /** * Set up the to and cc views properly for the "reply" and "replyAll" cases. What's important * is that we not 1) send to ourselves, and 2) duplicate addressees. * @param message the message we're replying to * @param account the account we're sending from * @param replyAll whether this is a replyAll (vs a reply) */ @VisibleForTesting void setupAddressViews(Message message, Account account, boolean replyAll) { // Start clean. clearAddressViews(); // If Reply-to: addresses are included, use those; otherwise, use the From: address. Address[] replyToAddresses = Address.unpack(message.mReplyTo); if (replyToAddresses.length == 0) { replyToAddresses = Address.unpack(message.mFrom); } // Check if ourAddress is one of the replyToAddresses to decide how to populate To: field String ourAddress = account.mEmailAddress; boolean containsOurAddress = false; for (Address address : replyToAddresses) { if (ourAddress.equalsIgnoreCase(address.getAddress())) { containsOurAddress = true; break; } } if (containsOurAddress) { addAddresses(mToView, message.mTo); } else { addAddresses(mToView, replyToAddresses); } if (replyAll) { // Keep a running list of addresses we're sending to ArrayList<Address> allAddresses = new ArrayList<Address>(); for (Address address: replyToAddresses) { allAddresses.add(address); } if (!containsOurAddress) { safeAddAddresses(message.mTo, ourAddress, mCcView, allAddresses); } safeAddAddresses(message.mCc, ourAddress, mCcView, allAddresses); } showCcBccFieldsIfFilled(); } private void clearAddressViews() { mToView.setText(""); mCcView.setText(""); mBccView.setText(""); } /** * Pull out the parts of the now loaded source message and apply them to the new message * depending on the type of message being composed. */ @VisibleForTesting void processSourceMessage(Message message, Account account) { String subject = message.mSubject; if (subject == null) { subject = ""; } if (ACTION_REPLY.equals(mAction) || ACTION_REPLY_ALL.equals(mAction)) { setupAddressViews(message, account, ACTION_REPLY_ALL.equals(mAction)); if (!subject.toLowerCase().startsWith("re:")) { mSubjectView.setText("Re: " + subject); } else { mSubjectView.setText(subject); } displayQuotedText(message.mText, message.mHtml); setIncludeQuotedText(true, false); } else if (ACTION_FORWARD.equals(mAction)) { clearAddressViews(); mSubjectView.setText(!subject.toLowerCase().startsWith("fwd:") ? "Fwd: " + subject : subject); displayQuotedText(message.mText, message.mHtml); setIncludeQuotedText(true, false); } else { Log.w(Logging.LOG_TAG, "Unexpected action for a call to processSourceMessage " + mAction); } showCcBccFieldsIfFilled(); setNewMessageFocus(); } /** * Processes the source attachments and ensures they're either included or excluded from * a list of active attachments. This can be used to add attachments for a forwarded message, or * to remove them if going from a "Forward" to a "Reply" * Uniqueness is based on filename. * * @param current the list of active attachments on the current message. Injected for tests. * @param sourceAttachments the list of attachments related with the source message. Injected * for tests. * @param include whether or not the sourceMessages should be included or excluded from the * current list of active attachments * @return whether or not the current attachments were modified */ @VisibleForTesting boolean processSourceMessageAttachments( List<Attachment> current, List<Attachment> sourceAttachments, boolean include) { // Build a map of filename to the active attachments. HashMap<String, Attachment> currentNames = new HashMap<String, Attachment>(); for (Attachment attachment : current) { currentNames.put(attachment.mFileName, attachment); } boolean dirty = false; if (include) { // Needs to make sure it's in the list. for (Attachment attachment : sourceAttachments) { if (!currentNames.containsKey(attachment.mFileName)) { current.add(attachment); dirty = true; } } } else { // Need to remove the source attachments. HashSet<String> sourceNames = new HashSet<String>(); for (Attachment attachment : sourceAttachments) { if (currentNames.containsKey(attachment.mFileName)) { deleteAttachment(current, currentNames.get(attachment.mFileName)); dirty = true; } } } return dirty; } /** * Set a cursor to the end of a body except a signature. */ @VisibleForTesting void setMessageContentSelection(String signature) { int selection = mMessageContentView.length(); if (!TextUtils.isEmpty(signature)) { int signatureLength = signature.length(); int estimatedSelection = selection - signatureLength; if (estimatedSelection >= 0) { CharSequence text = mMessageContentView.getText(); int i = 0; while (i < signatureLength && text.charAt(estimatedSelection + i) == signature.charAt(i)) { ++i; } if (i == signatureLength) { selection = estimatedSelection; while (selection > 0 && text.charAt(selection - 1) == '\n') { --selection; } } } } mMessageContentView.setSelection(selection, selection); } /** * In order to accelerate typing, position the cursor in the first empty field, * or at the end of the body composition field if none are empty. Typically, this will * play out as follows: * Reply / Reply All - put cursor in the empty message body * Forward - put cursor in the empty To field * Edit Draft - put cursor in whatever field still needs entry */ private void setNewMessageFocus() { if (mToView.length() == 0) { mToView.requestFocus(); } else if (mSubjectView.length() == 0) { mSubjectView.requestFocus(); } else { mMessageContentView.requestFocus(); } } private boolean isForward() { return ACTION_FORWARD.equals(mAction); } /** * @return the signature for the specified account, if non-null. If the account specified is * null or has no signature, {@code null} is returned. */ private static String getAccountSignature(Account account) { return (account == null) ? null : account.mSignature; } }
false
true
private void initViews() { ViewGroup toParent = UiUtilities.getViewOrNull(this, R.id.to_content); if (toParent != null) { mToView = (MultiAutoCompleteTextView) toParent.findViewById(R.id.address_field); ((TextView) toParent.findViewById(R.id.label)) .setText(R.string.message_compose_to_hint); ViewGroup ccParent, bccParent; ccParent = (ViewGroup) findViewById(R.id.cc_content); mCcView = (MultiAutoCompleteTextView) ccParent.findViewById(R.id.address_field); ((TextView) ccParent.findViewById(R.id.label)) .setText(R.string.message_compose_cc_hint); bccParent = (ViewGroup) findViewById(R.id.bcc_content); mBccView = (MultiAutoCompleteTextView) bccParent.findViewById(R.id.address_field); ((TextView) bccParent.findViewById(R.id.label)) .setText(R.string.message_compose_bcc_hint); } else { mToView = UiUtilities.getView(this, R.id.to); mCcView = UiUtilities.getView(this, R.id.cc); mBccView = UiUtilities.getView(this, R.id.bcc); // add hints only when no labels exist if (UiUtilities.getViewOrNull(this, R.id.to_label) == null) { mToView.setHint(R.string.message_compose_to_hint); mCcView.setHint(R.string.message_compose_cc_hint); mBccView.setHint(R.string.message_compose_bcc_hint); } } mFromView = UiUtilities.getView(this, R.id.from); mCcBccContainer = UiUtilities.getView(this, R.id.cc_bcc_container); mSubjectView = UiUtilities.getView(this, R.id.subject); mMessageContentView = UiUtilities.getView(this, R.id.message_content); mAttachmentContentView = UiUtilities.getView(this, R.id.attachments); mAttachmentContainer = UiUtilities.getView(this, R.id.attachment_container); mQuotedTextBar = UiUtilities.getView(this, R.id.quoted_text_bar); mIncludeQuotedTextCheckBox = UiUtilities.getView(this, R.id.include_quoted_text); mQuotedText = UiUtilities.getView(this, R.id.quoted_text); InputFilter[] recipientFilters = new InputFilter[] { RECIPIENT_FILTER }; // NOTE: assumes no other filters are set mToView.setFilters(recipientFilters); mCcView.setFilters(recipientFilters); mBccView.setFilters(recipientFilters); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ mQuotedTextBar.setVisibility(View.GONE); setIncludeQuotedText(false, false); mIncludeQuotedTextCheckBox.setOnClickListener(this); EmailAddressValidator addressValidator = new EmailAddressValidator(); setupAddressAdapters(); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(addressValidator); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(addressValidator); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(addressValidator); final View addCcBccView = UiUtilities.getViewOrNull(this, R.id.add_cc_bcc); if (addCcBccView != null) { // Tablet view. addCcBccView.setOnClickListener(this); } final View addAttachmentView = UiUtilities.getViewOrNull(this, R.id.add_attachment); if (addAttachmentView != null) { // Tablet view. addAttachmentView.setOnClickListener(this); } setFocusShifter(R.id.to_label, R.id.to); setFocusShifter(R.id.cc_label, R.id.cc); setFocusShifter(R.id.bcc_label, R.id.bcc); setFocusShifter(R.id.subject_label, R.id.subject); setFocusShifter(R.id.tap_trap, R.id.message_content); mMessageContentView.setOnFocusChangeListener(this); updateAttachmentContainer(); mToView.requestFocus(); }
private void initViews() { ViewGroup toParent = UiUtilities.getViewOrNull(this, R.id.to_content); if (toParent != null) { mToView = (MultiAutoCompleteTextView) toParent.findViewById(R.id.to_address_field); ((TextView) toParent.findViewById(R.id.label)) .setText(R.string.message_compose_to_hint); ViewGroup ccParent, bccParent; ccParent = (ViewGroup) findViewById(R.id.cc_content); mCcView = (MultiAutoCompleteTextView) ccParent.findViewById(R.id.cc_address_field); ((TextView) ccParent.findViewById(R.id.label)) .setText(R.string.message_compose_cc_hint); bccParent = (ViewGroup) findViewById(R.id.bcc_content); mBccView = (MultiAutoCompleteTextView) bccParent.findViewById(R.id.bcc_address_field); ((TextView) bccParent.findViewById(R.id.label)) .setText(R.string.message_compose_bcc_hint); } else { mToView = UiUtilities.getView(this, R.id.to); mCcView = UiUtilities.getView(this, R.id.cc); mBccView = UiUtilities.getView(this, R.id.bcc); // add hints only when no labels exist if (UiUtilities.getViewOrNull(this, R.id.to_label) == null) { mToView.setHint(R.string.message_compose_to_hint); mCcView.setHint(R.string.message_compose_cc_hint); mBccView.setHint(R.string.message_compose_bcc_hint); } } mFromView = UiUtilities.getView(this, R.id.from); mCcBccContainer = UiUtilities.getView(this, R.id.cc_bcc_container); mSubjectView = UiUtilities.getView(this, R.id.subject); mMessageContentView = UiUtilities.getView(this, R.id.message_content); mAttachmentContentView = UiUtilities.getView(this, R.id.attachments); mAttachmentContainer = UiUtilities.getView(this, R.id.attachment_container); mQuotedTextBar = UiUtilities.getView(this, R.id.quoted_text_bar); mIncludeQuotedTextCheckBox = UiUtilities.getView(this, R.id.include_quoted_text); mQuotedText = UiUtilities.getView(this, R.id.quoted_text); InputFilter[] recipientFilters = new InputFilter[] { RECIPIENT_FILTER }; // NOTE: assumes no other filters are set mToView.setFilters(recipientFilters); mCcView.setFilters(recipientFilters); mBccView.setFilters(recipientFilters); /* * We set this to invisible by default. Other methods will turn it back on if it's * needed. */ mQuotedTextBar.setVisibility(View.GONE); setIncludeQuotedText(false, false); mIncludeQuotedTextCheckBox.setOnClickListener(this); EmailAddressValidator addressValidator = new EmailAddressValidator(); setupAddressAdapters(); mToView.setTokenizer(new Rfc822Tokenizer()); mToView.setValidator(addressValidator); mCcView.setTokenizer(new Rfc822Tokenizer()); mCcView.setValidator(addressValidator); mBccView.setTokenizer(new Rfc822Tokenizer()); mBccView.setValidator(addressValidator); final View addCcBccView = UiUtilities.getViewOrNull(this, R.id.add_cc_bcc); if (addCcBccView != null) { // Tablet view. addCcBccView.setOnClickListener(this); } final View addAttachmentView = UiUtilities.getViewOrNull(this, R.id.add_attachment); if (addAttachmentView != null) { // Tablet view. addAttachmentView.setOnClickListener(this); } setFocusShifter(R.id.to_label, R.id.to); setFocusShifter(R.id.cc_label, R.id.cc); setFocusShifter(R.id.bcc_label, R.id.bcc); setFocusShifter(R.id.subject_label, R.id.subject); setFocusShifter(R.id.tap_trap, R.id.message_content); mMessageContentView.setOnFocusChangeListener(this); updateAttachmentContainer(); mToView.requestFocus(); }
diff --git a/src/uk/ac/ic/doc/analysis/PhiPlacement.java b/src/uk/ac/ic/doc/analysis/PhiPlacement.java index 63dbc15..5d57721 100644 --- a/src/uk/ac/ic/doc/analysis/PhiPlacement.java +++ b/src/uk/ac/ic/doc/analysis/PhiPlacement.java @@ -1,69 +1,69 @@ package uk.ac.ic.doc.analysis; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Set; import uk.ac.ic.doc.analysis.dominance.DomFront; import uk.ac.ic.doc.analysis.dominance.DomFront.DomInfo; import uk.ac.ic.doc.analysis.dominance.DomMethod; import uk.ac.ic.doc.cfg.model.BasicBlock; import uk.ac.ic.doc.cfg.model.Cfg; public class PhiPlacement { private GlobalsAndDefsFinder finder; private Map<BasicBlock, DomInfo> domInfo; private Map<BasicBlock, Set<String>> phis = new HashMap<BasicBlock, Set<String>>(); public PhiPlacement(Cfg graph) throws Exception { finder = new GlobalsAndDefsFinder(graph); domInfo = new DomFront(new DomMethod(graph)).run(); for (String name : finder.globals()) { Collection<BasicBlock> definingLocations = finder .definingLocations(name); // Variables can be global (used in multiple blocks) yet never // defined. This most likely indicates a true global in the Python // sense of the word or a function name that has been imported (also // a Python global really). if (definingLocations == null) continue; Queue<BasicBlock> worklist = new LinkedList<BasicBlock>( definingLocations); Set<BasicBlock> doneList = new HashSet<BasicBlock>(); while (!worklist.isEmpty()) { BasicBlock workItem = worklist.remove(); doneList.add(workItem); for (BasicBlock frontierBlock : domInfo.get(workItem).dominanceFrontiers) { Set<String> phiTargetsAtLocation = phis.get(frontierBlock); if (phiTargetsAtLocation == null) { phiTargetsAtLocation = new HashSet<String>(); phis.put(frontierBlock, phiTargetsAtLocation); } phiTargetsAtLocation.add(name); - if (doneList.contains(frontierBlock)) + if (!doneList.contains(frontierBlock)) worklist.add(frontierBlock); } } } } public Iterable<String> phiTargets(BasicBlock location) { return phis.get(location); } public Map<BasicBlock, DomInfo> getDomInfo() { return domInfo; } }
true
true
public PhiPlacement(Cfg graph) throws Exception { finder = new GlobalsAndDefsFinder(graph); domInfo = new DomFront(new DomMethod(graph)).run(); for (String name : finder.globals()) { Collection<BasicBlock> definingLocations = finder .definingLocations(name); // Variables can be global (used in multiple blocks) yet never // defined. This most likely indicates a true global in the Python // sense of the word or a function name that has been imported (also // a Python global really). if (definingLocations == null) continue; Queue<BasicBlock> worklist = new LinkedList<BasicBlock>( definingLocations); Set<BasicBlock> doneList = new HashSet<BasicBlock>(); while (!worklist.isEmpty()) { BasicBlock workItem = worklist.remove(); doneList.add(workItem); for (BasicBlock frontierBlock : domInfo.get(workItem).dominanceFrontiers) { Set<String> phiTargetsAtLocation = phis.get(frontierBlock); if (phiTargetsAtLocation == null) { phiTargetsAtLocation = new HashSet<String>(); phis.put(frontierBlock, phiTargetsAtLocation); } phiTargetsAtLocation.add(name); if (doneList.contains(frontierBlock)) worklist.add(frontierBlock); } } } }
public PhiPlacement(Cfg graph) throws Exception { finder = new GlobalsAndDefsFinder(graph); domInfo = new DomFront(new DomMethod(graph)).run(); for (String name : finder.globals()) { Collection<BasicBlock> definingLocations = finder .definingLocations(name); // Variables can be global (used in multiple blocks) yet never // defined. This most likely indicates a true global in the Python // sense of the word or a function name that has been imported (also // a Python global really). if (definingLocations == null) continue; Queue<BasicBlock> worklist = new LinkedList<BasicBlock>( definingLocations); Set<BasicBlock> doneList = new HashSet<BasicBlock>(); while (!worklist.isEmpty()) { BasicBlock workItem = worklist.remove(); doneList.add(workItem); for (BasicBlock frontierBlock : domInfo.get(workItem).dominanceFrontiers) { Set<String> phiTargetsAtLocation = phis.get(frontierBlock); if (phiTargetsAtLocation == null) { phiTargetsAtLocation = new HashSet<String>(); phis.put(frontierBlock, phiTargetsAtLocation); } phiTargetsAtLocation.add(name); if (!doneList.contains(frontierBlock)) worklist.add(frontierBlock); } } } }
diff --git a/src-pos/com/openbravo/pos/printer/escpos/UnicodeTranslatorStar.java b/src-pos/com/openbravo/pos/printer/escpos/UnicodeTranslatorStar.java index 431c5b6..2a1c0b3 100644 --- a/src-pos/com/openbravo/pos/printer/escpos/UnicodeTranslatorStar.java +++ b/src-pos/com/openbravo/pos/printer/escpos/UnicodeTranslatorStar.java @@ -1,177 +1,177 @@ // Openbravo POS is a point of sales application designed for touch screens. // Copyright (C) 2007-2009 Openbravo, S.L. // http://www.openbravo.com/product/pos // // This file is part of Openbravo POS. // // Openbravo POS is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Openbravo POS is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Openbravo POS. If not, see <http://www.gnu.org/licenses/>. package com.openbravo.pos.printer.escpos; public class UnicodeTranslatorStar extends UnicodeTranslator { /** Creates a UnicodeTranslatorStar instance of UnicodeTranslatorInt */ public UnicodeTranslatorStar() { } public byte[] getCodeTable() { return new byte[] {0x1B, 0x1D, 0x74, 0x01}; // Select code page 437 } public byte transChar(char sChar) { if ((sChar >= 0x0000) && (sChar < 0x0080)) { return (byte) sChar; } else { switch (sChar) { case '\u00c1': return 0x41; // A acute case '\u00c9': return 0x45; // E acute case '\u00cd': return 0x49; // I acute case '\u00d3': return 0x4F; // O acute case '\u00da': return 0x55; // U acute -// case '\u0000': return -0x80; // 0x80 : + case '\u00C7': return -0x80; // 0x80 : C cedilla case '\u00FC': return -0x7F; // 0x81 : u dieresis case '\u00E9': return -0x7E; // 0x82 : e acute // case '\u0000': return -0x7D; // 0x83 : -// case '\u0000': return -0x7C; // 0x84 : + case '\u00E4': return -0x7C; // 0x84 : a dieresis // case '\u0000': return -0x7B; // 0x85 : -// case '\u0000': return -0x7A; // 0x86 : -// case '\u0000': return -0x79; // 0x87 : + case '\u00E5': return -0x7A; // 0x86 : a circle + case '\u00E7': return -0x79; // 0x87 : c cedilla // case '\u0000': return -0x78; // 0x88 : // case '\u0000': return -0x77; // 0x89 : // case '\u0000': return -0x76; // 0x8A : // case '\u0000': return -0x75; // 0x8B : -// case '\u0000': return -0x74; // 0x8C : +// case '\u0000': return -0x74; // 0x8C :dieresis // case '\u0000': return -0x73; // 0x8D : -// case '\u0000': return -0x72; // 0x8E : -// case '\u0000': return -0x71; // 0x8F : + case '\u00C4': return -0x72; // 0x8E : A dieresis + case '\u00C5': return -0x71; // 0x8F : A circle // case '\u0000': return -0x70; // 0x90 : // case '\u0000': return -0x6F; // 0x91 : // case '\u0000': return -0x6E; // 0x92 : // case '\u0000': return -0x6D; // 0x93 : -// case '\u0000': return -0x6C; // 0x94 : + case '\u00F6': return -0x6C; // 0x94 : o dieresis // case '\u0000': return -0x6B; // 0x95 : // case '\u0000': return -0x6A; // 0x96 : // case '\u0000': return -0x69; // 0x97 : // case '\u0000': return -0x68; // 0x98 : -// case '\u0000': return -0x67; // 0x99 : + case '\u00D6': return -0x67; // 0x99 : O dieresis case '\u00DC': return -0x66; // 0x9A : U dieresesis // case '\u0000': return -0x65; // 0x9B : case '\u00A3': return -0x64; // 0x9C : Pound currency case '\u00A5': return -0x63; // 0x9D : Yen currency // case '\u0000': return -0x62; // 0x9E : // case '\u0000': return -0x61; // 0x9F : case '\u00E1': return -0x60; // 0xA0 : a acute case '\u00ED': return -0x5F; // 0xA1 : i acute case '\u00F3': return -0x5E; // 0xA2 : o acute case '\u00FA': return -0x5D; // 0xA3 : u acute case '\u00F1': return -0x5C; // 0xA4 : n tilde case '\u00D1': return -0x5B; // 0xA5 : N tilde // case '\u0000': return -0x5A; // 0xA6 : // case '\u0000': return -0x59; // 0xA7 : case '\u00BF': return -0x58; // 0xA8 : open ? // case '\u0000': return -0x57; // 0xA9 : // case '\u0000': return -0x56; // 0xAA : // case '\u0000': return -0x55; // 0xAB : // case '\u0000': return -0x54; // 0xAC : case '\u00A1': return -0x53; // 0xAD : open ! // case '\u0000': return -0x52; // 0xAE : // case '\u0000': return -0x51; // 0xAF : // case '\u0000': return -0x50; // 0xB0 : // case '\u0000': return -0x4F; // 0xB1 : // case '\u0000': return -0x4E; // 0xB2 : // case '\u0000': return -0x4D; // 0xB3 : // case '\u0000': return -0x4C; // 0xB4 : // case '\u0000': return -0x4B; // 0xB5 : // case '\u0000': return -0x4A; // 0xB6 : // case '\u0000': return -0x49; // 0xB7 : // case '\u0000': return -0x48; // 0xB8 : // case '\u0000': return -0x47; // 0xB9 : // case '\u0000': return -0x46; // 0xBA : // case '\u0000': return -0x45; // 0xBB : // case '\u0000': return -0x44; // 0xBC : // case '\u0000': return -0x43; // 0xBD : // case '\u0000': return -0x42; // 0xBE : // case '\u0000': return -0x41; // 0xBF : // case '\u0000': return -0x40; // 0xC0 : // case '\u0000': return -0x3F; // 0xC1 : // case '\u0000': return -0x3E; // 0xC2 : // case '\u0000': return -0x3D; // 0xC3 : // case '\u0000': return -0x3C; // 0xC4 : // case '\u0000': return -0x3B; // 0xC5 : // case '\u0000': return -0x3A; // 0xC6 : // case '\u0000': return -0x39; // 0xC7 : // case '\u0000': return -0x38; // 0xC8 : // case '\u0000': return -0x37; // 0xC9 : // case '\u0000': return -0x36; // 0xCA : // case '\u0000': return -0x35; // 0xCB : // case '\u0000': return -0x34; // 0xCC : // case '\u0000': return -0x33; // 0xCD : // case '\u0000': return -0x32; // 0xCE : // case '\u0000': return -0x31; // 0xCF : // case '\u0000': return -0x30; // 0xD0 : // case '\u0000': return -0x2F; // 0xD1 : // case '\u0000': return -0x2E; // 0xD2 : // case '\u0000': return -0x2D; // 0xD3 : // case '\u0000': return -0x2C; // 0xD4 : // case '\u0000': return -0x2B; // 0xD5 : // case '\u0000': return -0x2A; // 0xD6 : // case '\u0000': return -0x29; // 0xD7 : // case '\u0000': return -0x28; // 0xD8 : // case '\u0000': return -0x27; // 0xD9 : // case '\u0000': return -0x26; // 0xDA : // case '\u0000': return -0x25; // 0xDB : // case '\u0000': return -0x24; // 0xDC : // case '\u0000': return -0x23; // 0xDD : // case '\u0000': return -0x22; // 0xDE : // case '\u0000': return -0x21; // 0xDF : // case '\u0000': return -0x20; // 0xE0 : // case '\u0000': return -0x2F; // 0xE1 : // case '\u0000': return -0x1E; // 0xE2 : // case '\u0000': return -0x1D; // 0xE3 : // case '\u0000': return -0x1C; // 0xE4 : // case '\u0000': return -0x1B; // 0xE5 : // case '\u0000': return -0x1A; // 0xE6 : // case '\u0000': return -0x19; // 0xE7 : // case '\u0000': return -0x18; // 0xE8 : // case '\u0000': return -0x17; // 0xE9 : // case '\u0000': return -0x16; // 0xEA : // case '\u0000': return -0x15; // 0xEB : // case '\u0000': return -0x14; // 0xEC : // case '\u0000': return -0x13; // 0xED : case '\u20AC': return -0x12; // 0xEE : euro sign // case '\u0000': return -0x11; // 0xEF : // case '\u0000': return -0x10; // 0xF0 : // case '\u0000': return -0x0F; // 0xF1 : // case '\u0000': return -0x0E; // 0xF2 : // case '\u0000': return -0x0D; // 0xF3 : // case '\u0000': return -0x0C; // 0xF4 : // case '\u0000': return -0x0B; // 0xF5 : // case '\u0000': return -0x0A; // 0xF6 : // case '\u0000': return -0x09; // 0xF7 : // case '\u0000': return -0x08; // 0xF8 : // case '\u0000': return -0x07; // 0xF9 : // case '\u0000': return -0x06; // 0xFA : // case '\u0000': return -0x05; // 0xFB : // case '\u0000': return -0x04; // 0xFC : // case '\u0000': return -0x03; // 0xFD : // case '\u0000': return -0x02; // 0xFE : // case '\u0000': return -0x01; // 0xFF : default: return 0x3F; // ? Not valid character. } } } }
false
true
public byte transChar(char sChar) { if ((sChar >= 0x0000) && (sChar < 0x0080)) { return (byte) sChar; } else { switch (sChar) { case '\u00c1': return 0x41; // A acute case '\u00c9': return 0x45; // E acute case '\u00cd': return 0x49; // I acute case '\u00d3': return 0x4F; // O acute case '\u00da': return 0x55; // U acute // case '\u0000': return -0x80; // 0x80 : case '\u00FC': return -0x7F; // 0x81 : u dieresis case '\u00E9': return -0x7E; // 0x82 : e acute // case '\u0000': return -0x7D; // 0x83 : // case '\u0000': return -0x7C; // 0x84 : // case '\u0000': return -0x7B; // 0x85 : // case '\u0000': return -0x7A; // 0x86 : // case '\u0000': return -0x79; // 0x87 : // case '\u0000': return -0x78; // 0x88 : // case '\u0000': return -0x77; // 0x89 : // case '\u0000': return -0x76; // 0x8A : // case '\u0000': return -0x75; // 0x8B : // case '\u0000': return -0x74; // 0x8C : // case '\u0000': return -0x73; // 0x8D : // case '\u0000': return -0x72; // 0x8E : // case '\u0000': return -0x71; // 0x8F : // case '\u0000': return -0x70; // 0x90 : // case '\u0000': return -0x6F; // 0x91 : // case '\u0000': return -0x6E; // 0x92 : // case '\u0000': return -0x6D; // 0x93 : // case '\u0000': return -0x6C; // 0x94 : // case '\u0000': return -0x6B; // 0x95 : // case '\u0000': return -0x6A; // 0x96 : // case '\u0000': return -0x69; // 0x97 : // case '\u0000': return -0x68; // 0x98 : // case '\u0000': return -0x67; // 0x99 : case '\u00DC': return -0x66; // 0x9A : U dieresesis // case '\u0000': return -0x65; // 0x9B : case '\u00A3': return -0x64; // 0x9C : Pound currency case '\u00A5': return -0x63; // 0x9D : Yen currency // case '\u0000': return -0x62; // 0x9E : // case '\u0000': return -0x61; // 0x9F : case '\u00E1': return -0x60; // 0xA0 : a acute case '\u00ED': return -0x5F; // 0xA1 : i acute case '\u00F3': return -0x5E; // 0xA2 : o acute case '\u00FA': return -0x5D; // 0xA3 : u acute case '\u00F1': return -0x5C; // 0xA4 : n tilde case '\u00D1': return -0x5B; // 0xA5 : N tilde // case '\u0000': return -0x5A; // 0xA6 : // case '\u0000': return -0x59; // 0xA7 : case '\u00BF': return -0x58; // 0xA8 : open ? // case '\u0000': return -0x57; // 0xA9 : // case '\u0000': return -0x56; // 0xAA : // case '\u0000': return -0x55; // 0xAB : // case '\u0000': return -0x54; // 0xAC : case '\u00A1': return -0x53; // 0xAD : open ! // case '\u0000': return -0x52; // 0xAE : // case '\u0000': return -0x51; // 0xAF : // case '\u0000': return -0x50; // 0xB0 : // case '\u0000': return -0x4F; // 0xB1 : // case '\u0000': return -0x4E; // 0xB2 : // case '\u0000': return -0x4D; // 0xB3 : // case '\u0000': return -0x4C; // 0xB4 : // case '\u0000': return -0x4B; // 0xB5 : // case '\u0000': return -0x4A; // 0xB6 : // case '\u0000': return -0x49; // 0xB7 : // case '\u0000': return -0x48; // 0xB8 : // case '\u0000': return -0x47; // 0xB9 : // case '\u0000': return -0x46; // 0xBA : // case '\u0000': return -0x45; // 0xBB : // case '\u0000': return -0x44; // 0xBC : // case '\u0000': return -0x43; // 0xBD : // case '\u0000': return -0x42; // 0xBE : // case '\u0000': return -0x41; // 0xBF : // case '\u0000': return -0x40; // 0xC0 : // case '\u0000': return -0x3F; // 0xC1 : // case '\u0000': return -0x3E; // 0xC2 : // case '\u0000': return -0x3D; // 0xC3 : // case '\u0000': return -0x3C; // 0xC4 : // case '\u0000': return -0x3B; // 0xC5 : // case '\u0000': return -0x3A; // 0xC6 : // case '\u0000': return -0x39; // 0xC7 : // case '\u0000': return -0x38; // 0xC8 : // case '\u0000': return -0x37; // 0xC9 : // case '\u0000': return -0x36; // 0xCA : // case '\u0000': return -0x35; // 0xCB : // case '\u0000': return -0x34; // 0xCC : // case '\u0000': return -0x33; // 0xCD : // case '\u0000': return -0x32; // 0xCE : // case '\u0000': return -0x31; // 0xCF : // case '\u0000': return -0x30; // 0xD0 : // case '\u0000': return -0x2F; // 0xD1 : // case '\u0000': return -0x2E; // 0xD2 : // case '\u0000': return -0x2D; // 0xD3 : // case '\u0000': return -0x2C; // 0xD4 : // case '\u0000': return -0x2B; // 0xD5 : // case '\u0000': return -0x2A; // 0xD6 : // case '\u0000': return -0x29; // 0xD7 : // case '\u0000': return -0x28; // 0xD8 : // case '\u0000': return -0x27; // 0xD9 : // case '\u0000': return -0x26; // 0xDA : // case '\u0000': return -0x25; // 0xDB : // case '\u0000': return -0x24; // 0xDC : // case '\u0000': return -0x23; // 0xDD : // case '\u0000': return -0x22; // 0xDE : // case '\u0000': return -0x21; // 0xDF : // case '\u0000': return -0x20; // 0xE0 : // case '\u0000': return -0x2F; // 0xE1 : // case '\u0000': return -0x1E; // 0xE2 : // case '\u0000': return -0x1D; // 0xE3 : // case '\u0000': return -0x1C; // 0xE4 : // case '\u0000': return -0x1B; // 0xE5 : // case '\u0000': return -0x1A; // 0xE6 : // case '\u0000': return -0x19; // 0xE7 : // case '\u0000': return -0x18; // 0xE8 : // case '\u0000': return -0x17; // 0xE9 : // case '\u0000': return -0x16; // 0xEA : // case '\u0000': return -0x15; // 0xEB : // case '\u0000': return -0x14; // 0xEC : // case '\u0000': return -0x13; // 0xED : case '\u20AC': return -0x12; // 0xEE : euro sign // case '\u0000': return -0x11; // 0xEF : // case '\u0000': return -0x10; // 0xF0 : // case '\u0000': return -0x0F; // 0xF1 : // case '\u0000': return -0x0E; // 0xF2 : // case '\u0000': return -0x0D; // 0xF3 : // case '\u0000': return -0x0C; // 0xF4 : // case '\u0000': return -0x0B; // 0xF5 : // case '\u0000': return -0x0A; // 0xF6 : // case '\u0000': return -0x09; // 0xF7 : // case '\u0000': return -0x08; // 0xF8 : // case '\u0000': return -0x07; // 0xF9 : // case '\u0000': return -0x06; // 0xFA : // case '\u0000': return -0x05; // 0xFB : // case '\u0000': return -0x04; // 0xFC : // case '\u0000': return -0x03; // 0xFD : // case '\u0000': return -0x02; // 0xFE : // case '\u0000': return -0x01; // 0xFF : default: return 0x3F; // ? Not valid character. } } }
public byte transChar(char sChar) { if ((sChar >= 0x0000) && (sChar < 0x0080)) { return (byte) sChar; } else { switch (sChar) { case '\u00c1': return 0x41; // A acute case '\u00c9': return 0x45; // E acute case '\u00cd': return 0x49; // I acute case '\u00d3': return 0x4F; // O acute case '\u00da': return 0x55; // U acute case '\u00C7': return -0x80; // 0x80 : C cedilla case '\u00FC': return -0x7F; // 0x81 : u dieresis case '\u00E9': return -0x7E; // 0x82 : e acute // case '\u0000': return -0x7D; // 0x83 : case '\u00E4': return -0x7C; // 0x84 : a dieresis // case '\u0000': return -0x7B; // 0x85 : case '\u00E5': return -0x7A; // 0x86 : a circle case '\u00E7': return -0x79; // 0x87 : c cedilla // case '\u0000': return -0x78; // 0x88 : // case '\u0000': return -0x77; // 0x89 : // case '\u0000': return -0x76; // 0x8A : // case '\u0000': return -0x75; // 0x8B : // case '\u0000': return -0x74; // 0x8C :dieresis // case '\u0000': return -0x73; // 0x8D : case '\u00C4': return -0x72; // 0x8E : A dieresis case '\u00C5': return -0x71; // 0x8F : A circle // case '\u0000': return -0x70; // 0x90 : // case '\u0000': return -0x6F; // 0x91 : // case '\u0000': return -0x6E; // 0x92 : // case '\u0000': return -0x6D; // 0x93 : case '\u00F6': return -0x6C; // 0x94 : o dieresis // case '\u0000': return -0x6B; // 0x95 : // case '\u0000': return -0x6A; // 0x96 : // case '\u0000': return -0x69; // 0x97 : // case '\u0000': return -0x68; // 0x98 : case '\u00D6': return -0x67; // 0x99 : O dieresis case '\u00DC': return -0x66; // 0x9A : U dieresesis // case '\u0000': return -0x65; // 0x9B : case '\u00A3': return -0x64; // 0x9C : Pound currency case '\u00A5': return -0x63; // 0x9D : Yen currency // case '\u0000': return -0x62; // 0x9E : // case '\u0000': return -0x61; // 0x9F : case '\u00E1': return -0x60; // 0xA0 : a acute case '\u00ED': return -0x5F; // 0xA1 : i acute case '\u00F3': return -0x5E; // 0xA2 : o acute case '\u00FA': return -0x5D; // 0xA3 : u acute case '\u00F1': return -0x5C; // 0xA4 : n tilde case '\u00D1': return -0x5B; // 0xA5 : N tilde // case '\u0000': return -0x5A; // 0xA6 : // case '\u0000': return -0x59; // 0xA7 : case '\u00BF': return -0x58; // 0xA8 : open ? // case '\u0000': return -0x57; // 0xA9 : // case '\u0000': return -0x56; // 0xAA : // case '\u0000': return -0x55; // 0xAB : // case '\u0000': return -0x54; // 0xAC : case '\u00A1': return -0x53; // 0xAD : open ! // case '\u0000': return -0x52; // 0xAE : // case '\u0000': return -0x51; // 0xAF : // case '\u0000': return -0x50; // 0xB0 : // case '\u0000': return -0x4F; // 0xB1 : // case '\u0000': return -0x4E; // 0xB2 : // case '\u0000': return -0x4D; // 0xB3 : // case '\u0000': return -0x4C; // 0xB4 : // case '\u0000': return -0x4B; // 0xB5 : // case '\u0000': return -0x4A; // 0xB6 : // case '\u0000': return -0x49; // 0xB7 : // case '\u0000': return -0x48; // 0xB8 : // case '\u0000': return -0x47; // 0xB9 : // case '\u0000': return -0x46; // 0xBA : // case '\u0000': return -0x45; // 0xBB : // case '\u0000': return -0x44; // 0xBC : // case '\u0000': return -0x43; // 0xBD : // case '\u0000': return -0x42; // 0xBE : // case '\u0000': return -0x41; // 0xBF : // case '\u0000': return -0x40; // 0xC0 : // case '\u0000': return -0x3F; // 0xC1 : // case '\u0000': return -0x3E; // 0xC2 : // case '\u0000': return -0x3D; // 0xC3 : // case '\u0000': return -0x3C; // 0xC4 : // case '\u0000': return -0x3B; // 0xC5 : // case '\u0000': return -0x3A; // 0xC6 : // case '\u0000': return -0x39; // 0xC7 : // case '\u0000': return -0x38; // 0xC8 : // case '\u0000': return -0x37; // 0xC9 : // case '\u0000': return -0x36; // 0xCA : // case '\u0000': return -0x35; // 0xCB : // case '\u0000': return -0x34; // 0xCC : // case '\u0000': return -0x33; // 0xCD : // case '\u0000': return -0x32; // 0xCE : // case '\u0000': return -0x31; // 0xCF : // case '\u0000': return -0x30; // 0xD0 : // case '\u0000': return -0x2F; // 0xD1 : // case '\u0000': return -0x2E; // 0xD2 : // case '\u0000': return -0x2D; // 0xD3 : // case '\u0000': return -0x2C; // 0xD4 : // case '\u0000': return -0x2B; // 0xD5 : // case '\u0000': return -0x2A; // 0xD6 : // case '\u0000': return -0x29; // 0xD7 : // case '\u0000': return -0x28; // 0xD8 : // case '\u0000': return -0x27; // 0xD9 : // case '\u0000': return -0x26; // 0xDA : // case '\u0000': return -0x25; // 0xDB : // case '\u0000': return -0x24; // 0xDC : // case '\u0000': return -0x23; // 0xDD : // case '\u0000': return -0x22; // 0xDE : // case '\u0000': return -0x21; // 0xDF : // case '\u0000': return -0x20; // 0xE0 : // case '\u0000': return -0x2F; // 0xE1 : // case '\u0000': return -0x1E; // 0xE2 : // case '\u0000': return -0x1D; // 0xE3 : // case '\u0000': return -0x1C; // 0xE4 : // case '\u0000': return -0x1B; // 0xE5 : // case '\u0000': return -0x1A; // 0xE6 : // case '\u0000': return -0x19; // 0xE7 : // case '\u0000': return -0x18; // 0xE8 : // case '\u0000': return -0x17; // 0xE9 : // case '\u0000': return -0x16; // 0xEA : // case '\u0000': return -0x15; // 0xEB : // case '\u0000': return -0x14; // 0xEC : // case '\u0000': return -0x13; // 0xED : case '\u20AC': return -0x12; // 0xEE : euro sign // case '\u0000': return -0x11; // 0xEF : // case '\u0000': return -0x10; // 0xF0 : // case '\u0000': return -0x0F; // 0xF1 : // case '\u0000': return -0x0E; // 0xF2 : // case '\u0000': return -0x0D; // 0xF3 : // case '\u0000': return -0x0C; // 0xF4 : // case '\u0000': return -0x0B; // 0xF5 : // case '\u0000': return -0x0A; // 0xF6 : // case '\u0000': return -0x09; // 0xF7 : // case '\u0000': return -0x08; // 0xF8 : // case '\u0000': return -0x07; // 0xF9 : // case '\u0000': return -0x06; // 0xFA : // case '\u0000': return -0x05; // 0xFB : // case '\u0000': return -0x04; // 0xFC : // case '\u0000': return -0x03; // 0xFD : // case '\u0000': return -0x02; // 0xFE : // case '\u0000': return -0x01; // 0xFF : default: return 0x3F; // ? Not valid character. } } }
diff --git a/GuerraVaixellsMylyn/src/Tauler.java b/GuerraVaixellsMylyn/src/Tauler.java index af3f560..0e15fdd 100644 --- a/GuerraVaixellsMylyn/src/Tauler.java +++ b/GuerraVaixellsMylyn/src/Tauler.java @@ -1,64 +1,64 @@ public class Tauler { int alc, ampl; Casella casella [][]; public Tauler(int amplada, int alcada) { alc=alcada; ampl=amplada; casella = new Casella[alc][ampl]; FerTotAigua(); } public void FerTotAigua() { for(int i=0;i<alc;++i) for(int j=0;j<ampl;++j) casella[i][j]=Casella.AIGUA; } public boolean ColocarVaixell(int y, int x, Vaixell v) { int incrX=0 ; int incrY=0; - switch (v.getOrientacio() ) + switch (v.getOrientacio() ) { case V: incrX=0; incrY=1; break; case H: incrX=1; incrY=0; break; } // Copiem el vaixell int xPointer=x; int yPointer=y; for(int i=0;i<v.getMida();++i) { casella[yPointer][xPointer]=Casella.VAIXELL; yPointer+=incrY; xPointer+=incrX; } return true; } public Casella Tret(int x, int y) { } }
true
true
public boolean ColocarVaixell(int y, int x, Vaixell v) { int incrX=0 ; int incrY=0; switch (v.getOrientacio() ) { case V: incrX=0; incrY=1; break; case H: incrX=1; incrY=0; break; } // Copiem el vaixell int xPointer=x; int yPointer=y; for(int i=0;i<v.getMida();++i) { casella[yPointer][xPointer]=Casella.VAIXELL; yPointer+=incrY; xPointer+=incrX; } return true; }
public boolean ColocarVaixell(int y, int x, Vaixell v) { int incrX=0 ; int incrY=0; switch (v.getOrientacio() ) { case V: incrX=0; incrY=1; break; case H: incrX=1; incrY=0; break; } // Copiem el vaixell int xPointer=x; int yPointer=y; for(int i=0;i<v.getMida();++i) { casella[yPointer][xPointer]=Casella.VAIXELL; yPointer+=incrY; xPointer+=incrX; } return true; }
diff --git a/atlas-web/src/test/java/uk/ac/ebi/gxa/web/AtlasPlotterAssayFactorValuesTest.java b/atlas-web/src/test/java/uk/ac/ebi/gxa/web/AtlasPlotterAssayFactorValuesTest.java index 328bbd34d..b45792465 100644 --- a/atlas-web/src/test/java/uk/ac/ebi/gxa/web/AtlasPlotterAssayFactorValuesTest.java +++ b/atlas-web/src/test/java/uk/ac/ebi/gxa/web/AtlasPlotterAssayFactorValuesTest.java @@ -1,66 +1,66 @@ /* * Copyright 2008-2011 Microarray Informatics Team, EMBL-European Bioinformatics Institute * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * For further details of the Gene Expression Atlas project, including source code, * downloads and documentation, please see: * * http://gxa.github.com/gxa */ package uk.ac.ebi.gxa.web; import org.junit.Test; import uk.ac.ebi.gxa.web.AtlasPlotter.AssayFactorValues; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; /** * @author Olga Melnichuk */ public class AtlasPlotterAssayFactorValuesTest { @Test public void testAssayFactorValues() { String[] factorValues = new String[]{"value1", "value2", "value1", "value2", "value3"}; - List<Float> expressions = Arrays.asList(1.0f, 2.0f, 1.0f, 2.0f, 3.0f, 0.0f); + List<Float> expressions = Arrays.asList(1.0f, 2.0f, 1.0f, 2.0f, 3.0f); assertEquals(factorValues.length, expressions.size()); AssayFactorValues afv = new AssayFactorValues(factorValues); assertContainsAll(afv.getUniqueValues(), "value1", "value2", "value3"); assertContainsAll(afv.getAssayExpressionsFor("value1", expressions), 1.0f, 1.0f); assertContainsAll(afv.getAssayExpressionsFor("value2", expressions), 2.0f, 2.0f); assertContainsAll(afv.getAssayExpressionsFor("value3", expressions), 3.0f); try{ afv.getAssayExpressionsFor("value1", Collections.<Float>emptyList()); fail(); }catch(IllegalArgumentException e) { //OK } } private <T> void assertContainsAll(Collection<T> collection, T... array) { assertEquals(collection.size(), array.length); for(T s : array) { assertTrue(collection.contains(s)); } } }
true
true
public void testAssayFactorValues() { String[] factorValues = new String[]{"value1", "value2", "value1", "value2", "value3"}; List<Float> expressions = Arrays.asList(1.0f, 2.0f, 1.0f, 2.0f, 3.0f, 0.0f); assertEquals(factorValues.length, expressions.size()); AssayFactorValues afv = new AssayFactorValues(factorValues); assertContainsAll(afv.getUniqueValues(), "value1", "value2", "value3"); assertContainsAll(afv.getAssayExpressionsFor("value1", expressions), 1.0f, 1.0f); assertContainsAll(afv.getAssayExpressionsFor("value2", expressions), 2.0f, 2.0f); assertContainsAll(afv.getAssayExpressionsFor("value3", expressions), 3.0f); try{ afv.getAssayExpressionsFor("value1", Collections.<Float>emptyList()); fail(); }catch(IllegalArgumentException e) { //OK } }
public void testAssayFactorValues() { String[] factorValues = new String[]{"value1", "value2", "value1", "value2", "value3"}; List<Float> expressions = Arrays.asList(1.0f, 2.0f, 1.0f, 2.0f, 3.0f); assertEquals(factorValues.length, expressions.size()); AssayFactorValues afv = new AssayFactorValues(factorValues); assertContainsAll(afv.getUniqueValues(), "value1", "value2", "value3"); assertContainsAll(afv.getAssayExpressionsFor("value1", expressions), 1.0f, 1.0f); assertContainsAll(afv.getAssayExpressionsFor("value2", expressions), 2.0f, 2.0f); assertContainsAll(afv.getAssayExpressionsFor("value3", expressions), 3.0f); try{ afv.getAssayExpressionsFor("value1", Collections.<Float>emptyList()); fail(); }catch(IllegalArgumentException e) { //OK } }
diff --git a/Utilities/java/GetFastaStats.java b/Utilities/java/GetFastaStats.java index 7e17457..cf9aad1 100755 --- a/Utilities/java/GetFastaStats.java +++ b/Utilities/java/GetFastaStats.java @@ -1,400 +1,400 @@ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.io.File; public class GetFastaStats { private static final int MIN_GAP_SIZE = 20; private static int MIN_LENGTH = 2000; private static final int CONTIG_AT_INITIAL_STEP = 1000000; private static final NumberFormat nf = new DecimalFormat("############.#"); private static DecimalFormat largeInts = new DecimalFormat(); private static DecimalFormatSymbols dfs = new DecimalFormatSymbols(); private static final int MAX_DEFAULT_STRING = 4000000; private class ContigAt { ContigAt(long currentBases) { this.count = this.len = 0; this.totalBP = 0; this.goal = currentBases; } public int count; public long totalBP; public int len; public long goal; } String splitLetter = null; boolean baylorFormat = false; boolean oldStyle = false; boolean n50only = false; boolean storeCtgs = false; HashMap<String, Integer> fastaLens = new HashMap<String, Integer>(); HashMap<String, String> ctgs = new HashMap<String, String>(); int totalCount = 0; int genomeSize = 0; public GetFastaStats(boolean useBaylor, boolean old, boolean n50, int size, String split) { baylorFormat = useBaylor; oldStyle = old; n50only = n50; genomeSize = size; splitLetter = split; dfs.setGroupingSeparator(','); largeInts.setDecimalFormatSymbols(dfs); } public void processLens(String inputFile) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(inputFile))); String line = null; StringBuffer counterStr = new StringBuffer(10); int counter = 1; while ((line = bf.readLine()) != null) { String[] splitLine = line.trim().split("\\s+"); try { counterStr.append(counter); fastaLens.put(counterStr.toString(), Integer.parseInt(splitLine[0])); counter++; counterStr.delete(0, counterStr.length()); } catch (NumberFormatException e) { System.err.println("Number format exception " + e.getMessage() + " while parsing line " + line); } } bf.close(); } public void processFile(String inputFile) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader( new FileInputStream(inputFile))); String line = null; StringBuffer fastaSeq = new StringBuffer(MAX_DEFAULT_STRING); String header = ""; while ((line = bf.readLine()) != null) { if (line.startsWith(">")) { String fastaString = fastaSeq.toString().replaceAll("-", ""); fastaString = fastaString.toString().replaceAll("\\.", ""); //String[] split = fastaString.trim().split("N+"); //String[] split = { fastaString.replaceAll("N", "").trim() }; String[] split = { "null" }; if (splitLetter == null) { split[0] = fastaString.trim(); } else { split = fastaString.trim().split(splitLetter + "+"); } //System.err.println("SPLIT one ctg of length " + fastaString.length() + " INTO " + split.length); for (int i = 0; i < split.length; i++) { if (split[i].length() != 0) { fastaLens.put(header + "_" + i,split[i].length()); if (storeCtgs) ctgs.put(header + "_" + i, split[i].toString()); } } //header = line.replace(">contig_", "").trim(); header = line.trim().split("\\s+")[0].replace(">", "").replaceAll("ctg", "").trim(); header = line.trim().split("\\s+")[0].replace(">", "").replaceAll("scf", "").trim(); header = line.trim().split("\\s+")[0].replace(">", "").replaceAll("deg", "").trim(); fastaSeq.setLength(0); // = new StringBuffer(); } else { fastaSeq.append(line); } } String fastaString = fastaSeq.toString().replaceAll("-", ""); fastaString = fastaString.toString().replaceAll("\\.", ""); String[] split = { "null" }; if (splitLetter == null) { split[0] = fastaString.trim(); } else { split = fastaString.trim().split(splitLetter + "+"); } for (int i = 0; i < split.length; i++) { if (fastaSeq.length() != 0) { fastaLens.put(header + "_" + i,split[i].length()); if (storeCtgs) ctgs.put(header + "_" + i, split[i].toString()); } } bf.close(); } public String toString(boolean outputHeader, String title) { StringBuffer st = new StringBuffer(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; long total = 0; int count = 0; int n10 = 0; int n25 = 0; int n50 = 0; int n75 = 0; int n95 = 0; int n10count = 0; int n25count = 0; int n50count = 0; int n75count = 0; int n95count = 0; int totalOverLength = 0; long totalBPOverLength = 0; double eSize = 0; if (fastaLens.size() == 0) { System.err.println("No contigs"); return ""; } for (String s : fastaLens.keySet()) { int len = fastaLens.get(s); if (oldStyle == true && len <= MIN_LENGTH) { continue; } if (len > max) { max = len; } if (len < min) { min = len; } total += len; count++; if (len > MIN_LENGTH) { totalOverLength++; totalBPOverLength += len; } eSize += Math.pow(len, 2); } eSize /= (genomeSize == 0 ? totalBPOverLength : genomeSize); // get the goal contig at X bases (1MBp, 2MBp) ArrayList<ContigAt> contigAtArray = new ArrayList<ContigAt>(); if (baylorFormat == true) { contigAtArray.add(new ContigAt( 1 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt( 2 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt( 4 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt(10 * CONTIG_AT_INITIAL_STEP)); } else { long step = CONTIG_AT_INITIAL_STEP; long currentBases = 0; while (currentBases <= total) { if ((currentBases / step) >= 10) { step *= 10; } currentBases += step; contigAtArray.add(new ContigAt(currentBases)); } } ContigAt[] contigAtVals = contigAtArray.toArray(new ContigAt[0]); Integer[] vals = fastaLens.values().toArray(new Integer[0]); Arrays.sort(vals); long sum = 0; double median = 0; int medianCount = 0; int numberContigsSeen = 0; int currentValPoint = 0; for (int i = vals.length - 1; i >= 0; i--) { if (((int) (count / 2)) == i) { median += vals[i]; medianCount++; } else if (count % 2 == 0 && ((((int) (count / 2)) + 1) == i)) { median += vals[i]; medianCount++; } sum += vals[i]; // calculate the bases at if (currentValPoint < contigAtVals.length && sum >= contigAtVals[currentValPoint].goal && contigAtVals[currentValPoint].count == 0) { contigAtVals[currentValPoint].count = numberContigsSeen; contigAtVals[currentValPoint].len = vals[i]; contigAtVals[currentValPoint].totalBP = sum; currentValPoint++; } // calculate the NXs if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.1 && n10count == 0) { n10 = vals[i]; n10count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.25 && n25count == 0) { n25 = vals[i]; n25count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.5 && n50count == 0) { n50 = vals[i]; n50count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.75 && n75count == 0) { n75 = vals[i]; n75count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.95 && n95count == 0) { n95 = vals[i]; n95count = vals.length - i; } numberContigsSeen++; } if (medianCount != 1 && medianCount != 2) { System.err.println("ERROR INVALID MEDIAN COUNT " + medianCount); System.exit(1); } if (oldStyle == true) { if (n50only == true) { - st.append(title + "\t" + largeInts.format(n50)); + st.append(title + "\t" + n50); } else { st.append("GenomeSize: " + genomeSize + "\n"); st.append("NumReads: " + totalCount + "\n"); st.append("Total units: " + count + "\n"); st.append("BasesInFasta: " + total + "\n"); st.append("Min: " + largeInts.format(min) + "\n"); st.append("Max: " + largeInts.format(max) + "\n"); st.append("N10: " + largeInts.format(n10) + " COUNT: " + n10count + "\n"); st.append("N25: " + largeInts.format(n25) + " COUNT: " + n25count + "\n"); st.append("N50: " + largeInts.format(n50) + " COUNT: " + n50count + "\n"); st.append("N75: " + largeInts.format(n75) + " COUNT: " + n75count + "\n"); st.append("N95: " + largeInts.format(n95) + " COUNT: " + n95count + "\n"); st.append("E-SIZE: " + nf.format(eSize) + "\n"); } } else { if (outputHeader) { st.append("Assembly"); st.append(",Unit Number"); st.append(",Unit Total BP"); st.append(",Number Units > " + MIN_LENGTH); st.append(",Total BP in Units > " + MIN_LENGTH); st.append(",Min"); st.append(",Max"); st.append(",Average"); st.append(",Median"); for (int i = 0; i < contigAtVals.length; i++) { if (contigAtVals[i].count != 0) { st.append(",Unit At " + nf.format(contigAtVals[i].goal) + " Unit Count," + /*"Total Length," + */ " Actual Unit Length" ); } } st.append("\n"); } st.append(title); st.append("," + nf.format(count)); st.append("," + nf.format(total)); st.append("," + nf.format(totalOverLength)); st.append("," + nf.format(totalBPOverLength)); st.append("," + nf.format(min)); st.append("," + nf.format(max)); st.append("," + nf.format((double)total / count)); st.append("," + nf.format((double)median / medianCount)); for (int i = 0; i < contigAtVals.length; i++) { if (contigAtVals[i].count != 0) { st.append("," + contigAtVals[i].count + "," + /*contigAtVals[i].totalBP + "," +*/ contigAtVals[i].len); } } } return st.toString(); } public static void printUsage() { System.err.println("This program computes total bases in fasta sequences, N50, min, and max."); } public static void main(String[] args) throws Exception { if (args.length < 1) { printUsage(); System.exit(1);} /* if (args.length > 1) { f.storeCtgs = true; } */ boolean useBaylorFormat = false; boolean oldStyle = false; boolean n50only = false; int genomeSize = 0; int initialVal = 0; String splitByLetter = null; for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-")) { if (args[i].trim().equalsIgnoreCase("-b")) { useBaylorFormat = true; } else if (args[i].trim().equalsIgnoreCase("-o")) { oldStyle = true; } else if (args[i].trim().equalsIgnoreCase("-n50")) { n50only = true; oldStyle = true; } else if (args[i].trim().equalsIgnoreCase("-genomeSize")) { String param = args[++i]; try { genomeSize = Integer.parseInt(param); } catch (NumberFormatException e) { // assume it's a fasta file to size SizeFasta s = new SizeFasta(); genomeSize = s.sizeSingleRecord(param); } finally { initialVal++; } } else if (args[i].trim().equalsIgnoreCase("-min")) { GetFastaStats.MIN_LENGTH = Integer.parseInt(args[++i]); initialVal++; System.err.println("Set min to be " + GetFastaStats.MIN_LENGTH); } else if (args[i].trim().equalsIgnoreCase("-split")) { splitByLetter = args[++i]; initialVal++; } else { System.err.println("Unknown parameter "+ args[0] + " specified, please specify -b for Baylor-style output."); System.exit(1); } initialVal++; } } for (int i = initialVal; i < args.length; i++) { String assemblyTitle = new File(args[i].trim()).getName(); GetFastaStats f = new GetFastaStats(useBaylorFormat, oldStyle, n50only, genomeSize, splitByLetter); String[] splitLine = args[i].trim().split(","); //System.err.println("The input file is " + args[i] + " AND SPLIT INTO " + splitLine.length); for (int j = 0; j < splitLine.length; j++) { System.err.println("Processing file " + splitLine[j]); if (splitLine[j].endsWith("lens")) { f.processLens(splitLine[j]); } else { f.processFile(splitLine[j]); } } System.out.println(f.toString(i == initialVal, assemblyTitle)); } } }
true
true
public String toString(boolean outputHeader, String title) { StringBuffer st = new StringBuffer(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; long total = 0; int count = 0; int n10 = 0; int n25 = 0; int n50 = 0; int n75 = 0; int n95 = 0; int n10count = 0; int n25count = 0; int n50count = 0; int n75count = 0; int n95count = 0; int totalOverLength = 0; long totalBPOverLength = 0; double eSize = 0; if (fastaLens.size() == 0) { System.err.println("No contigs"); return ""; } for (String s : fastaLens.keySet()) { int len = fastaLens.get(s); if (oldStyle == true && len <= MIN_LENGTH) { continue; } if (len > max) { max = len; } if (len < min) { min = len; } total += len; count++; if (len > MIN_LENGTH) { totalOverLength++; totalBPOverLength += len; } eSize += Math.pow(len, 2); } eSize /= (genomeSize == 0 ? totalBPOverLength : genomeSize); // get the goal contig at X bases (1MBp, 2MBp) ArrayList<ContigAt> contigAtArray = new ArrayList<ContigAt>(); if (baylorFormat == true) { contigAtArray.add(new ContigAt( 1 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt( 2 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt( 4 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt(10 * CONTIG_AT_INITIAL_STEP)); } else { long step = CONTIG_AT_INITIAL_STEP; long currentBases = 0; while (currentBases <= total) { if ((currentBases / step) >= 10) { step *= 10; } currentBases += step; contigAtArray.add(new ContigAt(currentBases)); } } ContigAt[] contigAtVals = contigAtArray.toArray(new ContigAt[0]); Integer[] vals = fastaLens.values().toArray(new Integer[0]); Arrays.sort(vals); long sum = 0; double median = 0; int medianCount = 0; int numberContigsSeen = 0; int currentValPoint = 0; for (int i = vals.length - 1; i >= 0; i--) { if (((int) (count / 2)) == i) { median += vals[i]; medianCount++; } else if (count % 2 == 0 && ((((int) (count / 2)) + 1) == i)) { median += vals[i]; medianCount++; } sum += vals[i]; // calculate the bases at if (currentValPoint < contigAtVals.length && sum >= contigAtVals[currentValPoint].goal && contigAtVals[currentValPoint].count == 0) { contigAtVals[currentValPoint].count = numberContigsSeen; contigAtVals[currentValPoint].len = vals[i]; contigAtVals[currentValPoint].totalBP = sum; currentValPoint++; } // calculate the NXs if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.1 && n10count == 0) { n10 = vals[i]; n10count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.25 && n25count == 0) { n25 = vals[i]; n25count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.5 && n50count == 0) { n50 = vals[i]; n50count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.75 && n75count == 0) { n75 = vals[i]; n75count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.95 && n95count == 0) { n95 = vals[i]; n95count = vals.length - i; } numberContigsSeen++; } if (medianCount != 1 && medianCount != 2) { System.err.println("ERROR INVALID MEDIAN COUNT " + medianCount); System.exit(1); } if (oldStyle == true) { if (n50only == true) { st.append(title + "\t" + largeInts.format(n50)); } else { st.append("GenomeSize: " + genomeSize + "\n"); st.append("NumReads: " + totalCount + "\n"); st.append("Total units: " + count + "\n"); st.append("BasesInFasta: " + total + "\n"); st.append("Min: " + largeInts.format(min) + "\n"); st.append("Max: " + largeInts.format(max) + "\n"); st.append("N10: " + largeInts.format(n10) + " COUNT: " + n10count + "\n"); st.append("N25: " + largeInts.format(n25) + " COUNT: " + n25count + "\n"); st.append("N50: " + largeInts.format(n50) + " COUNT: " + n50count + "\n"); st.append("N75: " + largeInts.format(n75) + " COUNT: " + n75count + "\n"); st.append("N95: " + largeInts.format(n95) + " COUNT: " + n95count + "\n"); st.append("E-SIZE: " + nf.format(eSize) + "\n"); } } else { if (outputHeader) { st.append("Assembly"); st.append(",Unit Number"); st.append(",Unit Total BP"); st.append(",Number Units > " + MIN_LENGTH); st.append(",Total BP in Units > " + MIN_LENGTH); st.append(",Min"); st.append(",Max"); st.append(",Average"); st.append(",Median"); for (int i = 0; i < contigAtVals.length; i++) { if (contigAtVals[i].count != 0) { st.append(",Unit At " + nf.format(contigAtVals[i].goal) + " Unit Count," + /*"Total Length," + */ " Actual Unit Length" ); } } st.append("\n"); } st.append(title); st.append("," + nf.format(count)); st.append("," + nf.format(total)); st.append("," + nf.format(totalOverLength)); st.append("," + nf.format(totalBPOverLength)); st.append("," + nf.format(min)); st.append("," + nf.format(max)); st.append("," + nf.format((double)total / count)); st.append("," + nf.format((double)median / medianCount)); for (int i = 0; i < contigAtVals.length; i++) { if (contigAtVals[i].count != 0) { st.append("," + contigAtVals[i].count + "," + /*contigAtVals[i].totalBP + "," +*/ contigAtVals[i].len); } } } return st.toString(); }
public String toString(boolean outputHeader, String title) { StringBuffer st = new StringBuffer(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; long total = 0; int count = 0; int n10 = 0; int n25 = 0; int n50 = 0; int n75 = 0; int n95 = 0; int n10count = 0; int n25count = 0; int n50count = 0; int n75count = 0; int n95count = 0; int totalOverLength = 0; long totalBPOverLength = 0; double eSize = 0; if (fastaLens.size() == 0) { System.err.println("No contigs"); return ""; } for (String s : fastaLens.keySet()) { int len = fastaLens.get(s); if (oldStyle == true && len <= MIN_LENGTH) { continue; } if (len > max) { max = len; } if (len < min) { min = len; } total += len; count++; if (len > MIN_LENGTH) { totalOverLength++; totalBPOverLength += len; } eSize += Math.pow(len, 2); } eSize /= (genomeSize == 0 ? totalBPOverLength : genomeSize); // get the goal contig at X bases (1MBp, 2MBp) ArrayList<ContigAt> contigAtArray = new ArrayList<ContigAt>(); if (baylorFormat == true) { contigAtArray.add(new ContigAt( 1 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt( 2 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt( 4 * CONTIG_AT_INITIAL_STEP)); contigAtArray.add(new ContigAt(10 * CONTIG_AT_INITIAL_STEP)); } else { long step = CONTIG_AT_INITIAL_STEP; long currentBases = 0; while (currentBases <= total) { if ((currentBases / step) >= 10) { step *= 10; } currentBases += step; contigAtArray.add(new ContigAt(currentBases)); } } ContigAt[] contigAtVals = contigAtArray.toArray(new ContigAt[0]); Integer[] vals = fastaLens.values().toArray(new Integer[0]); Arrays.sort(vals); long sum = 0; double median = 0; int medianCount = 0; int numberContigsSeen = 0; int currentValPoint = 0; for (int i = vals.length - 1; i >= 0; i--) { if (((int) (count / 2)) == i) { median += vals[i]; medianCount++; } else if (count % 2 == 0 && ((((int) (count / 2)) + 1) == i)) { median += vals[i]; medianCount++; } sum += vals[i]; // calculate the bases at if (currentValPoint < contigAtVals.length && sum >= contigAtVals[currentValPoint].goal && contigAtVals[currentValPoint].count == 0) { contigAtVals[currentValPoint].count = numberContigsSeen; contigAtVals[currentValPoint].len = vals[i]; contigAtVals[currentValPoint].totalBP = sum; currentValPoint++; } // calculate the NXs if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.1 && n10count == 0) { n10 = vals[i]; n10count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.25 && n25count == 0) { n25 = vals[i]; n25count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.5 && n50count == 0) { n50 = vals[i]; n50count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.75 && n75count == 0) { n75 = vals[i]; n75count = vals.length - i; } if (sum / (double)(genomeSize == 0 ? total : genomeSize) >= 0.95 && n95count == 0) { n95 = vals[i]; n95count = vals.length - i; } numberContigsSeen++; } if (medianCount != 1 && medianCount != 2) { System.err.println("ERROR INVALID MEDIAN COUNT " + medianCount); System.exit(1); } if (oldStyle == true) { if (n50only == true) { st.append(title + "\t" + n50); } else { st.append("GenomeSize: " + genomeSize + "\n"); st.append("NumReads: " + totalCount + "\n"); st.append("Total units: " + count + "\n"); st.append("BasesInFasta: " + total + "\n"); st.append("Min: " + largeInts.format(min) + "\n"); st.append("Max: " + largeInts.format(max) + "\n"); st.append("N10: " + largeInts.format(n10) + " COUNT: " + n10count + "\n"); st.append("N25: " + largeInts.format(n25) + " COUNT: " + n25count + "\n"); st.append("N50: " + largeInts.format(n50) + " COUNT: " + n50count + "\n"); st.append("N75: " + largeInts.format(n75) + " COUNT: " + n75count + "\n"); st.append("N95: " + largeInts.format(n95) + " COUNT: " + n95count + "\n"); st.append("E-SIZE: " + nf.format(eSize) + "\n"); } } else { if (outputHeader) { st.append("Assembly"); st.append(",Unit Number"); st.append(",Unit Total BP"); st.append(",Number Units > " + MIN_LENGTH); st.append(",Total BP in Units > " + MIN_LENGTH); st.append(",Min"); st.append(",Max"); st.append(",Average"); st.append(",Median"); for (int i = 0; i < contigAtVals.length; i++) { if (contigAtVals[i].count != 0) { st.append(",Unit At " + nf.format(contigAtVals[i].goal) + " Unit Count," + /*"Total Length," + */ " Actual Unit Length" ); } } st.append("\n"); } st.append(title); st.append("," + nf.format(count)); st.append("," + nf.format(total)); st.append("," + nf.format(totalOverLength)); st.append("," + nf.format(totalBPOverLength)); st.append("," + nf.format(min)); st.append("," + nf.format(max)); st.append("," + nf.format((double)total / count)); st.append("," + nf.format((double)median / medianCount)); for (int i = 0; i < contigAtVals.length; i++) { if (contigAtVals[i].count != 0) { st.append("," + contigAtVals[i].count + "," + /*contigAtVals[i].totalBP + "," +*/ contigAtVals[i].len); } } } return st.toString(); }
diff --git a/src/com/android/calendar/CalendarViewAdapter.java b/src/com/android/calendar/CalendarViewAdapter.java index 5045b6b9a..a31287547 100644 --- a/src/com/android/calendar/CalendarViewAdapter.java +++ b/src/com/android/calendar/CalendarViewAdapter.java @@ -1,450 +1,450 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.calendar; import com.android.calendar.CalendarController.ViewType; import android.content.Context; import android.os.Handler; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import java.util.Calendar; import java.util.Formatter; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.util.Lunar; /* * The MenuSpinnerAdapter defines the look of the ActionBar's pull down menu * for small screen layouts. The pull down menu replaces the tabs uses for big screen layouts * * The MenuSpinnerAdapter responsible for creating the views used for in the pull down menu. */ public class CalendarViewAdapter extends BaseAdapter { private static final String TAG = "MenuSpinnerAdapter"; private final String mButtonNames []; // Text on buttons // Used to define the look of the menu button according to the current view: // Day view: show day of the week + full date underneath // Week view: show the month + year // Month view: show the month + year // Agenda view: show day of the week + full date underneath private int mCurrentMainView; private final LayoutInflater mInflater; // Defines the types of view returned by this spinner private static final int BUTTON_VIEW_TYPE = 0; static final int VIEW_TYPE_NUM = 1; // Increase this if you add more view types public static final int DAY_BUTTON_INDEX = 0; public static final int WEEK_BUTTON_INDEX = 1; public static final int MONTH_BUTTON_INDEX = 2; public static final int AGENDA_BUTTON_INDEX = 3; // The current selected event's time, used to calculate the date and day of the week // for the buttons. private long mMilliTime; private String mTimeZone; private long mTodayJulianDay; private final Context mContext; private final Formatter mFormatter; private final StringBuilder mStringBuilder; private Handler mMidnightHandler = null; // Used to run a time update every midnight private final boolean mShowDate; // Spinner mode indicator (view name or view name with date) // Updates time specific variables (time-zone, today's Julian day). private final Runnable mTimeUpdater = new Runnable() { @Override public void run() { refresh(mContext); } }; public CalendarViewAdapter(Context context, int viewType, boolean showDate) { super(); mMidnightHandler = new Handler(); mCurrentMainView = viewType; mContext = context; mShowDate = showDate; // Initialize mButtonNames = context.getResources().getStringArray(R.array.buttons_list); mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); mStringBuilder = new StringBuilder(50); mFormatter = new Formatter(mStringBuilder, Locale.getDefault()); // Sets time specific variables and starts a thread for midnight updates if (showDate) { refresh(context); } } // Sets the time zone and today's Julian day to be used by the adapter. // Also, notify listener on the change and resets the midnight update thread. public void refresh(Context context) { mTimeZone = Utils.getTimeZone(context, mTimeUpdater); Time time = new Time(mTimeZone); long now = System.currentTimeMillis(); time.set(now); mTodayJulianDay = Time.getJulianDay(now, time.gmtoff); notifyDataSetChanged(); setMidnightHandler(); } // Sets a thread to run 1 second after midnight and update the current date // This is used to display correctly the date of yesterday/today/tomorrow private void setMidnightHandler() { mMidnightHandler.removeCallbacks(mTimeUpdater); // Set the time updater to run at 1 second after midnight long now = System.currentTimeMillis(); Time time = new Time(mTimeZone); time.set(now); long runInMillis = (24 * 3600 - time.hour * 3600 - time.minute * 60 - time.second + 1) * 1000; mMidnightHandler.postDelayed(mTimeUpdater, runInMillis); } // Stops the midnight update thread, called by the activity when it is paused. public void onPause() { mMidnightHandler.removeCallbacks(mTimeUpdater); } // Returns the amount of buttons in the menu @Override public int getCount() { return mButtonNames.length; } @Override public Object getItem(int position) { if (position < mButtonNames.length) { return mButtonNames[position]; } return null; } @Override public long getItemId(int position) { // Item ID is its location in the list return position; } @Override public boolean hasStableIds() { return false; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v; if (mShowDate) { // Check if can recycle the view if (convertView == null || ((Integer) convertView.getTag()).intValue() != R.layout.actionbar_pulldown_menu_top_button) { v = mInflater.inflate(R.layout.actionbar_pulldown_menu_top_button, parent, false); // Set the tag to make sure you can recycle it when you get it // as a convert view v.setTag(new Integer(R.layout.actionbar_pulldown_menu_top_button)); } else { v = convertView; } TextView weekDay = (TextView) v.findViewById(R.id.top_button_weekday); TextView date = (TextView) v.findViewById(R.id.top_button_date); switch (mCurrentMainView) { case ViewType.DAY: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildFullDate()); break; case ViewType.WEEK: if (Utils.getShowWeekNumber(mContext)) { weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildWeekNum()); } else { weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(false)); } date.setText(buildMonthYearDate()); break; case ViewType.MONTH: weekDay.setVisibility(View.VISIBLE); - weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); + weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(false)); date.setText(buildMonthYearDate()); break; case ViewType.AGENDA: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildFullDate()); break; default: v = null; break; } } else { if (convertView == null || ((Integer) convertView.getTag()).intValue() != R.layout.actionbar_pulldown_menu_top_button_no_date) { v = mInflater.inflate( R.layout.actionbar_pulldown_menu_top_button_no_date, parent, false); // Set the tag to make sure you can recycle it when you get it // as a convert view v.setTag(new Integer(R.layout.actionbar_pulldown_menu_top_button_no_date)); } else { v = convertView; } TextView title = (TextView) v; switch (mCurrentMainView) { case ViewType.DAY: title.setText(mButtonNames [DAY_BUTTON_INDEX]); break; case ViewType.WEEK: title.setText(mButtonNames [WEEK_BUTTON_INDEX]); break; case ViewType.MONTH: title.setText(mButtonNames [MONTH_BUTTON_INDEX]); break; case ViewType.AGENDA: title.setText(mButtonNames [AGENDA_BUTTON_INDEX]); break; default: v = null; break; } } return v; } @Override public int getItemViewType(int position) { // Only one kind of view is used return BUTTON_VIEW_TYPE; } @Override public int getViewTypeCount() { return VIEW_TYPE_NUM; } @Override public boolean isEmpty() { return (mButtonNames.length == 0); } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View v = mInflater.inflate(R.layout.actionbar_pulldown_menu_button, parent, false); TextView viewType = (TextView)v.findViewById(R.id.button_view); TextView date = (TextView)v.findViewById(R.id.button_date); switch (position) { case DAY_BUTTON_INDEX: viewType.setText(mButtonNames [DAY_BUTTON_INDEX]); if (mShowDate) { date.setText(buildMonthDayDate()); } break; case WEEK_BUTTON_INDEX: viewType.setText(mButtonNames [WEEK_BUTTON_INDEX]); if (mShowDate) { date.setText(buildWeekDate()); } break; case MONTH_BUTTON_INDEX: viewType.setText(mButtonNames [MONTH_BUTTON_INDEX]); if (mShowDate) { date.setText(buildMonthDate()); } break; case AGENDA_BUTTON_INDEX: viewType.setText(mButtonNames [AGENDA_BUTTON_INDEX]); if (mShowDate) { date.setText(buildMonthDayDate()); } break; default: v = convertView; break; } return v; } // Updates the current viewType // Used to match the label on the menu button with the calendar view public void setMainView(int viewType) { mCurrentMainView = viewType; notifyDataSetChanged(); } // Update the date that is displayed on buttons // Used when the user selects a new day/week/month to watch public void setTime(long time) { mMilliTime = time; notifyDataSetChanged(); } // Builds a string with the day of the week and the word yesterday/today/tomorrow // before it if applicable. private String buildDayOfWeek() { Time t = new Time(mTimeZone); t.set(mMilliTime); long julianDay = Time.getJulianDay(mMilliTime,t.gmtoff); String dayOfWeek = null; mStringBuilder.setLength(0); if (julianDay == mTodayJulianDay) { dayOfWeek = mContext.getString(R.string.agenda_today, DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_WEEKDAY, mTimeZone).toString()); } else if (julianDay == mTodayJulianDay - 1) { dayOfWeek = mContext.getString(R.string.agenda_yesterday, DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_WEEKDAY, mTimeZone).toString()); } else if (julianDay == mTodayJulianDay + 1) { dayOfWeek = mContext.getString(R.string.agenda_tomorrow, DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_WEEKDAY, mTimeZone).toString()); } else { dayOfWeek = DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_WEEKDAY, mTimeZone).toString(); } return dayOfWeek.toUpperCase(); } // Builds strings with different formats: // Full date: Month,day Year // Month year // Month day // Month // Week: month day-day or month day - month day private String buildFullDate() { mStringBuilder.setLength(0); String date = DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR, mTimeZone).toString(); return date; } private String buildLunarDate(boolean isFull){ List<String> list = new ArrayList<String>(); Calendar cal = Calendar.getInstance(); String date = DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR, mTimeZone).toString(); Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]+|\\d+"); Matcher m = p.matcher(date); while(m.find()){ list.add(m.group()); } cal.set(Integer.parseInt(list.get(1)), Integer.parseInt(list.get(3)) - 1,Integer.parseInt(list.get(5))); Lunar lunar = new Lunar(cal, mContext); return isFull == true ? lunar.toString():lunar.toString().substring(0, 4); } private String buildMonthYearDate() { mStringBuilder.setLength(0); String date = DateUtils.formatDateRange( mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_SHOW_YEAR, mTimeZone).toString(); return date; } private String buildMonthDayDate() { mStringBuilder.setLength(0); String date = DateUtils.formatDateRange(mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR, mTimeZone).toString(); return date; } private String buildMonthDate() { mStringBuilder.setLength(0); String date = DateUtils.formatDateRange( mContext, mFormatter, mMilliTime, mMilliTime, DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR | DateUtils.FORMAT_NO_MONTH_DAY, mTimeZone).toString(); return date; } private String buildWeekDate() { // Calculate the start of the week, taking into account the "first day of the week" // setting. Time t = new Time(mTimeZone); t.set(mMilliTime); int firstDayOfWeek = Utils.getFirstDayOfWeek(mContext); int dayOfWeek = t.weekDay; int diff = dayOfWeek - firstDayOfWeek; if (diff != 0) { if (diff < 0) { diff += 7; } t.monthDay -= diff; t.normalize(true /* ignore isDst */); } long weekStartTime = t.toMillis(true); // The end of the week is 6 days after the start of the week long weekEndTime = weekStartTime + DateUtils.WEEK_IN_MILLIS - DateUtils.DAY_IN_MILLIS; // If week start and end is in 2 different months, use short months names Time t1 = new Time(mTimeZone); t.set(weekEndTime); int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR; if (t.month != t1.month) { flags |= DateUtils.FORMAT_ABBREV_MONTH; } mStringBuilder.setLength(0); String date = DateUtils.formatDateRange(mContext, mFormatter, weekStartTime, weekEndTime, flags, mTimeZone).toString(); return date; } private String buildWeekNum() { int week = Utils.getWeekNumberFromTime(mMilliTime, mContext); return mContext.getResources().getQuantityString(R.plurals.weekN, week, week); } }
true
true
public View getView(int position, View convertView, ViewGroup parent) { View v; if (mShowDate) { // Check if can recycle the view if (convertView == null || ((Integer) convertView.getTag()).intValue() != R.layout.actionbar_pulldown_menu_top_button) { v = mInflater.inflate(R.layout.actionbar_pulldown_menu_top_button, parent, false); // Set the tag to make sure you can recycle it when you get it // as a convert view v.setTag(new Integer(R.layout.actionbar_pulldown_menu_top_button)); } else { v = convertView; } TextView weekDay = (TextView) v.findViewById(R.id.top_button_weekday); TextView date = (TextView) v.findViewById(R.id.top_button_date); switch (mCurrentMainView) { case ViewType.DAY: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildFullDate()); break; case ViewType.WEEK: if (Utils.getShowWeekNumber(mContext)) { weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildWeekNum()); } else { weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(false)); } date.setText(buildMonthYearDate()); break; case ViewType.MONTH: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildMonthYearDate()); break; case ViewType.AGENDA: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildFullDate()); break; default: v = null; break; } } else { if (convertView == null || ((Integer) convertView.getTag()).intValue() != R.layout.actionbar_pulldown_menu_top_button_no_date) { v = mInflater.inflate( R.layout.actionbar_pulldown_menu_top_button_no_date, parent, false); // Set the tag to make sure you can recycle it when you get it // as a convert view v.setTag(new Integer(R.layout.actionbar_pulldown_menu_top_button_no_date)); } else { v = convertView; } TextView title = (TextView) v; switch (mCurrentMainView) { case ViewType.DAY: title.setText(mButtonNames [DAY_BUTTON_INDEX]); break; case ViewType.WEEK: title.setText(mButtonNames [WEEK_BUTTON_INDEX]); break; case ViewType.MONTH: title.setText(mButtonNames [MONTH_BUTTON_INDEX]); break; case ViewType.AGENDA: title.setText(mButtonNames [AGENDA_BUTTON_INDEX]); break; default: v = null; break; } } return v; }
public View getView(int position, View convertView, ViewGroup parent) { View v; if (mShowDate) { // Check if can recycle the view if (convertView == null || ((Integer) convertView.getTag()).intValue() != R.layout.actionbar_pulldown_menu_top_button) { v = mInflater.inflate(R.layout.actionbar_pulldown_menu_top_button, parent, false); // Set the tag to make sure you can recycle it when you get it // as a convert view v.setTag(new Integer(R.layout.actionbar_pulldown_menu_top_button)); } else { v = convertView; } TextView weekDay = (TextView) v.findViewById(R.id.top_button_weekday); TextView date = (TextView) v.findViewById(R.id.top_button_date); switch (mCurrentMainView) { case ViewType.DAY: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildFullDate()); break; case ViewType.WEEK: if (Utils.getShowWeekNumber(mContext)) { weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildWeekNum()); } else { weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(false)); } date.setText(buildMonthYearDate()); break; case ViewType.MONTH: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(false)); date.setText(buildMonthYearDate()); break; case ViewType.AGENDA: weekDay.setVisibility(View.VISIBLE); weekDay.setText(buildDayOfWeek()+" "+buildLunarDate(true)); date.setText(buildFullDate()); break; default: v = null; break; } } else { if (convertView == null || ((Integer) convertView.getTag()).intValue() != R.layout.actionbar_pulldown_menu_top_button_no_date) { v = mInflater.inflate( R.layout.actionbar_pulldown_menu_top_button_no_date, parent, false); // Set the tag to make sure you can recycle it when you get it // as a convert view v.setTag(new Integer(R.layout.actionbar_pulldown_menu_top_button_no_date)); } else { v = convertView; } TextView title = (TextView) v; switch (mCurrentMainView) { case ViewType.DAY: title.setText(mButtonNames [DAY_BUTTON_INDEX]); break; case ViewType.WEEK: title.setText(mButtonNames [WEEK_BUTTON_INDEX]); break; case ViewType.MONTH: title.setText(mButtonNames [MONTH_BUTTON_INDEX]); break; case ViewType.AGENDA: title.setText(mButtonNames [AGENDA_BUTTON_INDEX]); break; default: v = null; break; } } return v; }
diff --git a/src/service/hr/fer/zemris/vhdllab/vhdl/simulations/VcdParser.java b/src/service/hr/fer/zemris/vhdllab/vhdl/simulations/VcdParser.java index b45c9867..36a0e376 100644 --- a/src/service/hr/fer/zemris/vhdllab/vhdl/simulations/VcdParser.java +++ b/src/service/hr/fer/zemris/vhdllab/vhdl/simulations/VcdParser.java @@ -1,351 +1,360 @@ package hr.fer.zemris.vhdllab.vhdl.simulations; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Klasa cita linije VCD-datoteke i sprema ih polje stringova * @author Boris Ozegovic */ class VcdFileReader { /** Ime datoteke koju treba parsirati */ private String fileName; /** Constructor * * @param fileName VCD file */ VcdFileReader (String fileName) { this.fileName = fileName; } /** * Metoda koja cita VCD-datoteku * * @return Polje stringova; string predstavlja pojedinu liniju datoteke */ public String[] toArrayString () { String string; List<String> list = new ArrayList<String>(); try { BufferedReader in = new BufferedReader(new FileReader (fileName)); while ((string = in.readLine()) != null) { list.add(string); } in.close(); } catch (FileNotFoundException e) { System.out.println ("File open error"); } catch (IOException e) { System.out.println ("File input/output error"); } return ((String[])list.toArray(new String[list.size()])); } } /** * Klasa parsira VCD-datoteku koju generira GHDL (GHDL je GNU VHDL simulator) * VCD-datoteka ima sljedeci format: 9 prvih linija predstavljaju osnovne * informacije koje su konstantne za svaku datoteku. Nakon njih dolazi popis * svih signala predstavljen u obliku ASCII simbola, npr: * $var reg 1 ! tb_a $end * Svaka linija koja pocinje s "$var" predstavlja jedan signal. U produzetku se * nalazi tip signala (vektor, bit) predstavljen brojem iza podstringa "reg", * i sam ASCII simbol signala (u ovom slucaju je to "!"). Na kraju se nalazi * ime tog signala. Svaki se signal nalazi unutar svog scopea. * S podstringom "#0" pocinje samo simulacija: svaka se tocka promjene oznacuje * s '#' iza kojih slijedi vrijednost promjene. Vazno je napomenuti da vektori * imaju poseban nacin oznacavanja: svaki vektor pocinje sa slovom 'b', a prije * ASCII vrijednosti signala mora biti praznina. * * @author Boris Ozegovic */ public class VcdParser { /* Parser pocinje parsirati nakon osnovnih informacija */ private int index = 9; /** Sadrzi sve linije datoteke */ private String[] vcdLines; /** * Mapa ciji su kljucevi kompletna imena signala (scope ukljuciv), * te cije su vrijednosti poznate u svakoj od tocaka tranzicije */ private Map<String, List<String>> signalValues = new LinkedHashMap<String, List<String>>(); /** Sadrzi vrijednosti tocaka tranzicije (npr. 750-toj ns) */ private List<Long> transitionPoints = new ArrayList<Long>(); /** Sadrzi upotrebljene ASCII simbole, svaki od njih predstavlja signal */ private List<Character> asciiSignalSimbols = new ArrayList<Character>(); /** Predstavlja najduze ime od svih signala, potreban zbog duljine panela */ private int maximumSignalNameLength; /** Predstavlja string koji se prenosi klijentu */ private StringBuffer resultInString = new StringBuffer(""); /** * Upotrebljava se za interni format prilikom razdvajanja imena signala i * razdvajanja vrijednosti za svaki od signala prilikom transformacije us * mape u string */ private final String LIMITER = "###"; /** * Limiter koji razdvaja s jedne strane sva imena signala, njihove * vrijednosti, tocke u kojima se dogada promjena vrijednosti i konacno * duljinu u znakovima najduzeg imena signala */ private final String HEAD_LIMITER = "%%%"; /** Limiter koji razdvaju svaku od trenutnih vrijednosti (0 */ private final String VALUE_LIMITER = "&&&"; /** * Constructor * * @param fileName ime datoteke */ public VcdParser (String fileName) { VcdFileReader reader = new VcdFileReader(fileName); vcdLines = reader.toArrayString(); } /** * Metoda izdvaja ASCII reprezentante odgovarajucih signala i trazi * puna imena svih signala. Mapa imena signala/njihove vrijednosti poslije * koristenja ove metode sadrzavat ce samo imena signala kao kljuceve, bez * vrijednosti. Koristi je metoda parse(); */ public void parseSignals() { /* Pretrazuje sve linije dok ne nade kraj definiranja simbola. Ako linija * pocinje s $var znaci da predstavlja signal, pa se pronalazi ASCII simbol * i puno ime. Ako linija pocinje s $scope znaci da ulazimo u novi scope te * se u listu (koja se ponasao kao stog) dodaje novi scope na prethodni. * Inace brise zadnji dodan scope. */ LinkedList<String> scopeName = new LinkedList<String>(); scopeName.addFirst("/"); int endSignIndex; /* indeks na kojem pocinje $end */ String signalName; /* ime bez scopea */ StringBuffer completeSignalName = new StringBuffer(""); /* ime sa scopeom */ while (!vcdLines[index].equals("$enddefinitions $end")) { endSignIndex = vcdLines[index].indexOf("$end"); if (vcdLines[index].indexOf("$var") == 0) { asciiSignalSimbols.add(vcdLines[index].charAt(11)); signalName = vcdLines[index].substring(13, endSignIndex - 1); completeSignalName.setLength(0); completeSignalName.append(scopeName.getFirst()).append(signalName); if (vcdLines[index].charAt(9) != '1') { completeSignalName.insert(0, "+ "); } signalValues.put(completeSignalName.toString(), new ArrayList<String>()); if (completeSignalName.length() > maximumSignalNameLength) { maximumSignalNameLength = completeSignalName.length(); } } else if (vcdLines[index].indexOf ("$scope") == 0) { scopeName.addFirst(new StringBuffer(scopeName.getFirst()) .append(vcdLines[index].substring(14, endSignIndex - 1)).append("/").toString()); } else { scopeName.removeFirst (); } index++; } } /** * Metoda koja parsira cijelu VHDL-simulaciju. Nakon sto se upotrijebi ova * metoda dobije se rezultat u obliku stringa kojeg vraca * getResultInString() metoda. Za potpuno parsiranje dovoljna je upotreba * samo ove metode. */ public void parse() { /* Pretrazuje sve do kraja datoteke, tj. polja Stringova. Izmedu svake * tocke u kojima se dogada promjena (tocke tranzicije) cita red po red i * provjerava vrijednosti signala. Ako vrijednost pocinje s slovom 'b' * znaci da slijedi vrijednost vektora iza koje se nalazi znak praznine i * tek onda ASCII simbol, inace obraduje normalni signal. Pronalazi ASCII * simbol za svkai od signala i usporeduje koji je to signal u polju po redu * tako da automatski moze dodati pod tim indeksom novu vrijednost u * privremenom polju values. Nakon svake iteracije pune se mapa s * vrijednostima polje values, s tim da oni signali koji nisu mijenjali * vrijednost imaju vrijednost od prethodne iteracije. */ parseSignals(); /* vrijednosti pojedinih signala. Mogu biti 0, 1, U, X, Z... */ String[] values = new String[asciiSignalSimbols.size()]; char asciiSimbol; int position; int positionOfWhiteSpaceChar; /* odmah dodaje nulu. Nula predstavlja pocetak simulacije */ transitionPoints.add(Long.valueOf(vcdLines[++index].substring(1))); + boolean isSharpFound = true; for (++index; index < vcdLines.length; index++) { - while (index < vcdLines.length && vcdLines[index].charAt(0) != '#') + while (vcdLines[index].charAt(0) != '#') { if (vcdLines[index].charAt(0) != 'b') { asciiSimbol = vcdLines[index].charAt(1); position = asciiSignalSimbols.indexOf(asciiSimbol); values[position] = new Character(vcdLines[index].charAt(0)).toString(); } else { positionOfWhiteSpaceChar = vcdLines[index].indexOf(' '); asciiSimbol = vcdLines[index].charAt(positionOfWhiteSpaceChar + 1); position = asciiSignalSimbols.indexOf(asciiSimbol); values[position] = vcdLines[index].substring (1, positionOfWhiteSpaceChar); } index++; + if (index == vcdLines.length) { + isSharpFound = false; + break; + } } - transitionPoints.add (Long.valueOf(vcdLines[index].substring(1))); + if (isSharpFound) { + transitionPoints.add (Long.valueOf(vcdLines[index].substring(1))); + } else { + transitionPoints.add(transitionPoints.get(transitionPoints.size() - 1)); + } Iterator<List<String>> e = signalValues.values().iterator(); int i = 0; while (e.hasNext()) { ((List<String>)e.next()).add(values[i++]); } } this.resultToString(); } /** * Getter koji vraca rezultat simulacije kao jedan string * * @return Rezultat simulacije predstavljen kao String */ public String getResultInString () { return resultInString.toString(); } /** * Getter koji vraca mapu imena signala i njihovih vrijednosti */ public Map<String, List<String>> getSignalValues () { return signalValues; } /** * Getter koji vraca tocke promjene vrijednosti */ public List<Long> getTransitionPoints () { return transitionPoints; } /** * Getter koji vraca najduze ime signala */ public int getMaximumSignalNameLength () { return maximumSignalNameLength; } /** * Test metoda */ public static void main(String[] args) { VcdParser parser = new VcdParser("adder2.vcd"); parser.parse(); parser.resultToString(); System.out.println(parser.getResultInString()); } /** * Metoda transformira mapu sa imenima signala i njihovim vrijednostima, te * listu sa svim tockama u kojima se dogada promjena vrijednosti signala u * jedan string pomocu internog formata, npr: A###B%%%0&&&1&&&Z###1&&&Z&&&1 * Razlog je tome sto se pomocu HTTP-a ne mogu prenositi objekti */ private void resultToString () { for (String key : signalValues.keySet()) { resultInString.append(key).append(LIMITER); } /* ukloni zadnji limiter */ resultInString.delete(resultInString.length() - 3, resultInString.length()); /* stavi limiter izmedu imena signala i vrijednosti */ resultInString.append(HEAD_LIMITER); for (List<String> values : signalValues.values()) { for (String string : values) { resultInString.append(string).append(VALUE_LIMITER); } resultInString.delete(resultInString.length() - 3, resultInString.length()); resultInString.append(LIMITER); } resultInString.delete(resultInString.length() - 3, resultInString.length()); /* * stavli limiter izmedu vrijednosti signala i tocaka u kojima se dogada * promjena vrijednosti */ resultInString.append(HEAD_LIMITER); for (Long point : transitionPoints) { resultInString.append(point).append(LIMITER); } /* ukloni zadnji limiter */ resultInString.delete(resultInString.length() - 3, resultInString.length()); /* broj znakova najduljeg imena signala */ resultInString.append(HEAD_LIMITER).append(maximumSignalNameLength); } }
false
true
public void parse() { /* Pretrazuje sve do kraja datoteke, tj. polja Stringova. Izmedu svake * tocke u kojima se dogada promjena (tocke tranzicije) cita red po red i * provjerava vrijednosti signala. Ako vrijednost pocinje s slovom 'b' * znaci da slijedi vrijednost vektora iza koje se nalazi znak praznine i * tek onda ASCII simbol, inace obraduje normalni signal. Pronalazi ASCII * simbol za svkai od signala i usporeduje koji je to signal u polju po redu * tako da automatski moze dodati pod tim indeksom novu vrijednost u * privremenom polju values. Nakon svake iteracije pune se mapa s * vrijednostima polje values, s tim da oni signali koji nisu mijenjali * vrijednost imaju vrijednost od prethodne iteracije. */ parseSignals(); /* vrijednosti pojedinih signala. Mogu biti 0, 1, U, X, Z... */ String[] values = new String[asciiSignalSimbols.size()]; char asciiSimbol; int position; int positionOfWhiteSpaceChar; /* odmah dodaje nulu. Nula predstavlja pocetak simulacije */ transitionPoints.add(Long.valueOf(vcdLines[++index].substring(1))); for (++index; index < vcdLines.length; index++) { while (index < vcdLines.length && vcdLines[index].charAt(0) != '#') { if (vcdLines[index].charAt(0) != 'b') { asciiSimbol = vcdLines[index].charAt(1); position = asciiSignalSimbols.indexOf(asciiSimbol); values[position] = new Character(vcdLines[index].charAt(0)).toString(); } else { positionOfWhiteSpaceChar = vcdLines[index].indexOf(' '); asciiSimbol = vcdLines[index].charAt(positionOfWhiteSpaceChar + 1); position = asciiSignalSimbols.indexOf(asciiSimbol); values[position] = vcdLines[index].substring (1, positionOfWhiteSpaceChar); } index++; } transitionPoints.add (Long.valueOf(vcdLines[index].substring(1))); Iterator<List<String>> e = signalValues.values().iterator(); int i = 0; while (e.hasNext()) { ((List<String>)e.next()).add(values[i++]); } } this.resultToString(); }
public void parse() { /* Pretrazuje sve do kraja datoteke, tj. polja Stringova. Izmedu svake * tocke u kojima se dogada promjena (tocke tranzicije) cita red po red i * provjerava vrijednosti signala. Ako vrijednost pocinje s slovom 'b' * znaci da slijedi vrijednost vektora iza koje se nalazi znak praznine i * tek onda ASCII simbol, inace obraduje normalni signal. Pronalazi ASCII * simbol za svkai od signala i usporeduje koji je to signal u polju po redu * tako da automatski moze dodati pod tim indeksom novu vrijednost u * privremenom polju values. Nakon svake iteracije pune se mapa s * vrijednostima polje values, s tim da oni signali koji nisu mijenjali * vrijednost imaju vrijednost od prethodne iteracije. */ parseSignals(); /* vrijednosti pojedinih signala. Mogu biti 0, 1, U, X, Z... */ String[] values = new String[asciiSignalSimbols.size()]; char asciiSimbol; int position; int positionOfWhiteSpaceChar; /* odmah dodaje nulu. Nula predstavlja pocetak simulacije */ transitionPoints.add(Long.valueOf(vcdLines[++index].substring(1))); boolean isSharpFound = true; for (++index; index < vcdLines.length; index++) { while (vcdLines[index].charAt(0) != '#') { if (vcdLines[index].charAt(0) != 'b') { asciiSimbol = vcdLines[index].charAt(1); position = asciiSignalSimbols.indexOf(asciiSimbol); values[position] = new Character(vcdLines[index].charAt(0)).toString(); } else { positionOfWhiteSpaceChar = vcdLines[index].indexOf(' '); asciiSimbol = vcdLines[index].charAt(positionOfWhiteSpaceChar + 1); position = asciiSignalSimbols.indexOf(asciiSimbol); values[position] = vcdLines[index].substring (1, positionOfWhiteSpaceChar); } index++; if (index == vcdLines.length) { isSharpFound = false; break; } } if (isSharpFound) { transitionPoints.add (Long.valueOf(vcdLines[index].substring(1))); } else { transitionPoints.add(transitionPoints.get(transitionPoints.size() - 1)); } Iterator<List<String>> e = signalValues.values().iterator(); int i = 0; while (e.hasNext()) { ((List<String>)e.next()).add(values[i++]); } } this.resultToString(); }
diff --git a/src/org/fiz/section/CompoundSection.java b/src/org/fiz/section/CompoundSection.java index 1a4b2ac..ec7b0bd 100644 --- a/src/org/fiz/section/CompoundSection.java +++ b/src/org/fiz/section/CompoundSection.java @@ -1,221 +1,221 @@ /* Copyright (c) 2008-2010 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package org.fiz.section; import org.fiz.*; import java.util.*; /** * A CompoundSection is a Section that contains one or more other Sections. * By default the sections will be output right after each other, but if a * {@code layout} is specified, that is used to arrange the sections. * CompoundSections support the following constructor properties: * background: (optional) Specifies a background color to use for * the interior of this section (everything inside the * border). Defaults to transparent. * borderFamily: (optional) Specifies the base name for a family of * images that will be used to display a border around this * section. If this option has the value {@code x.gif}, then * there must exist images named {@code x-nw.gif}, * {@code x-n.gif}, {@code x-ne.gif}, {@code x-e.gif}, * {@code x-se.gif}, {@code x-s.gif}, {@code x-sw.gif}, * and {@code x-w.gif}; {@code x-nw.gif} displays the * upper left corner of the border, {@code x-n.gif} will be * stretched to cover the top of the border, and so on. * layout: (optional) Specifies a layout for arranging child * sections. See {@link Layout} for details. The layout will * be passed in a Dataset with id-section pairs, with the id * being the id of the section. * class: (optional) Used as the {@code class} attribute for * the HTML table or div that contains the CompoundSection. * id: (optional) Used as the {@code id} attribute for the * HTML table or div that contains the CompoundSection. * Used to find the section in Javascript, e.g. to make it * visible or invisible. Must be unique among all id's * for the page. * * CompoundSection automatically sets the following {@code class} attributes * for use in CSS: * compoundBody: The {@code <tr>} element containing all of the nested * child sections. */ public class CompoundSection extends Section { // The following variables are copies of the constructor arguments by // the same names. See the constructor documentation for details. protected Section[] children; // If the {@code add} method has been called, the following variable // keeps track of all of the additional children (not including // those already referred to by the {@code children} variable). protected ArrayList<Section> extraChildren = null; /** * Construct a CompoundSection. * @param properties Contains configuration information for * the section. * @param children Any number of Sections, which will be * displayed inside this section */ public CompoundSection(Dataset properties, Section ... children) { this.properties = properties; this.children = children; } /** * Add one or more additional children to an existing compound section. * The new children go at the end of the list. * @param children One or more additional children. */ public void add(Section ... children) { if (extraChildren == null) { extraChildren = new ArrayList<Section>(); } for (Section child: children) { extraChildren.add(child); } } @Override public void render(ClientRequest cr) { // If there is a border for this section, then the section gets // rendered as a 3x3 table, with the outer cells containing the // border and the inner cell containing the children's sections. // If there is no border then the section is rendered in a <div>. // Render the portion of the container that comes before the children. StringBuilder out = cr.getHtml().getBody(); Template.appendHtml(out, "\n<!-- Start CompoundSection {{@id}} -->\n", properties); String borderFamily = properties.checkString("borderFamily"); Layout layout = null; - if (properties.check("layout") instanceof Layout) { + if (properties.check("layout") != null) { layout = (Layout) properties.get("layout"); } if (borderFamily != null) { Template.appendHtml(out, "<table {{id=\"@id\"}} {{class=\"@class\"}} " + "cellspacing=\"0\">\n" + " <tr style=\"line-height: 0px;\">\n" + " <td><img src=\"@1\" alt=\"\" />" + "</td>\n" + " <td style=\"background-image: " + "url(@2); " + "background-repeat: repeat-x;\">" + "</td>\n" + " <td><img src=\"@3\" alt=\"\" />" + "</td>\n" + " </tr>\n" + " <tr>\n" + " <td style=\"background-image: " + "url(@4); " + "background-repeat: repeat-y;\">" + "</td>\n" + " <td class=\"compoundBody\" " + "{{style=\"background: @background;\"}}>\n", properties, StringUtil.addSuffix(borderFamily, "-nw"), StringUtil.addSuffix(borderFamily, "-n"), StringUtil.addSuffix(borderFamily, "-ne"), StringUtil.addSuffix(borderFamily, "-w")); } else { Template.appendHtml(out, "<div {{id=\"@id\"}} {{class=\"@class\"}} " + "{{style=\"background: @background;\"}}>\n", properties); } if (layout != null) { Dataset data = new Dataset(); for (Section child : children) { data.set(child.getId(), child); } if (extraChildren != null) { for (Section child : extraChildren) { data.set(child.getId(), child); } } layout.render(cr, data); } else { for (Section child: children) { child.render(cr); } if (extraChildren != null) { for (Section child: extraChildren) { child.render(cr); } } } // Render the portion of the container that comes after the children. if (borderFamily != null) { Template.appendHtml(out, " </td>\n" + " <td style=\"background-image: " + "url(@1); " + "background-repeat: repeat-y;\">" + "</td>\n" + " </tr>\n" + " <tr style=\"line-height: 0px;\">\n" + " <td><img src=\"@2\" alt=\"\" />" + "</td>\n" + " <td style=\"background-image: " + "url(@3); " + "background-repeat: repeat-x;\">" + "</td>\n" + " <td><img src=\"@4\" alt=\"\" />" + "</td>\n" + " </tr>\n" + "</table>\n", properties, StringUtil.addSuffix(borderFamily, "-e"), StringUtil.addSuffix(borderFamily, "-sw"), StringUtil.addSuffix(borderFamily, "-s"), StringUtil.addSuffix(borderFamily, "-se")); } else { out.append("</div>\n"); } Template.appendHtml(out, "<!-- End CompoundSection {{@id}} -->\n", properties); } /** * Generate HTML for a child element of this container and append it to * the Html object associated with {@code cr}. If a child element * named {@code id} does not exist, this method just returns without * modifying {@code cr}. * * @param id The id of the child element. * @param cr Overall information about the client * request being serviced; HTML should get appended to * {@code cr.getHtml()}. */ public void renderChild(String id, ClientRequest cr) { // Search for a child Section whose id is "id". for (Section child : children) { String childId = child.checkId(); if (childId != null && childId.equals(id)) { // Found a child section with a matching id, generate Html // and return. child.render(cr); return; } } if (extraChildren != null) { for (Section child : extraChildren) { String childId = child.checkId(); if (childId != null && childId.equals(id)) { child.render(cr); return; } } } } }
true
true
public void render(ClientRequest cr) { // If there is a border for this section, then the section gets // rendered as a 3x3 table, with the outer cells containing the // border and the inner cell containing the children's sections. // If there is no border then the section is rendered in a <div>. // Render the portion of the container that comes before the children. StringBuilder out = cr.getHtml().getBody(); Template.appendHtml(out, "\n<!-- Start CompoundSection {{@id}} -->\n", properties); String borderFamily = properties.checkString("borderFamily"); Layout layout = null; if (properties.check("layout") instanceof Layout) { layout = (Layout) properties.get("layout"); } if (borderFamily != null) { Template.appendHtml(out, "<table {{id=\"@id\"}} {{class=\"@class\"}} " + "cellspacing=\"0\">\n" + " <tr style=\"line-height: 0px;\">\n" + " <td><img src=\"@1\" alt=\"\" />" + "</td>\n" + " <td style=\"background-image: " + "url(@2); " + "background-repeat: repeat-x;\">" + "</td>\n" + " <td><img src=\"@3\" alt=\"\" />" + "</td>\n" + " </tr>\n" + " <tr>\n" + " <td style=\"background-image: " + "url(@4); " + "background-repeat: repeat-y;\">" + "</td>\n" + " <td class=\"compoundBody\" " + "{{style=\"background: @background;\"}}>\n", properties, StringUtil.addSuffix(borderFamily, "-nw"), StringUtil.addSuffix(borderFamily, "-n"), StringUtil.addSuffix(borderFamily, "-ne"), StringUtil.addSuffix(borderFamily, "-w")); } else { Template.appendHtml(out, "<div {{id=\"@id\"}} {{class=\"@class\"}} " + "{{style=\"background: @background;\"}}>\n", properties); } if (layout != null) { Dataset data = new Dataset(); for (Section child : children) { data.set(child.getId(), child); } if (extraChildren != null) { for (Section child : extraChildren) { data.set(child.getId(), child); } } layout.render(cr, data); } else { for (Section child: children) { child.render(cr); } if (extraChildren != null) { for (Section child: extraChildren) { child.render(cr); } } } // Render the portion of the container that comes after the children. if (borderFamily != null) { Template.appendHtml(out, " </td>\n" + " <td style=\"background-image: " + "url(@1); " + "background-repeat: repeat-y;\">" + "</td>\n" + " </tr>\n" + " <tr style=\"line-height: 0px;\">\n" + " <td><img src=\"@2\" alt=\"\" />" + "</td>\n" + " <td style=\"background-image: " + "url(@3); " + "background-repeat: repeat-x;\">" + "</td>\n" + " <td><img src=\"@4\" alt=\"\" />" + "</td>\n" + " </tr>\n" + "</table>\n", properties, StringUtil.addSuffix(borderFamily, "-e"), StringUtil.addSuffix(borderFamily, "-sw"), StringUtil.addSuffix(borderFamily, "-s"), StringUtil.addSuffix(borderFamily, "-se")); } else { out.append("</div>\n"); } Template.appendHtml(out, "<!-- End CompoundSection {{@id}} -->\n", properties); }
public void render(ClientRequest cr) { // If there is a border for this section, then the section gets // rendered as a 3x3 table, with the outer cells containing the // border and the inner cell containing the children's sections. // If there is no border then the section is rendered in a <div>. // Render the portion of the container that comes before the children. StringBuilder out = cr.getHtml().getBody(); Template.appendHtml(out, "\n<!-- Start CompoundSection {{@id}} -->\n", properties); String borderFamily = properties.checkString("borderFamily"); Layout layout = null; if (properties.check("layout") != null) { layout = (Layout) properties.get("layout"); } if (borderFamily != null) { Template.appendHtml(out, "<table {{id=\"@id\"}} {{class=\"@class\"}} " + "cellspacing=\"0\">\n" + " <tr style=\"line-height: 0px;\">\n" + " <td><img src=\"@1\" alt=\"\" />" + "</td>\n" + " <td style=\"background-image: " + "url(@2); " + "background-repeat: repeat-x;\">" + "</td>\n" + " <td><img src=\"@3\" alt=\"\" />" + "</td>\n" + " </tr>\n" + " <tr>\n" + " <td style=\"background-image: " + "url(@4); " + "background-repeat: repeat-y;\">" + "</td>\n" + " <td class=\"compoundBody\" " + "{{style=\"background: @background;\"}}>\n", properties, StringUtil.addSuffix(borderFamily, "-nw"), StringUtil.addSuffix(borderFamily, "-n"), StringUtil.addSuffix(borderFamily, "-ne"), StringUtil.addSuffix(borderFamily, "-w")); } else { Template.appendHtml(out, "<div {{id=\"@id\"}} {{class=\"@class\"}} " + "{{style=\"background: @background;\"}}>\n", properties); } if (layout != null) { Dataset data = new Dataset(); for (Section child : children) { data.set(child.getId(), child); } if (extraChildren != null) { for (Section child : extraChildren) { data.set(child.getId(), child); } } layout.render(cr, data); } else { for (Section child: children) { child.render(cr); } if (extraChildren != null) { for (Section child: extraChildren) { child.render(cr); } } } // Render the portion of the container that comes after the children. if (borderFamily != null) { Template.appendHtml(out, " </td>\n" + " <td style=\"background-image: " + "url(@1); " + "background-repeat: repeat-y;\">" + "</td>\n" + " </tr>\n" + " <tr style=\"line-height: 0px;\">\n" + " <td><img src=\"@2\" alt=\"\" />" + "</td>\n" + " <td style=\"background-image: " + "url(@3); " + "background-repeat: repeat-x;\">" + "</td>\n" + " <td><img src=\"@4\" alt=\"\" />" + "</td>\n" + " </tr>\n" + "</table>\n", properties, StringUtil.addSuffix(borderFamily, "-e"), StringUtil.addSuffix(borderFamily, "-sw"), StringUtil.addSuffix(borderFamily, "-s"), StringUtil.addSuffix(borderFamily, "-se")); } else { out.append("</div>\n"); } Template.appendHtml(out, "<!-- End CompoundSection {{@id}} -->\n", properties); }
diff --git a/uk.ac.gda.core/src/gda/device/detector/countertimer/TfgScalerWithLogValues.java b/uk.ac.gda.core/src/gda/device/detector/countertimer/TfgScalerWithLogValues.java index f96484f0e..19863fd94 100644 --- a/uk.ac.gda.core/src/gda/device/detector/countertimer/TfgScalerWithLogValues.java +++ b/uk.ac.gda.core/src/gda/device/detector/countertimer/TfgScalerWithLogValues.java @@ -1,172 +1,173 @@ /*- * Copyright © 2009 Diamond Light Source Ltd. * * This file is part of GDA. * * GDA is free software: you can redistribute it and/or modify it under the * terms of the GNU General Public License version 3 as published by the Free * Software Foundation. * * GDA is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along * with GDA. If not, see <http://www.gnu.org/licenses/>. */ package gda.device.detector.countertimer; import gda.device.DeviceException; import org.apache.commons.lang.ArrayUtils; /** * A version of TfgScaler for Spectroscopy Ionchambers which assumes it has output channels (time),I0,It,Iref. * <p> * It has optional additional channels ln(I0/It) and ln(I0/Iref) It also reads the dark current at the scan start. */ public class TfgScalerWithLogValues extends TfgScalerWithDarkCurrent { public static final String LNI0IT_LABEL = "lnI0It"; public static final String LNITIREF_LABEL = "lnItIref"; private boolean outputLogValues = false; // add ln(I0/It) and ln(I0/Iref) to the output public TfgScalerWithLogValues() { super(); } /** * @return Returns the outputLogValues. */ public boolean isOutputLogValues() { return outputLogValues; } /** * When set to true ln(I0/It) and ln(I0/Iref) will be added to the output columns * * @param outputLogValues * The outputLogValues to set. */ public void setOutputLogValues(boolean outputLogValues) { this.outputLogValues = outputLogValues; // adjust the extraNmaes and outputFormat arrays if (!configured) { return; } if (outputLogValues) { if (!ArrayUtils.contains(extraNames, LNI0IT_LABEL)) { extraNames = (String[]) ArrayUtils.add(extraNames, LNI0IT_LABEL); outputFormat = (String[]) ArrayUtils.add(outputFormat, "%.4g"); } if (!ArrayUtils.contains(extraNames, LNITIREF_LABEL)) { extraNames = (String[]) ArrayUtils.add(extraNames, LNITIREF_LABEL); outputFormat = (String[]) ArrayUtils.add(outputFormat, "%.4g"); } } else { + int numInputs = inputNames.length; if (ArrayUtils.contains(extraNames, LNI0IT_LABEL)) { int index = ArrayUtils.indexOf(extraNames, LNI0IT_LABEL); extraNames = (String[]) ArrayUtils.remove(extraNames, index); - outputFormat = (String[]) ArrayUtils.remove(outputFormat, index); + outputFormat = (String[]) ArrayUtils.remove(outputFormat, index + numInputs); } if (ArrayUtils.contains(extraNames, LNITIREF_LABEL)) { int index = ArrayUtils.indexOf(extraNames, LNITIREF_LABEL); extraNames = (String[]) ArrayUtils.remove(extraNames, index); - outputFormat = (String[]) ArrayUtils.remove(outputFormat, index); + outputFormat = (String[]) ArrayUtils.remove(outputFormat, index + numInputs); } } } @Override public int getTotalChans() throws DeviceException { int cols = scaler.getDimension()[0]; if (numChannelsToRead != null) { cols = numChannelsToRead; } if (timeChannelRequired) { cols++; } if (outputLogValues) { cols += 2; } if (isTFGv2()) { cols--; } return cols; } @Override public double[] readout() throws DeviceException { double[] output = super.readout(); return performCorrections(output); } protected double[] performCorrections(double[] output) throws DeviceException { if (getDarkCurrent() != null) { output = adjustForDarkCurrent(output, getCollectionTime()); } if (outputLogValues) { output = appendLogValues(output); } return output; } @Override public double[] readFrame(int frame) throws DeviceException { // For legacy XAFS scans the time channel is in column 1 double[] output = super.readFrame(frame); return performCorrections(output); } protected double[] appendLogValues(double[] output) { Double[] logs = new Double[2]; // find which col is which I0, It and Iref Double[] values = getI0ItIRef(output); // NOTE Assumes that the order of the data (time, I0, It, Iref...) // for dark current does not change. logs[0] = Math.log(values[0] / values[1]); logs[1] = Math.log(values[1] / values[2]); // always return a numerical value if (logs[0].isInfinite() || logs[0].isNaN()) { logs[0] = 0.0; } if (logs[1].isInfinite() || logs[1].isNaN()) { logs[1] = 0.0; } // append to output array output = correctCounts(output, values); output = ArrayUtils.add(output, logs[0]); output = ArrayUtils.add(output, logs[1]); return output; } /* * This should only be called when outputLogValues is set to true. */ private Double[] getI0ItIRef(double[] data) { if (timeChannelRequired) { return new Double[] { data[1], data[2], data[3] }; } return new Double[] { data[0], data[1], data[2] }; } private double[] correctCounts(final double[] output, final Double[] counts) { final int outIndex = (timeChannelRequired) ? 1 : 0; for (int i = 0; i < counts.length; i++) { output[i + outIndex] = counts[i]; } return output; } }
false
true
public void setOutputLogValues(boolean outputLogValues) { this.outputLogValues = outputLogValues; // adjust the extraNmaes and outputFormat arrays if (!configured) { return; } if (outputLogValues) { if (!ArrayUtils.contains(extraNames, LNI0IT_LABEL)) { extraNames = (String[]) ArrayUtils.add(extraNames, LNI0IT_LABEL); outputFormat = (String[]) ArrayUtils.add(outputFormat, "%.4g"); } if (!ArrayUtils.contains(extraNames, LNITIREF_LABEL)) { extraNames = (String[]) ArrayUtils.add(extraNames, LNITIREF_LABEL); outputFormat = (String[]) ArrayUtils.add(outputFormat, "%.4g"); } } else { if (ArrayUtils.contains(extraNames, LNI0IT_LABEL)) { int index = ArrayUtils.indexOf(extraNames, LNI0IT_LABEL); extraNames = (String[]) ArrayUtils.remove(extraNames, index); outputFormat = (String[]) ArrayUtils.remove(outputFormat, index); } if (ArrayUtils.contains(extraNames, LNITIREF_LABEL)) { int index = ArrayUtils.indexOf(extraNames, LNITIREF_LABEL); extraNames = (String[]) ArrayUtils.remove(extraNames, index); outputFormat = (String[]) ArrayUtils.remove(outputFormat, index); } } }
public void setOutputLogValues(boolean outputLogValues) { this.outputLogValues = outputLogValues; // adjust the extraNmaes and outputFormat arrays if (!configured) { return; } if (outputLogValues) { if (!ArrayUtils.contains(extraNames, LNI0IT_LABEL)) { extraNames = (String[]) ArrayUtils.add(extraNames, LNI0IT_LABEL); outputFormat = (String[]) ArrayUtils.add(outputFormat, "%.4g"); } if (!ArrayUtils.contains(extraNames, LNITIREF_LABEL)) { extraNames = (String[]) ArrayUtils.add(extraNames, LNITIREF_LABEL); outputFormat = (String[]) ArrayUtils.add(outputFormat, "%.4g"); } } else { int numInputs = inputNames.length; if (ArrayUtils.contains(extraNames, LNI0IT_LABEL)) { int index = ArrayUtils.indexOf(extraNames, LNI0IT_LABEL); extraNames = (String[]) ArrayUtils.remove(extraNames, index); outputFormat = (String[]) ArrayUtils.remove(outputFormat, index + numInputs); } if (ArrayUtils.contains(extraNames, LNITIREF_LABEL)) { int index = ArrayUtils.indexOf(extraNames, LNITIREF_LABEL); extraNames = (String[]) ArrayUtils.remove(extraNames, index); outputFormat = (String[]) ArrayUtils.remove(outputFormat, index + numInputs); } } }
diff --git a/sql12/app/src/net/sourceforge/squirrel_sql/client/session/mainpanel/ResultTab.java b/sql12/app/src/net/sourceforge/squirrel_sql/client/session/mainpanel/ResultTab.java index 2f4efb1b6..6a3aeca76 100755 --- a/sql12/app/src/net/sourceforge/squirrel_sql/client/session/mainpanel/ResultTab.java +++ b/sql12/app/src/net/sourceforge/squirrel_sql/client/session/mainpanel/ResultTab.java @@ -1,604 +1,604 @@ package net.sourceforge.squirrel_sql.client.session.mainpanel; /* * Copyright (C) 2001-2004 Johan Compagner * [email protected] * * Modifications Copyright (C) 2003-2004 Jason Height * * Modifications copyright (C) 2004 Colin Bell * [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.NumberFormat; import javax.swing.*; import net.sourceforge.squirrel_sql.fw.datasetviewer.*; import net.sourceforge.squirrel_sql.fw.gui.MultipleLineLabel; import net.sourceforge.squirrel_sql.fw.id.IHasIdentifier; import net.sourceforge.squirrel_sql.fw.id.IIdentifier; import net.sourceforge.squirrel_sql.fw.util.StringManager; import net.sourceforge.squirrel_sql.fw.util.StringManagerFactory; import net.sourceforge.squirrel_sql.fw.util.StringUtilities; import net.sourceforge.squirrel_sql.client.IApplication; import net.sourceforge.squirrel_sql.client.action.SquirrelAction; import net.sourceforge.squirrel_sql.client.gui.builders.UIFactory; import net.sourceforge.squirrel_sql.client.session.ISession; import net.sourceforge.squirrel_sql.client.session.SQLExecutionInfo; import net.sourceforge.squirrel_sql.client.session.EditableSqlCheck; import net.sourceforge.squirrel_sql.client.session.properties.SessionProperties; public class ResultTab extends JPanel implements IHasIdentifier { /** Uniquely identifies this ResultTab. */ private IIdentifier _id; /** Current session. */ private ISession _session; /** SQL Execution information. */ private SQLExecutionInfo _exInfo; /** Panel displaying the SQL results. */ private IDataSetViewer _resultSetOutput; /** Panel displaying the SQL results meta data. */ private IDataSetViewer _metaDataOutput; /** Scroll pane for <TT>_resultSetOutput</TT>. */ private JScrollPane _resultSetSp = new JScrollPane(); /** Scroll pane for <TT>_metaDataOutput</TT>. */ private JScrollPane _metaDataSp = new JScrollPane(); /** Tabbed pane containing the SQL results the the results meta data. */ private JTabbedPane _tp; /** <TT>SQLExecuterPanel</TT> that this tab is showing results for. */ private SQLResultExecuterPanel _sqlPanel; /** Label shows the current SQL script. */ private JLabel _currentSqlLbl = new JLabel(); /** The SQL execurtes, cleaned up for display. */ private String _sql; /** Panel showing the query information. */ private QueryInfoPanel _queryInfoPanel = new QueryInfoPanel(); /** Listener to the sessions properties. */ private PropertyChangeListener _propsListener; private boolean _allowEditing; private IDataSetUpdateableTableModel _creator; private ResultSetDataSet _rsds; /** Internationalized strings for this class. */ private static final StringManager s_stringMgr = StringManagerFactory.getStringManager(ResultTab.class); private ResultTabListener _resultTabListener; /** * Ctor. * * @param session Current session. * @param sqlPanel <TT>SQLResultExecuterPanel</TT> that this tab is * showing results for. * @param id Unique ID for this object. * * @thrown IllegalArgumentException * Thrown if a <TT>null</TT> <TT>ISession</TT>, * <<TT>SQLResultExecuterPanel</TT> or <TT>IIdentifier</TT> passed. */ public ResultTab(ISession session, SQLResultExecuterPanel sqlPanel, IIdentifier id, SQLExecutionInfo exInfo, IDataSetUpdateableTableModel creator, ResultTabListener resultTabListener) throws IllegalArgumentException { super(); _resultTabListener = resultTabListener; if (session == null) { throw new IllegalArgumentException("Null ISession passed"); } if (sqlPanel == null) { throw new IllegalArgumentException("Null SQLPanel passed"); } if (id == null) { throw new IllegalArgumentException("Null IIdentifier passed"); } _session = session; _sqlPanel = sqlPanel; _id = id; reInit(creator, exInfo); createGUI(); propertiesHaveChanged(null); } public void reInit(IDataSetUpdateableTableModel creator, SQLExecutionInfo exInfo) { _creator = creator; _creator.addListener(new DataSetUpdateableTableModelListener() { public void forceEditMode(boolean mode) { onForceEditMode(mode); } }); _allowEditing = new EditableSqlCheck(exInfo).allowsEditing(); final SessionProperties props = _session.getProperties(); if (_allowEditing) { _resultSetOutput = BaseDataSetViewerDestination.getInstance(props.getSQLResultsOutputClassName(), _creator); } else { // sql contains columns from multiple tables, // so we cannot use all of the columns in a WHERE clause // and it becomes difficult to know which table (or tables!) an // edited column belongs to. Therefore limit the output // to be read-only _resultSetOutput = BaseDataSetViewerDestination.getInstance( props.getReadOnlySQLResultsOutputClassName(), null); } _resultSetSp.setViewportView(_resultSetOutput.getComponent()); _resultSetSp.setRowHeader(null); if (_session.getProperties().getShowResultsMetaData()) { _metaDataOutput = BaseDataSetViewerDestination.getInstance(props.getMetaDataOutputClassName(), null); _metaDataSp.setViewportView(_metaDataOutput.getComponent()); _metaDataSp.setRowHeader(null); } } /** * Panel is being added to its parent. Setup any required listeners. */ public void addNotify() { super.addNotify(); if (_propsListener == null) { _propsListener = new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { propertiesHaveChanged(evt); } }; _session.getProperties().addPropertyChangeListener(_propsListener); } } /** * Panel is being removed from its parent. Remove any required listeners. */ public void removeNotify() { super.removeNotify(); if (_propsListener != null) { _session.getProperties().removePropertyChangeListener(_propsListener); _propsListener = null; } } /** * Show the results from the passed <TT>IDataSet</TT>. * * @param rsds <TT>ResultSetDataSet</TT> to show results for. * @param mdds <TT>ResultSetMetaDataDataSet</TT> for rsds. * @param exInfo Execution info. * * @throws IllegalArgumentException * Thrown if <tt>null</tt> <tt>SQLExecutionInfo</tt> passed. * * @throws DataSetException * Thrown if error occured processing dataset. */ public void showResults(ResultSetDataSet rsds, ResultSetMetaDataDataSet mdds, SQLExecutionInfo exInfo) throws DataSetException { _exInfo = exInfo; _sql = StringUtilities.cleanString(exInfo.getSQL()); // Display the result set. _resultSetOutput.show(rsds, null); _rsds = rsds; final int rowCount = _resultSetOutput.getRowCount(); final int maxRows =_exInfo.getMaxRows(); if (maxRows > 0 && rowCount >= maxRows) { String buf = _sql.replaceAll("&", "&amp;"); buf = buf.replaceAll("<", "&lt;"); buf = buf.replaceAll("<", "&gt;"); buf = buf.replaceAll("\"", "&quot;"); // i18n[ResultTab.limitMessage=Limited to <font color='red'> {0} </font> rows] String limitMsg = s_stringMgr.getString("ResultTab.limitMessage", new Integer(rowCount)); _currentSqlLbl.setText("<html><pre>&nbsp;" + limitMsg + ";&nbsp;&nbsp;" + buf + "</pre></html>"); } else { _currentSqlLbl.setText(_sql); } // Display the result set metadata. if (mdds != null && _metaDataOutput != null) { _metaDataOutput.show(mdds, null); // Why null?? } exInfo.resultsProcessingComplete(); // And the query info. _queryInfoPanel.load(rsds, rowCount, exInfo); } /** * Clear results and current SQL script. */ public void clear() { if (_metaDataOutput != null) { _metaDataOutput.clear(); } if (_resultSetOutput != null) { _resultSetOutput.clear(); } _exInfo = null; _currentSqlLbl.setText(""); _sql = ""; } /** * Return the current SQL script. * * @return Current SQL script. */ public String getSqlString() { return _exInfo != null ? _exInfo.getSQL() : null; } /** * Return the current SQL script with control characters removed. * * @return Current SQL script. */ public String getViewableSqlString() { return StringUtilities.cleanString(getSqlString()); } /** * Return the title for this tab. */ public String getTitle() { String title = _sql; if (title.length() < 20) { return title; } return title.substring(0, 15); } /** * Close this tab. */ public void closeTab() { add(_tp, BorderLayout.CENTER); _sqlPanel.closeTab(this); } public void returnToTabbedPane() { add(_tp, BorderLayout.CENTER); _sqlPanel.returnToTabbedPane(this); } public Component getOutputComponent() { return _tp; } /** * Session properties have changed so update GUI if required. * * @param propertyName Name of property that has changed. */ private void propertiesHaveChanged(PropertyChangeEvent evt) { SessionProperties props = _session.getProperties(); if (evt == null || evt.getPropertyName().equals( SessionProperties.IPropertyNames.SQL_RESULTS_TAB_PLACEMENT)) { _tp.setTabPlacement(props.getSQLResultsTabPlacement()); } } private void onForceEditMode(boolean editable) { try { if(editable) { if (_allowEditing) { _resultSetOutput = BaseDataSetViewerDestination.getInstance(SessionProperties.IDataSetDestinations.EDITABLE_TABLE, _creator); _resultSetSp.setViewportView(_resultSetOutput.getComponent()); _resultSetSp.setRowHeader(null); _rsds.resetCursor(); _resultSetOutput.show(_rsds, null); } else { // i18n[ResultTab.cannotedit=This SQL can not be edited.] String msg = s_stringMgr.getString("ResultTab.cannotedit"); JOptionPane.showMessageDialog(_session.getApplication().getMainFrame(), msg); } } else { SessionProperties props = _session.getProperties(); String readOnlyOutput = props.getReadOnlySQLResultsOutputClassName(); _resultSetOutput = BaseDataSetViewerDestination.getInstance(readOnlyOutput, _creator); _resultSetSp.setViewportView(_resultSetOutput.getComponent()); _resultSetSp.setRowHeader(null); _rsds.resetCursor(); _resultSetOutput.show(_rsds, null); } } catch (DataSetException e) { throw new RuntimeException(e); } } private void createGUI() { // final Resources rsrc = _session.getApplication().getResources(); setLayout(new BorderLayout()); int sqlResultsTabPlacement = _session.getProperties().getSQLResultsTabPlacement(); _tp = UIFactory.getInstance().createTabbedPane(sqlResultsTabPlacement); JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); panel2.setLayout(new GridLayout(1, 3, 0, 0)); panel2.add(new TabButton(new RerunAction(_session.getApplication()))); panel2.add(new TabButton(new CreateResultTabFrameAction(_session.getApplication()))); panel2.add(new TabButton(new CloseAction())); panel1.setLayout(new BorderLayout()); panel1.add(panel2, BorderLayout.EAST); panel1.add(_currentSqlLbl, BorderLayout.CENTER); add(panel1, BorderLayout.NORTH); add(_tp, BorderLayout.CENTER); _resultSetSp.setBorder(BorderFactory.createEmptyBorder()); // i18n[ResultTab.resultsTabTitle=Results] String resultsTabTitle = s_stringMgr.getString("ResultTab.resultsTabTitle"); _tp.addTab(resultsTabTitle, _resultSetSp); if (_session.getProperties().getShowResultsMetaData()) { _metaDataSp.setBorder(BorderFactory.createEmptyBorder()); // i18n[ResultTab.metadataTabTitle=MetaData] String metadataTabTitle = s_stringMgr.getString("ResultTab.metadataTabTitle"); _tp.addTab(metadataTabTitle, _metaDataSp); } final JScrollPane sp = new JScrollPane(_queryInfoPanel); sp.setBorder(BorderFactory.createEmptyBorder()); // i18n[ResultTab.infoTabTitle=Info] String infoTabTitle = s_stringMgr.getString("ResultTab.infoTabTitle"); _tp.addTab(infoTabTitle, sp); } private final class TabButton extends JButton { TabButton(Action action) { super(action); setMargin(new Insets(0, 0, 0, 0)); setBorderPainted(false); setText(""); } } private class CloseAction extends SquirrelAction { CloseAction() { super( _session.getApplication(), _session.getApplication().getResources()); } public void actionPerformed(ActionEvent evt) { closeTab(); } } private class CreateResultTabFrameAction extends SquirrelAction { CreateResultTabFrameAction(IApplication app) { super(app, app.getResources()); } public void actionPerformed(ActionEvent evt) { _sqlPanel.createWindow(ResultTab.this); } } public class RerunAction extends SquirrelAction { RerunAction(IApplication app) { super(app, app.getResources()); } public void actionPerformed(ActionEvent evt) { _resultTabListener.rerunSQL(_exInfo.getSQL(), ResultTab.this); } } /** * @see IHasIdentifier#getIdentifier() */ public IIdentifier getIdentifier() { return _id; } private static class QueryInfoPanel extends JPanel { private MultipleLineLabel _queryLbl = new MultipleLineLabel(); private JLabel _rowCountLbl = new JLabel(); private JLabel _executedLbl = new JLabel(); private JLabel _elapsedLbl = new JLabel(); QueryInfoPanel() { super(); createGUI(); } void load(ResultSetDataSet rsds, int rowCount, SQLExecutionInfo exInfo) { _queryLbl.setText(StringUtilities.cleanString(exInfo.getSQL())); _rowCountLbl.setText(String.valueOf(rowCount)); _executedLbl.setText(exInfo.getSQLExecutionStartTime().toString()); _elapsedLbl.setText(formatElapsedTime(exInfo)); } private String formatElapsedTime(SQLExecutionInfo exInfo) { final NumberFormat nbrFmt = NumberFormat.getNumberInstance(); double executionLength = exInfo.getSQLExecutionElapsedMillis() / 1000.0; double outputLength = exInfo.getResultsProcessingElapsedMillis() / 1000.0; String totalTime = nbrFmt.format(executionLength + outputLength); String queryTime = nbrFmt.format(executionLength); String outputTime = nbrFmt.format(outputLength); // i18n[ResultTab.elapsedTime=Total: {0}, SQL query: {1}, Building output: {2}] String elapsedTime = s_stringMgr.getString("ResultTab.elapsedTime", new String[] { totalTime, queryTime, outputTime}); return elapsedTime; } private void createGUI() { setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridwidth = 1; gbc.weightx = 0; gbc.gridx = 0; gbc.gridy = 0; gbc.insets = new Insets(5, 10, 5, 10); gbc.fill = GridBagConstraints.HORIZONTAL; // i18n[ResultTab.executedLabel=Executed:] String label = s_stringMgr.getString("ResultTab.executedLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.rowCountLabel=Row Count:] label = s_stringMgr.getString("ResultTab.rowCountLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.statementLabel=SQL:] label = s_stringMgr.getString("ResultTab.statementLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.elapsedTimeLabel=Elapsed Time (seconds):] - label = s_stringMgr.getString("ResultTab.statementLabel"); + label = s_stringMgr.getString("ResultTab.elapsedTimeLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.gridx = 1; gbc.gridy = 0; add(_executedLbl, gbc); ++gbc.gridy; add(_rowCountLbl, gbc); ++gbc.gridy; add(_queryLbl, gbc); ++gbc.gridy; add(_elapsedLbl, gbc); } } }
true
true
private void createGUI() { setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridwidth = 1; gbc.weightx = 0; gbc.gridx = 0; gbc.gridy = 0; gbc.insets = new Insets(5, 10, 5, 10); gbc.fill = GridBagConstraints.HORIZONTAL; // i18n[ResultTab.executedLabel=Executed:] String label = s_stringMgr.getString("ResultTab.executedLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.rowCountLabel=Row Count:] label = s_stringMgr.getString("ResultTab.rowCountLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.statementLabel=SQL:] label = s_stringMgr.getString("ResultTab.statementLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.elapsedTimeLabel=Elapsed Time (seconds):] label = s_stringMgr.getString("ResultTab.statementLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.gridx = 1; gbc.gridy = 0; add(_executedLbl, gbc); ++gbc.gridy; add(_rowCountLbl, gbc); ++gbc.gridy; add(_queryLbl, gbc); ++gbc.gridy; add(_elapsedLbl, gbc); }
private void createGUI() { setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridwidth = 1; gbc.weightx = 0; gbc.gridx = 0; gbc.gridy = 0; gbc.insets = new Insets(5, 10, 5, 10); gbc.fill = GridBagConstraints.HORIZONTAL; // i18n[ResultTab.executedLabel=Executed:] String label = s_stringMgr.getString("ResultTab.executedLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.rowCountLabel=Row Count:] label = s_stringMgr.getString("ResultTab.rowCountLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.statementLabel=SQL:] label = s_stringMgr.getString("ResultTab.statementLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); ++gbc.gridy; // i18n[ResultTab.elapsedTimeLabel=Elapsed Time (seconds):] label = s_stringMgr.getString("ResultTab.elapsedTimeLabel"); add(new JLabel(label, SwingConstants.RIGHT), gbc); gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.weightx = 1; gbc.gridx = 1; gbc.gridy = 0; add(_executedLbl, gbc); ++gbc.gridy; add(_rowCountLbl, gbc); ++gbc.gridy; add(_queryLbl, gbc); ++gbc.gridy; add(_elapsedLbl, gbc); }
diff --git a/tests/balle/strategy/StrategyFactoryTest.java b/tests/balle/strategy/StrategyFactoryTest.java index bf73a7a..cf3df9f 100644 --- a/tests/balle/strategy/StrategyFactoryTest.java +++ b/tests/balle/strategy/StrategyFactoryTest.java @@ -1,23 +1,23 @@ package balle.strategy; import org.junit.Test; public class StrategyFactoryTest { /** * This is more an integration test than a unit test. Given available * designators, the strategy factory should be able to create all of them * and not raise UnknownDesignatorException * * @throws UnknownDesignatorException */ @Test public void testAvailableDesignators() throws UnknownDesignatorException { String[] availableDesignators = StrategyFactory.availableDesignators(); for (String designator : availableDesignators) { // An actual test - StrategyFactory.createClass(designator, null, null); + StrategyFactory.createClass(designator); } } }
true
true
public void testAvailableDesignators() throws UnknownDesignatorException { String[] availableDesignators = StrategyFactory.availableDesignators(); for (String designator : availableDesignators) { // An actual test StrategyFactory.createClass(designator, null, null); } }
public void testAvailableDesignators() throws UnknownDesignatorException { String[] availableDesignators = StrategyFactory.availableDesignators(); for (String designator : availableDesignators) { // An actual test StrategyFactory.createClass(designator); } }
diff --git a/src/dark/core/common/DarkMain.java b/src/dark/core/common/DarkMain.java index 0b5366cd..9f3e92c6 100644 --- a/src/dark/core/common/DarkMain.java +++ b/src/dark/core/common/DarkMain.java @@ -1,338 +1,338 @@ package dark.core.common; import java.awt.Color; import java.io.File; import java.util.Arrays; import net.minecraft.block.Block; import net.minecraft.item.ItemStack; import net.minecraftforge.common.Configuration; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.oredict.OreDictionary; import universalelectricity.prefab.TranslationHelper; import universalelectricity.prefab.ore.OreGenReplaceStone; import universalelectricity.prefab.ore.OreGenerator; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLLog; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.Mod.Instance; import cpw.mods.fml.common.Mod.Metadata; import cpw.mods.fml.common.ModMetadata; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStoppingEvent; import cpw.mods.fml.common.network.NetworkMod; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.relauncher.Side; import dark.api.reciepes.MachineRecipeHandler; import dark.core.common.blocks.BlockBasalt; import dark.core.common.blocks.BlockColorGlass; import dark.core.common.blocks.BlockColorGlowGlass; import dark.core.common.blocks.BlockColorSand; import dark.core.common.blocks.BlockGasOre; import dark.core.common.blocks.BlockOre; import dark.core.common.blocks.BlockOre.OreData; import dark.core.common.blocks.GasOreGenerator; import dark.core.common.blocks.ItemBlockColored; import dark.core.common.blocks.ItemBlockOre; import dark.core.common.items.EnumMaterial; import dark.core.common.items.EnumOrePart; import dark.core.common.items.ItemBattery; import dark.core.common.items.ItemColoredDust; import dark.core.common.items.ItemCommonTool; import dark.core.common.items.ItemOreDirv; import dark.core.common.items.ItemParts; import dark.core.common.items.ItemParts.Parts; import dark.core.common.items.ItemReadoutTools; import dark.core.common.items.ItemWrench; import dark.core.common.machines.BlockBasicMachine; import dark.core.common.machines.BlockDebug; import dark.core.common.machines.BlockSolarPanel; import dark.core.common.transmit.BlockWire; import dark.core.common.transmit.ItemBlockWire; import dark.core.helpers.PacketDataWatcher; import dark.core.network.PacketHandler; import dark.core.prefab.ItemBlockHolder; import dark.core.prefab.ModPrefab; import dark.core.prefab.fluids.EnumGas; import dark.core.prefab.machine.BlockMulti; import dark.core.prefab.machine.TileEntityNBTContainer; import dark.core.prefab.vehicles.EntityTestCar; import dark.core.prefab.vehicles.ItemVehicleSpawn; import dark.core.registration.ModObjectRegistry; /** @author HangCow, DarkGuardsman */ @Mod(modid = DarkMain.MOD_ID, name = DarkMain.MOD_NAME, version = DarkMain.VERSION, dependencies = "after:BuildCraft|Energy", useMetadata = true) @NetworkMod(channels = { DarkMain.CHANNEL }, clientSideRequired = true, serverSideRequired = false, packetHandler = PacketHandler.class) public class DarkMain extends ModPrefab { // @Mod Prerequisites public static final String MAJOR_VERSION = "@MAJOR@"; public static final String MINOR_VERSION = "@MINOR@"; public static final String REVIS_VERSION = "@REVIS@"; public static final String BUILD_VERSION = "@BUILD@"; public static final String VERSION = MAJOR_VERSION + "." + MINOR_VERSION + "." + REVIS_VERSION + "." + BUILD_VERSION; // @Mod public static final String MOD_ID = "DarkCore"; public static final String MOD_NAME = "Darks CoreMachine"; @SidedProxy(clientSide = "dark.core.client.ClientProxy", serverSide = "dark.core.common.CommonProxy") public static CommonProxy proxy; public static final String CHANNEL = "DarkPackets"; @Metadata(DarkMain.MOD_ID) public static ModMetadata meta; /** Main config file */ public static final Configuration CONFIGURATION = new Configuration(new File(Loader.instance().getConfigDir(), "Dark/TheDarkMachine.cfg")); private static final String[] LANGUAGES_SUPPORTED = new String[] { "en_US" }; /** Can over pressure of devices do area damage */ public static boolean overPressureDamage, zeroRendering, zeroAnimation, zeroGraphics; public static BlockMulti blockMulti; @Instance(MOD_ID) private static DarkMain instance; public static CoreRecipeLoader recipeLoader; public static final String[] dyeColorNames = new String[] { "Black", "Red", "Green", "Brown", "Blue", "Purple", "Cyan", "Silver", "Gray", "Pink", "Lime", "Yellow", "LightBlue", "Magenta", "Orange", "White" }; public static final Color[] dyeColors = new Color[] { Color.black, Color.red, Color.green, new Color(139, 69, 19), Color.BLUE, new Color(75, 0, 130), Color.cyan, new Color(192, 192, 192), Color.gray, Color.pink, new Color(0, 255, 0), Color.yellow, new Color(135, 206, 250), Color.magenta, Color.orange, Color.white }; public static DarkMain getInstance() { if (instance == null) { instance = new DarkMain(); } return instance; } @EventHandler @Override public void preInit(FMLPreInitializationEvent event) { instance = this; super.preInit(event); NetworkRegistry.instance().registerGuiHandler(this, proxy); MinecraftForge.EVENT_BUS.register(PacketDataWatcher.instance); proxy.preInit(); } @EventHandler @Override public void init(FMLInitializationEvent event) { super.init(event); EntityRegistry.registerGlobalEntityID(EntityTestCar.class, "TestCar", EntityRegistry.findGlobalUniqueEntityId()); EntityRegistry.registerModEntity(EntityTestCar.class, "TestCar", 60, this, 64, 1, true); for (EnumGas gas : EnumGas.values()) { FluidRegistry.registerFluid(gas.getGas()); if (CoreRecipeLoader.blockGas != null) { gas.getGas().setBlockID(CoreRecipeLoader.blockGas); } } if (CoreRecipeLoader.blockGas != null) { GameRegistry.registerWorldGenerator(new GasOreGenerator()); } if (CoreRecipeLoader.blockOre != null) { for (OreData data : OreData.values()) { if (data.doWorldGen) { OreGenReplaceStone gen = data.getGeneratorSettings(); if (gen != null) { OreGenerator.addOre(gen); } } } } if (CoreRecipeLoader.itemParts != null) { for (Parts part : Parts.values()) { OreDictionary.registerOre(part.name, new ItemStack(CoreRecipeLoader.itemParts, 1, part.ordinal())); } } if (CoreRecipeLoader.itemMetals != null) { MinecraftForge.EVENT_BUS.register(CoreRecipeLoader.itemMetals); //Ore material recipe loop for (EnumMaterial mat : EnumMaterial.values()) { if (mat.shouldCreateItem(EnumOrePart.INGOTS)) { - OreDictionary.registerOre(mat.simpleName + "ingot", mat.getStack(EnumOrePart.INGOTS, 1)); - OreDictionary.registerOre("ingot" + mat.simpleName, mat.getStack(EnumOrePart.INGOTS, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.INGOTS), mat.getStack(EnumOrePart.INGOTS, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.INGOTS), mat.getStack(EnumOrePart.INGOTS, 1)); } if (mat.shouldCreateItem(EnumOrePart.RUBBLE)) { - OreDictionary.registerOre(mat.simpleName + "rubble", mat.getStack(EnumOrePart.RUBBLE, 1)); - OreDictionary.registerOre("rubble" + mat.simpleName, mat.getStack(EnumOrePart.RUBBLE, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.RUBBLE), mat.getStack(EnumOrePart.RUBBLE, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.RUBBLE), mat.getStack(EnumOrePart.RUBBLE, 1)); } if (mat.shouldCreateItem(EnumOrePart.DUST)) { - OreDictionary.registerOre(mat.simpleName + "dust", mat.getStack(EnumOrePart.DUST, 1)); - OreDictionary.registerOre("dust" + mat.simpleName, mat.getStack(EnumOrePart.DUST, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.DUST), mat.getStack(EnumOrePart.DUST, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.DUST), mat.getStack(EnumOrePart.DUST, 1)); } if (mat.shouldCreateItem(EnumOrePart.SCRAPS)) { - OreDictionary.registerOre(mat.simpleName + "scraps", mat.getStack(EnumOrePart.SCRAPS, 1)); - OreDictionary.registerOre("scraps" + mat.simpleName, mat.getStack(EnumOrePart.SCRAPS, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.SCRAPS), mat.getStack(EnumOrePart.SCRAPS, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.SCRAPS), mat.getStack(EnumOrePart.SCRAPS, 1)); } if (mat.shouldCreateItem(EnumOrePart.TUBE)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.TUBE), mat.getStack(EnumOrePart.TUBE, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.TUBE), mat.getStack(EnumOrePart.TUBE, 1)); } if (mat.shouldCreateItem(EnumOrePart.ROD)) { - OreDictionary.registerOre(mat.simpleName + "rod", mat.getStack(EnumOrePart.ROD, 1)); - OreDictionary.registerOre("rod" + mat.simpleName, mat.getStack(EnumOrePart.ROD, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.ROD), mat.getStack(EnumOrePart.ROD, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.ROD), mat.getStack(EnumOrePart.ROD, 1)); } if (mat.shouldCreateItem(EnumOrePart.PLATES)) { - OreDictionary.registerOre(mat.simpleName + "plate", mat.getStack(EnumOrePart.PLATES, 1)); - OreDictionary.registerOre("plate" + mat.simpleName, mat.getStack(EnumOrePart.PLATES, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.PLATES), mat.getStack(EnumOrePart.PLATES, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.PLATES), mat.getStack(EnumOrePart.PLATES, 1)); } if (mat.shouldCreateItem(EnumOrePart.GEARS)) { - OreDictionary.registerOre(mat.simpleName + "gear", mat.getStack(EnumOrePart.GEARS, 1)); - OreDictionary.registerOre("gear" + mat.simpleName, mat.getStack(EnumOrePart.GEARS, 1)); + OreDictionary.registerOre(mat.getOreName(EnumOrePart.GEARS), mat.getStack(EnumOrePart.GEARS, 1)); + OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.GEARS), mat.getStack(EnumOrePart.GEARS, 1)); } } } FMLLog.info(" Loaded: " + TranslationHelper.loadLanguages(LANGUAGE_PATH, LANGUAGES_SUPPORTED) + " Languages."); proxy.init(); } @EventHandler @Override public void postInit(FMLPostInitializationEvent event) { super.postInit(event); proxy.postInit(); if (CoreRecipeLoader.itemParts instanceof ItemParts) { DMCreativeTab.tabMining.itemStack = new ItemStack(CoreRecipeLoader.itemParts.itemID, 1, ItemParts.Parts.MiningIcon.ordinal()); } if (CoreRecipeLoader.itemMetals instanceof ItemOreDirv) { DMCreativeTab.tabIndustrial.itemStack = EnumMaterial.getStack(EnumMaterial.IRON, EnumOrePart.GEARS, 1); } MachineRecipeHandler.parseOreNames(CONFIGURATION); } @Override public void registerObjects() { if (recipeLoader == null) { recipeLoader = new CoreRecipeLoader(); } /* CONFIGS */ CONFIGURATION.load(); GameRegistry.registerTileEntity(TileEntityNBTContainer.class, "DMNBTSaveBlock"); if (FMLCommonHandler.instance().getEffectiveSide() == Side.CLIENT) { DarkMain.zeroAnimation = CONFIGURATION.get("Graphics", "DisableAllAnimation", false, "Disables active animations by any non-active models").getBoolean(false); DarkMain.zeroRendering = CONFIGURATION.get("Graphics", "DisableAllRendering", false, "Replaces all model renderers with single block forms").getBoolean(false); DarkMain.zeroGraphics = CONFIGURATION.get("Graphics", "DisableAllGraphics", false, "Disables extra effects that models and renders have. Such as particles, and text").getBoolean(false); } /* BLOCKS */ Block m = ModObjectRegistry.createNewBlock("DMBlockMulti", DarkMain.MOD_ID, BlockMulti.class, false); if (m instanceof BlockMulti) { blockMulti = (BlockMulti) m; } CoreRecipeLoader.basicMachine = ModObjectRegistry.createNewBlock("DMBlockBasicMachine", DarkMain.MOD_ID, BlockBasicMachine.class, ItemBlockHolder.class); CoreRecipeLoader.blockOre = ModObjectRegistry.createNewBlock("DMBlockOre", DarkMain.MOD_ID, BlockOre.class, ItemBlockOre.class); CoreRecipeLoader.blockWire = ModObjectRegistry.createNewBlock("DMBlockWire", DarkMain.MOD_ID, BlockWire.class, ItemBlockWire.class); CoreRecipeLoader.blockDebug = ModObjectRegistry.createNewBlock("DMBlockDebug", DarkMain.MOD_ID, BlockDebug.class, ItemBlockHolder.class); CoreRecipeLoader.blockStainGlass = ModObjectRegistry.createNewBlock("DMBlockStainedGlass", DarkMain.MOD_ID, BlockColorGlass.class, ItemBlockColored.class); CoreRecipeLoader.blockColorSand = ModObjectRegistry.createNewBlock("DMBlockColorSand", DarkMain.MOD_ID, BlockColorSand.class, ItemBlockColored.class); CoreRecipeLoader.blockBasalt = ModObjectRegistry.createNewBlock("DMBlockBasalt", DarkMain.MOD_ID, BlockBasalt.class, ItemBlockColored.class); CoreRecipeLoader.blockGlowGlass = ModObjectRegistry.createNewBlock("DMBlockGlowGlass", DarkMain.MOD_ID, BlockColorGlowGlass.class, ItemBlockColored.class); CoreRecipeLoader.blockSolar = ModObjectRegistry.createNewBlock("DMBlockSolar", DarkMain.MOD_ID, BlockSolarPanel.class, ItemBlockHolder.class); CoreRecipeLoader.blockGas = ModObjectRegistry.createNewBlock("DMBlockGas", DarkMain.MOD_ID, BlockGasOre.class, ItemBlockHolder.class); /* ITEMS */ CoreRecipeLoader.itemTool = ModObjectRegistry.createNewItem("DMReadoutTools", DarkMain.MOD_ID, ItemReadoutTools.class, true); CoreRecipeLoader.itemMetals = ModObjectRegistry.createNewItem("DMOreDirvParts", DarkMain.MOD_ID, ItemOreDirv.class, true); CoreRecipeLoader.battery = ModObjectRegistry.createNewItem("DMItemBattery", DarkMain.MOD_ID, ItemBattery.class, true); CoreRecipeLoader.wrench = ModObjectRegistry.createNewItem("DMWrench", DarkMain.MOD_ID, ItemWrench.class, true); CoreRecipeLoader.itemParts = ModObjectRegistry.createNewItem("DMCraftingParts", DarkMain.MOD_ID, ItemParts.class, true); CoreRecipeLoader.itemGlowingSand = ModObjectRegistry.createNewItem("DMItemGlowingSand", DarkMain.MOD_ID, ItemColoredDust.class, true); CoreRecipeLoader.itemDiggingTool = ModObjectRegistry.createNewItem("ItemDiggingTools", DarkMain.MOD_ID, ItemCommonTool.class, true); CoreRecipeLoader.itemVehicleTest = ModObjectRegistry.createNewItem("ItemVehicleTest", DarkMain.MOD_ID, ItemVehicleSpawn.class, true); CONFIGURATION.save(); } @Override public void loadModMeta() { /* MCMOD.INFO FILE BUILDER? */ meta.modId = MOD_ID; meta.name = MOD_NAME; meta.description = "Main mod for several of the mods created by DarkGuardsman and his team. Adds basic features, functions, ores, items, and blocks"; meta.url = "http://www.universalelectricity.com/coremachine"; meta.logoFile = TEXTURE_DIRECTORY + "GP_Banner.png"; meta.version = VERSION; meta.authorList = Arrays.asList(new String[] { "DarkGuardsman", "HangCow", "Elrath18", "Archadia" }); meta.credits = "Please see the website."; meta.autogenerated = false; } @ForgeSubscribe public void onWorldSave(WorldEvent.Save event) { //SaveManager.save(!event.world.isRemote); } @EventHandler public void serverStopping(FMLServerStoppingEvent event) { //SaveManager.save(true); } @Override public String getDomain() { return "dark"; } @Override public void loadRecipes() { if (recipeLoader == null) { recipeLoader = new CoreRecipeLoader(); } recipeLoader.loadRecipes(); } }
false
true
public void init(FMLInitializationEvent event) { super.init(event); EntityRegistry.registerGlobalEntityID(EntityTestCar.class, "TestCar", EntityRegistry.findGlobalUniqueEntityId()); EntityRegistry.registerModEntity(EntityTestCar.class, "TestCar", 60, this, 64, 1, true); for (EnumGas gas : EnumGas.values()) { FluidRegistry.registerFluid(gas.getGas()); if (CoreRecipeLoader.blockGas != null) { gas.getGas().setBlockID(CoreRecipeLoader.blockGas); } } if (CoreRecipeLoader.blockGas != null) { GameRegistry.registerWorldGenerator(new GasOreGenerator()); } if (CoreRecipeLoader.blockOre != null) { for (OreData data : OreData.values()) { if (data.doWorldGen) { OreGenReplaceStone gen = data.getGeneratorSettings(); if (gen != null) { OreGenerator.addOre(gen); } } } } if (CoreRecipeLoader.itemParts != null) { for (Parts part : Parts.values()) { OreDictionary.registerOre(part.name, new ItemStack(CoreRecipeLoader.itemParts, 1, part.ordinal())); } } if (CoreRecipeLoader.itemMetals != null) { MinecraftForge.EVENT_BUS.register(CoreRecipeLoader.itemMetals); //Ore material recipe loop for (EnumMaterial mat : EnumMaterial.values()) { if (mat.shouldCreateItem(EnumOrePart.INGOTS)) { OreDictionary.registerOre(mat.simpleName + "ingot", mat.getStack(EnumOrePart.INGOTS, 1)); OreDictionary.registerOre("ingot" + mat.simpleName, mat.getStack(EnumOrePart.INGOTS, 1)); } if (mat.shouldCreateItem(EnumOrePart.RUBBLE)) { OreDictionary.registerOre(mat.simpleName + "rubble", mat.getStack(EnumOrePart.RUBBLE, 1)); OreDictionary.registerOre("rubble" + mat.simpleName, mat.getStack(EnumOrePart.RUBBLE, 1)); } if (mat.shouldCreateItem(EnumOrePart.DUST)) { OreDictionary.registerOre(mat.simpleName + "dust", mat.getStack(EnumOrePart.DUST, 1)); OreDictionary.registerOre("dust" + mat.simpleName, mat.getStack(EnumOrePart.DUST, 1)); } if (mat.shouldCreateItem(EnumOrePart.SCRAPS)) { OreDictionary.registerOre(mat.simpleName + "scraps", mat.getStack(EnumOrePart.SCRAPS, 1)); OreDictionary.registerOre("scraps" + mat.simpleName, mat.getStack(EnumOrePart.SCRAPS, 1)); } if (mat.shouldCreateItem(EnumOrePart.TUBE)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.TUBE), mat.getStack(EnumOrePart.TUBE, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.TUBE), mat.getStack(EnumOrePart.TUBE, 1)); } if (mat.shouldCreateItem(EnumOrePart.ROD)) { OreDictionary.registerOre(mat.simpleName + "rod", mat.getStack(EnumOrePart.ROD, 1)); OreDictionary.registerOre("rod" + mat.simpleName, mat.getStack(EnumOrePart.ROD, 1)); } if (mat.shouldCreateItem(EnumOrePart.PLATES)) { OreDictionary.registerOre(mat.simpleName + "plate", mat.getStack(EnumOrePart.PLATES, 1)); OreDictionary.registerOre("plate" + mat.simpleName, mat.getStack(EnumOrePart.PLATES, 1)); } if (mat.shouldCreateItem(EnumOrePart.GEARS)) { OreDictionary.registerOre(mat.simpleName + "gear", mat.getStack(EnumOrePart.GEARS, 1)); OreDictionary.registerOre("gear" + mat.simpleName, mat.getStack(EnumOrePart.GEARS, 1)); } } } FMLLog.info(" Loaded: " + TranslationHelper.loadLanguages(LANGUAGE_PATH, LANGUAGES_SUPPORTED) + " Languages."); proxy.init(); }
public void init(FMLInitializationEvent event) { super.init(event); EntityRegistry.registerGlobalEntityID(EntityTestCar.class, "TestCar", EntityRegistry.findGlobalUniqueEntityId()); EntityRegistry.registerModEntity(EntityTestCar.class, "TestCar", 60, this, 64, 1, true); for (EnumGas gas : EnumGas.values()) { FluidRegistry.registerFluid(gas.getGas()); if (CoreRecipeLoader.blockGas != null) { gas.getGas().setBlockID(CoreRecipeLoader.blockGas); } } if (CoreRecipeLoader.blockGas != null) { GameRegistry.registerWorldGenerator(new GasOreGenerator()); } if (CoreRecipeLoader.blockOre != null) { for (OreData data : OreData.values()) { if (data.doWorldGen) { OreGenReplaceStone gen = data.getGeneratorSettings(); if (gen != null) { OreGenerator.addOre(gen); } } } } if (CoreRecipeLoader.itemParts != null) { for (Parts part : Parts.values()) { OreDictionary.registerOre(part.name, new ItemStack(CoreRecipeLoader.itemParts, 1, part.ordinal())); } } if (CoreRecipeLoader.itemMetals != null) { MinecraftForge.EVENT_BUS.register(CoreRecipeLoader.itemMetals); //Ore material recipe loop for (EnumMaterial mat : EnumMaterial.values()) { if (mat.shouldCreateItem(EnumOrePart.INGOTS)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.INGOTS), mat.getStack(EnumOrePart.INGOTS, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.INGOTS), mat.getStack(EnumOrePart.INGOTS, 1)); } if (mat.shouldCreateItem(EnumOrePart.RUBBLE)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.RUBBLE), mat.getStack(EnumOrePart.RUBBLE, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.RUBBLE), mat.getStack(EnumOrePart.RUBBLE, 1)); } if (mat.shouldCreateItem(EnumOrePart.DUST)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.DUST), mat.getStack(EnumOrePart.DUST, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.DUST), mat.getStack(EnumOrePart.DUST, 1)); } if (mat.shouldCreateItem(EnumOrePart.SCRAPS)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.SCRAPS), mat.getStack(EnumOrePart.SCRAPS, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.SCRAPS), mat.getStack(EnumOrePart.SCRAPS, 1)); } if (mat.shouldCreateItem(EnumOrePart.TUBE)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.TUBE), mat.getStack(EnumOrePart.TUBE, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.TUBE), mat.getStack(EnumOrePart.TUBE, 1)); } if (mat.shouldCreateItem(EnumOrePart.ROD)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.ROD), mat.getStack(EnumOrePart.ROD, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.ROD), mat.getStack(EnumOrePart.ROD, 1)); } if (mat.shouldCreateItem(EnumOrePart.PLATES)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.PLATES), mat.getStack(EnumOrePart.PLATES, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.PLATES), mat.getStack(EnumOrePart.PLATES, 1)); } if (mat.shouldCreateItem(EnumOrePart.GEARS)) { OreDictionary.registerOre(mat.getOreName(EnumOrePart.GEARS), mat.getStack(EnumOrePart.GEARS, 1)); OreDictionary.registerOre(mat.getOreNameReverse(EnumOrePart.GEARS), mat.getStack(EnumOrePart.GEARS, 1)); } } } FMLLog.info(" Loaded: " + TranslationHelper.loadLanguages(LANGUAGE_PATH, LANGUAGES_SUPPORTED) + " Languages."); proxy.init(); }
diff --git a/src/master/src/org/drftpd/vfs/DirectoryHandle.java b/src/master/src/org/drftpd/vfs/DirectoryHandle.java index 0b47412b..9f394edc 100644 --- a/src/master/src/org/drftpd/vfs/DirectoryHandle.java +++ b/src/master/src/org/drftpd/vfs/DirectoryHandle.java @@ -1,810 +1,808 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * DrFTPD is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.vfs; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.drftpd.GlobalContext; import org.drftpd.exceptions.FileExistsException; import org.drftpd.exceptions.SlaveUnavailableException; import org.drftpd.io.PermissionDeniedException; import org.drftpd.master.RemoteSlave; import org.drftpd.slave.LightRemoteInode; import org.drftpd.usermanager.User; /** * @author zubov * @version $Id$ */ public class DirectoryHandle extends InodeHandle implements DirectoryHandleInterface { public DirectoryHandle(String path) { super(path); } /** * @param reason * @throws FileNotFoundException if this Directory does not exist */ public void abortAllTransfers(String reason) throws FileNotFoundException { for (FileHandle file : getFilesUnchecked()) { try { file.abortTransfers(reason); } catch (FileNotFoundException e) { } } } /** * Returns a DirectoryHandle for a possibly non-existant directory in this path * No verification to its existence is made * @param name * @return */ public DirectoryHandle getNonExistentDirectoryHandle(String name) { if (name.startsWith(VirtualFileSystem.separator)) { // absolute path, easy to handle return new DirectoryHandle(name); } // path must be relative return new DirectoryHandle(getPath() + VirtualFileSystem.separator + name); } /** * Returns a LinkHandle for a possibly non-existant directory in this path * No verification to its existence is made * @param name * @return */ public LinkHandle getNonExistentLinkHandle(String name) { return new LinkHandle(getPath() + VirtualFileSystem.separator + name); } /** * @see org.drftpd.vfs.InodleHandle#getInode() */ @Override public VirtualFileSystemDirectory getInode() throws FileNotFoundException { VirtualFileSystemInode inode = super.getInode(); if (inode instanceof VirtualFileSystemDirectory) { return (VirtualFileSystemDirectory) inode; } throw new ClassCastException( "DirectoryHandle object pointing to Inode:" + inode); } /** * @return all InodeHandles inside this dir. * @throws FileNotFoundException */ public Set<InodeHandle> getInodeHandles(User user) throws FileNotFoundException { Set<InodeHandle> inodes = getInodeHandlesUnchecked(); for (Iterator<InodeHandle> iter = inodes.iterator(); iter.hasNext();) { InodeHandle inode = iter.next(); try { checkHiddenPath(inode, user); } catch (FileNotFoundException e) { // file is hidden or a race just happened. iter.remove(); } } return inodes; } /** * @return all InodeHandles inside this dir. * @throws FileNotFoundException */ public Set<InodeHandle> getInodeHandlesUnchecked() throws FileNotFoundException { return getInode().getInodes(); } public ArrayList<FileHandle> getAllFilesRecursiveUnchecked() { ArrayList<FileHandle> files = new ArrayList<FileHandle>(); try { for (InodeHandle inode : getInodeHandlesUnchecked()) { if (inode.isFile()) { files.add((FileHandle) inode); } else if (inode.isDirectory()) { files.addAll(((DirectoryHandle)inode).getAllFilesRecursiveUnchecked()); } } } catch (FileNotFoundException e) { // oh well, we just won't have any files to add } return files; } /** * @return a set containing only the files of this dir. * (no links or directories included.) * @throws FileNotFoundException */ public Set<FileHandle> getFiles(User user) throws FileNotFoundException { return getFilesUnchecked(getInodeHandles(user)); } public Set<FileHandle> getFilesUnchecked() throws FileNotFoundException { return getFilesUnchecked(getInodeHandlesUnchecked()); } private Set<FileHandle> getFilesUnchecked(Set<InodeHandle> inodes) throws FileNotFoundException { Set<FileHandle> set = new HashSet<FileHandle>(); for (InodeHandle handle : getInode().getInodes()) { if (handle instanceof FileHandle) { set.add((FileHandle) handle); } } return (Set<FileHandle>) set; } /**. * This method *does* check for hiddens paths. * @return a set containing only the directories of this dir. (no links or files included.) * @throws FileNotFoundException */ public Set<DirectoryHandle> getDirectories(User user) throws FileNotFoundException { return getDirectoriesUnchecked(getInodeHandles(user)); } /** * This method does not check for hiddens paths. * @return a set containing only the directories of this dir. (no links or files included.) * @throws FileNotFoundException */ public Set<DirectoryHandle> getDirectoriesUnchecked() throws FileNotFoundException { return getDirectoriesUnchecked(getInodeHandlesUnchecked()); } /** * This method iterates through the given Set, removing non-Directory objects. * @return a set containing only the directories of this dir. (no links or files included.) * @throws FileNotFoundException */ private Set<DirectoryHandle> getDirectoriesUnchecked(Set<InodeHandle> inodes) throws FileNotFoundException { Set<DirectoryHandle> set = new HashSet<DirectoryHandle>(); for (InodeHandle handle : inodes) { if (handle instanceof DirectoryHandle) { set.add((DirectoryHandle) handle); } } return (Set<DirectoryHandle>) set; } /** * @return a set containing only the links of this dir. * (no directories or files included.) * @throws FileNotFoundException */ public Set<LinkHandle> getLinks(User user) throws FileNotFoundException { return getLinksUnchecked(getInodeHandles(user)); } public Set<LinkHandle> getLinksUnchecked() throws FileNotFoundException { return getLinksUnchecked(getInodeHandlesUnchecked()); } private Set<LinkHandle> getLinksUnchecked(Set<InodeHandle> inodes) throws FileNotFoundException { Set<LinkHandle> set = new HashSet<LinkHandle>(); for (Iterator<InodeHandle> iter = inodes.iterator(); iter .hasNext();) { InodeHandle handle = iter.next(); if (handle instanceof LinkHandle) { set.add((LinkHandle) handle); } } return (Set<LinkHandle>) set; } /** * @return true if the dir has offline files. * @throws FileNotFoundException */ public boolean hasOfflineFiles() throws FileNotFoundException { return getOfflineFiles().size() != 0; } /** * @return a set containing only the offline files of this dir. * @throws FileNotFoundException */ private Set<FileHandle> getOfflineFiles() throws FileNotFoundException { Set<FileHandle> allFiles = getFilesUnchecked(); Set<FileHandle> offlineFiles = new HashSet<FileHandle>(allFiles.size()); for (FileHandle file : allFiles) { if (!file.isAvailable()) offlineFiles.add(file); } return offlineFiles; } /** * @param name * @throws FileNotFoundException */ public InodeHandle getInodeHandle(String name, User user) throws FileNotFoundException { InodeHandle inode = getInodeHandleUnchecked(name); checkHiddenPath(inode, user); return inode; } public InodeHandle getInodeHandleUnchecked(String name) throws FileNotFoundException { VirtualFileSystemInode inode = getInode().getInodeByName(name); if (inode.isDirectory()) { return new DirectoryHandle(inode.getPath()); } else if (inode.isFile()) { return new FileHandle(inode.getPath()); } else if (inode.isLink()) { return new LinkHandle(inode.getPath()); } throw new IllegalStateException( "Not a directory, file, or link -- punt"); } public DirectoryHandle getDirectory(String name, User user) throws FileNotFoundException, ObjectNotValidException { DirectoryHandle dir = getDirectoryUnchecked(name); checkHiddenPath(dir, user); return dir; } public DirectoryHandle getDirectoryUnchecked(String name) throws FileNotFoundException, ObjectNotValidException { if (name.equals(VirtualFileSystem.separator)) { return new DirectoryHandle("/"); } logger.debug("getDirectory(" + name + ")"); if (name.equals("..")) { return getParent(); } else if (name.startsWith("../")) { // strip off the ../ return getParent().getDirectoryUnchecked(name.substring(3)); } else if (name.equals(".")) { return this; } else if (name.startsWith("./")) { return getDirectoryUnchecked(name.substring(2)); } InodeHandle handle = getInodeHandleUnchecked(name); if (handle.isDirectory()) { return (DirectoryHandle) handle; } if (handle.isLink()) { return ((LinkHandle) handle).getTargetDirectoryUnchecked(); } throw new ObjectNotValidException(name + " is not a directory"); } public FileHandle getFile(String name, User user) throws FileNotFoundException, ObjectNotValidException { FileHandle file = getFileUnchecked(name); checkHiddenPath(file.getParent(), user); return file; } public FileHandle getFileUnchecked(String name) throws FileNotFoundException, ObjectNotValidException { InodeHandle handle = getInodeHandleUnchecked(name); if (handle.isFile()) { return (FileHandle) handle; } else if (handle.isLink()) { LinkHandle link = (LinkHandle) handle; return link.getTargetFileUnchecked(); } throw new ObjectNotValidException(name + " is not a file"); } public LinkHandle getLink(String name, User user) throws FileNotFoundException, ObjectNotValidException { LinkHandle link = getLinkUnchecked(name); checkHiddenPath(link.getTargetInode(user), user); return link; } public LinkHandle getLinkUnchecked(String name) throws FileNotFoundException, ObjectNotValidException { InodeHandle handle = getInodeHandleUnchecked(name); if (handle.isLink()) { return (LinkHandle) handle; } throw new ObjectNotValidException(name + " is not a link"); } private void createRemergedFile(LightRemoteInode lrf, RemoteSlave rslave, boolean collision) throws IOException, SlaveUnavailableException { String name = lrf.getName(); if (collision) { name = lrf.getName() + ".collision." + rslave.getName(); rslave.simpleRename(getPath() + lrf.getPath(), getPath(), name); } FileHandle newFile = createFileUnchecked(name, "drftpd", "drftpd", rslave); newFile.setLastModified(lrf.lastModified()); newFile.setSize(lrf.length()); //newFile.setCheckSum(rslave.getCheckSumForPath(newFile.getPath())); // TODO Implement a Checksum queue on remerge newFile.setCheckSum(0); } public void remerge(List<LightRemoteInode> files, RemoteSlave rslave) throws IOException, SlaveUnavailableException { Iterator<LightRemoteInode> sourceIter = files.iterator(); // source comes pre-sorted from the slave List<InodeHandle> destinationList = null; try { destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked()); } catch (FileNotFoundException e) { - logger.debug("FileNotFoundException during remerge", e); // create directory for merging getParent().createDirectoryRecursive(getName()); // lets try this again, this time, if it doesn't work, we throw an // IOException up the chain destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked()); } Collections.sort(destinationList, VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR); Iterator<InodeHandle> destinationIter = destinationList.iterator(); LightRemoteInode source = null; InodeHandle destination = null; if (sourceIter.hasNext()) { source = sourceIter.next(); } if (destinationIter.hasNext()) { destination = destinationIter.next(); } while (true) { /*logger.debug("loop, [destination=" + (destination == null ? "null" : destination.getName()) + "][source=" + (source == null ? "null" : source.getName()) + "]"); */ // source & destination are set at the "next to process" one OR are // null and at the end of that list // case1 : source list is out, remove slave from all remaining // files/directories if (source == null) { while (destination != null) { // can removeSlave()'s from all types of Inodes, no type // checking needed destination.removeSlave(rslave); if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } } // all done, both lists are empty return; } // case2: destination list is out, add files if (destination == null) { while (source != null) { if (source.isFile()) { createRemergedFile(source, rslave, false); } else { throw new IOException( source + ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process"); } if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } // all done, both lists are empty return; } // both source and destination are non-null // we don't know which one is first alphabetically int compare = source.getName().compareToIgnoreCase( destination.getName()); // compare is < 0, source comes before destination // compare is > 0, source comes after destination // compare is == 0, they have the same name if (compare < 0) { // add the file createRemergedFile(source, rslave, false); // advance one runner if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } else if (compare > 0) { // remove the slave destination.removeSlave(rslave); // advance one runner if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } } else if (compare == 0) { if (destination.isLink()) { // this is bad, links don't exist on slaves // name collision if (source.isFile()) { createRemergedFile(source, rslave, true); logger.warn("In remerging " + rslave.getName() + ", a file on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a link on the master"); // set crc now? } else { // source.isDirectory() logger.warn("In remerging " + rslave.getName() + ", a directory on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a link on the master"); } } else if (source.isFile() && destination.isFile()) { // both files FileHandle destinationFile = (FileHandle) destination; /* long sourceCRC = rslave.getCheckSumForPath(getPath() + VirtualFileSystem.separator + source.getName()); long destinationCRC; try { destinationCRC = destinationFile.getCheckSum(); } catch (NoAvailableSlaveException e) { destinationCRC = 0L; } */ if (source.length() != destinationFile.getSize()) { // || (sourceCRC != destinationCRC && destinationCRC != 0L)) { // handle collision Set<RemoteSlave> rslaves = destinationFile.getSlaves(); if (rslaves.contains(rslave) && rslaves.size() == 1) { // size of the file has changed, but since this is the only slave with the file, just change the size destinationFile.setSize(source.length()); } else { if (rslaves.contains(rslave)) { // the master thought the slave had the file, it's not the same size anymore, remove it destinationFile.removeSlave(rslave); } createRemergedFile(source, rslave, true); logger.warn("In remerging " + rslave.getName() + ", a file on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a file on the master"); } } else { destinationFile.addSlave(rslave); } } else if (source.isDirectory() && destination.isDirectory()) { // this is good, do nothing other than take up this case - logger.debug("In remerge, directories were equal! (" + destination.getPath() + ")"); } else { // we have a directory/name collision, let's find which one // :) if (source.isDirectory()) { // & destination.isFile() // we don't care about directories on the slaves, let's // just skip it logger.warn("In remerging " + rslave.getName() + ", a directory on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a file on the master"); } else { // source.isFile() && destination.isDirectory() // handle collision createRemergedFile(source, rslave, true); // set crc now? } } // advance both runners, they were equal if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } } } /** * Shortcut to create "owner-less" directories. */ public DirectoryHandle createDirectorySystem(String name) throws FileExistsException, FileNotFoundException { return createDirectoryUnchecked(name, "drftpd", "drftpd"); } /** * Given a DirectoryHandle, it makes sure that this directory and all of its parent(s) exist * @param name * @throws FileExistsException * @throws FileNotFoundException */ public void createDirectoryRecursive(String name) throws FileExistsException, FileNotFoundException { DirectoryHandle dir = null; try { dir = createDirectorySystem(name); } catch (FileNotFoundException e) { getParent().createDirectoryRecursive(getName()); } catch (FileExistsException e) { throw new FileExistsException("Object already exists -- " + getPath() + VirtualFileSystem.separator + name); } if (dir == null) { dir = createDirectorySystem(name); } logger.debug("Created directory " + dir); } /** * Creates a Directory object in the FileSystem with this directory as its parent.<br> * This method does not check for permissions, so be careful while using it.<br> * @see For a checked way of creating dirs {@link #createFile(User, String, RemoteSlave)}; * @param user * @param group * @return the created directory. * @throws FileNotFoundException * @throws FileExistsException */ public DirectoryHandle createDirectoryUnchecked(String name, String user, String group) throws FileExistsException, FileNotFoundException { getInode().createDirectory(name, user, group); try { return getDirectoryUnchecked(name); } catch (FileNotFoundException e) { throw new RuntimeException("Something really funky happened, we just created it", e); } catch (ObjectNotValidException e) { throw new RuntimeException("Something really funky happened, we just created it", e); } } /** * Attempts to create a Directory in the FileSystem with this directory as parent. * @see For an unchecked way of creating dirs: {@link #createDirectoryUnchecked(String, String, String)} * @param user * @param name * @return the created directory. * @throws PermissionDeniedException if the given user is not allowed to create dirs. * @throws FileExistsException * @throws FileNotFoundException */ public DirectoryHandle createDirectory(User user, String name) throws PermissionDeniedException, FileExistsException, FileNotFoundException { if (user == null) { throw new PermissionDeniedException("User cannot be null"); } DirectoryHandle newDir = getNonExistentDirectoryHandle(name); checkHiddenPath(newDir, user); if (!getVFSPermissions().checkPathPermission("makedir", user, newDir)) { throw new PermissionDeniedException("You are not allowed to create a directory at "+ newDir.getParent()); } return createDirectoryUnchecked(name, user.getName(), user.getGroup()); } /** * Creates a File object in the FileSystem with this directory as its parent.<br> * This method does not check for permissions, so be careful while using it.<br> * @see For unchecked creating of files {@link #createFileUnchecked(String, String, String, RemoteSlave)} * @param name * @param user * @param group * @param initialSlave * @return the created file. * @throws FileExistsException * @throws FileNotFoundException */ public FileHandle createFileUnchecked(String name, String user, String group, RemoteSlave initialSlave) throws FileExistsException, FileNotFoundException { getInode().createFile(name, user, group, initialSlave.getName()); try { return getFileUnchecked(name); } catch (FileNotFoundException e) { throw new RuntimeException("Something really funky happened, we just created it", e); } catch (ObjectNotValidException e) { throw new RuntimeException("Something really funky happened, we just created it", e); } } /** * Attempts to create a File in the FileSystem having this directory as parent. * @param user * @param name * @param initialSlave * @return * @throws PermissionDeniedException if the user is not allowed to create a file in this dir. * @throws FileExistsException * @throws FileNotFoundException */ public FileHandle createFile(User user, String name, RemoteSlave initialSlave) throws PermissionDeniedException, FileExistsException, FileNotFoundException { if (user == null) { throw new PermissionDeniedException("User cannot be null"); } checkHiddenPath(this, user); if (!getVFSPermissions().checkPathPermission("upload", user, this)) { throw new PermissionDeniedException("You are not allowed to upload to "+ getParent()); } return createFileUnchecked(name, user.getName(), user.getGroup(), initialSlave); } /** * Creates a Link object in the FileSystem with this directory as its parent */ public LinkHandle createLinkUnchecked(String name, String target, String user, String group) throws FileExistsException, FileNotFoundException { getInode().createLink(name, target, user, group); try { return getLinkUnchecked(name); } catch (FileNotFoundException e) { throw new RuntimeException("Something really funky happened, we just created it", e); } catch (ObjectNotValidException e) { throw new RuntimeException("Something really funky happened, we just created it", e); } } public LinkHandle createLink(User user, String name, String target) throws FileExistsException, FileNotFoundException, PermissionDeniedException { if (user == null) { throw new PermissionDeniedException("User cannot be null"); } // check if this dir is hidden. checkHiddenPath(this, user); InodeHandle inode = getInodeHandle(target, user); // check if the target is hidden checkHiddenPath(inode, user); if (inode.isLink()) { throw new PermissionDeniedException("Impossible to point a link to a link"); } return createLinkUnchecked(name, target, user.getName(), user.getGroup()); } public boolean isRoot() { return equals(GlobalContext.getGlobalContext().getRoot()); } /** * For use during PRET * Returns a FileHandle for a possibly non-existant directory in this path * No verification to its existence is made * @param name * @return */ public FileHandle getNonExistentFileHandle(String argument) { if (argument.startsWith(VirtualFileSystem.separator)) { // absolute path, easy to handle return new FileHandle(argument); } // path must be relative return new FileHandle(getPath() + VirtualFileSystem.separator + argument); } public void removeSlave(RemoteSlave rslave) throws FileNotFoundException { boolean empty = isEmptyUnchecked(); for (InodeHandle inode : getInodeHandlesUnchecked()) { inode.removeSlave(rslave); } if (!empty && isEmptyUnchecked()) { // if it wasn't empty before, but is now, delete it deleteUnchecked(); } } public boolean isEmptyUnchecked() throws FileNotFoundException { return getInodeHandlesUnchecked().size() == 0; } public boolean isEmpty(User user) throws FileNotFoundException, PermissionDeniedException { // let's fetch the list of existent files inside this dir // if the dir does not exist, FileNotFoundException is thrown // if the dir exists the operation continues smoothly. getInode(); try { checkHiddenPath(this, user); } catch (FileNotFoundException e) { // either a race condition happened or the dir is hidden // cuz we just checked and the dir was here. throw new PermissionDeniedException("Unable to check if the directory is empty."); } return isEmptyUnchecked(); } @Override public boolean isDirectory() { return true; } @Override public boolean isFile() { return false; } @Override public boolean isLink() { return false; } @Override public void deleteUnchecked() throws FileNotFoundException { abortAllTransfers("Directory " + getPath() + " is being deleted"); GlobalContext.getGlobalContext().getSlaveManager().deleteOnAllSlaves(this); super.deleteUnchecked(); } public long validateSizeRecursive() throws FileNotFoundException { Set<InodeHandle> inodes = getInodeHandlesUnchecked(); long newSize = 0; long oldSize = getSize(); for (InodeHandle inode : inodes) { if (inode.isDirectory()) { ((DirectoryHandle) inode).validateSizeRecursive(); } newSize += inode.getSize(); } getInode().setSize(newSize); return oldSize - newSize; } }
false
true
public void remerge(List<LightRemoteInode> files, RemoteSlave rslave) throws IOException, SlaveUnavailableException { Iterator<LightRemoteInode> sourceIter = files.iterator(); // source comes pre-sorted from the slave List<InodeHandle> destinationList = null; try { destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked()); } catch (FileNotFoundException e) { logger.debug("FileNotFoundException during remerge", e); // create directory for merging getParent().createDirectoryRecursive(getName()); // lets try this again, this time, if it doesn't work, we throw an // IOException up the chain destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked()); } Collections.sort(destinationList, VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR); Iterator<InodeHandle> destinationIter = destinationList.iterator(); LightRemoteInode source = null; InodeHandle destination = null; if (sourceIter.hasNext()) { source = sourceIter.next(); } if (destinationIter.hasNext()) { destination = destinationIter.next(); } while (true) { /*logger.debug("loop, [destination=" + (destination == null ? "null" : destination.getName()) + "][source=" + (source == null ? "null" : source.getName()) + "]"); */ // source & destination are set at the "next to process" one OR are // null and at the end of that list // case1 : source list is out, remove slave from all remaining // files/directories if (source == null) { while (destination != null) { // can removeSlave()'s from all types of Inodes, no type // checking needed destination.removeSlave(rslave); if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } } // all done, both lists are empty return; } // case2: destination list is out, add files if (destination == null) { while (source != null) { if (source.isFile()) { createRemergedFile(source, rslave, false); } else { throw new IOException( source + ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process"); } if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } // all done, both lists are empty return; } // both source and destination are non-null // we don't know which one is first alphabetically int compare = source.getName().compareToIgnoreCase( destination.getName()); // compare is < 0, source comes before destination // compare is > 0, source comes after destination // compare is == 0, they have the same name if (compare < 0) { // add the file createRemergedFile(source, rslave, false); // advance one runner if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } else if (compare > 0) { // remove the slave destination.removeSlave(rslave); // advance one runner if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } } else if (compare == 0) { if (destination.isLink()) { // this is bad, links don't exist on slaves // name collision if (source.isFile()) { createRemergedFile(source, rslave, true); logger.warn("In remerging " + rslave.getName() + ", a file on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a link on the master"); // set crc now? } else { // source.isDirectory() logger.warn("In remerging " + rslave.getName() + ", a directory on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a link on the master"); } } else if (source.isFile() && destination.isFile()) { // both files FileHandle destinationFile = (FileHandle) destination; /* long sourceCRC = rslave.getCheckSumForPath(getPath() + VirtualFileSystem.separator + source.getName()); long destinationCRC; try { destinationCRC = destinationFile.getCheckSum(); } catch (NoAvailableSlaveException e) { destinationCRC = 0L; } */ if (source.length() != destinationFile.getSize()) { // || (sourceCRC != destinationCRC && destinationCRC != 0L)) { // handle collision Set<RemoteSlave> rslaves = destinationFile.getSlaves(); if (rslaves.contains(rslave) && rslaves.size() == 1) { // size of the file has changed, but since this is the only slave with the file, just change the size destinationFile.setSize(source.length()); } else { if (rslaves.contains(rslave)) { // the master thought the slave had the file, it's not the same size anymore, remove it destinationFile.removeSlave(rslave); } createRemergedFile(source, rslave, true); logger.warn("In remerging " + rslave.getName() + ", a file on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a file on the master"); } } else { destinationFile.addSlave(rslave); } } else if (source.isDirectory() && destination.isDirectory()) { // this is good, do nothing other than take up this case logger.debug("In remerge, directories were equal! (" + destination.getPath() + ")"); } else { // we have a directory/name collision, let's find which one // :) if (source.isDirectory()) { // & destination.isFile() // we don't care about directories on the slaves, let's // just skip it logger.warn("In remerging " + rslave.getName() + ", a directory on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a file on the master"); } else { // source.isFile() && destination.isDirectory() // handle collision createRemergedFile(source, rslave, true); // set crc now? } } // advance both runners, they were equal if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } } }
public void remerge(List<LightRemoteInode> files, RemoteSlave rslave) throws IOException, SlaveUnavailableException { Iterator<LightRemoteInode> sourceIter = files.iterator(); // source comes pre-sorted from the slave List<InodeHandle> destinationList = null; try { destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked()); } catch (FileNotFoundException e) { // create directory for merging getParent().createDirectoryRecursive(getName()); // lets try this again, this time, if it doesn't work, we throw an // IOException up the chain destinationList = new ArrayList<InodeHandle>(getInodeHandlesUnchecked()); } Collections.sort(destinationList, VirtualFileSystem.INODE_HANDLE_CASE_INSENSITIVE_COMPARATOR); Iterator<InodeHandle> destinationIter = destinationList.iterator(); LightRemoteInode source = null; InodeHandle destination = null; if (sourceIter.hasNext()) { source = sourceIter.next(); } if (destinationIter.hasNext()) { destination = destinationIter.next(); } while (true) { /*logger.debug("loop, [destination=" + (destination == null ? "null" : destination.getName()) + "][source=" + (source == null ? "null" : source.getName()) + "]"); */ // source & destination are set at the "next to process" one OR are // null and at the end of that list // case1 : source list is out, remove slave from all remaining // files/directories if (source == null) { while (destination != null) { // can removeSlave()'s from all types of Inodes, no type // checking needed destination.removeSlave(rslave); if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } } // all done, both lists are empty return; } // case2: destination list is out, add files if (destination == null) { while (source != null) { if (source.isFile()) { createRemergedFile(source, rslave, false); } else { throw new IOException( source + ".isDirectory() -- this shouldn't happen, this directory should already be created through a previous remerge process"); } if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } // all done, both lists are empty return; } // both source and destination are non-null // we don't know which one is first alphabetically int compare = source.getName().compareToIgnoreCase( destination.getName()); // compare is < 0, source comes before destination // compare is > 0, source comes after destination // compare is == 0, they have the same name if (compare < 0) { // add the file createRemergedFile(source, rslave, false); // advance one runner if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } else if (compare > 0) { // remove the slave destination.removeSlave(rslave); // advance one runner if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } } else if (compare == 0) { if (destination.isLink()) { // this is bad, links don't exist on slaves // name collision if (source.isFile()) { createRemergedFile(source, rslave, true); logger.warn("In remerging " + rslave.getName() + ", a file on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a link on the master"); // set crc now? } else { // source.isDirectory() logger.warn("In remerging " + rslave.getName() + ", a directory on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a link on the master"); } } else if (source.isFile() && destination.isFile()) { // both files FileHandle destinationFile = (FileHandle) destination; /* long sourceCRC = rslave.getCheckSumForPath(getPath() + VirtualFileSystem.separator + source.getName()); long destinationCRC; try { destinationCRC = destinationFile.getCheckSum(); } catch (NoAvailableSlaveException e) { destinationCRC = 0L; } */ if (source.length() != destinationFile.getSize()) { // || (sourceCRC != destinationCRC && destinationCRC != 0L)) { // handle collision Set<RemoteSlave> rslaves = destinationFile.getSlaves(); if (rslaves.contains(rslave) && rslaves.size() == 1) { // size of the file has changed, but since this is the only slave with the file, just change the size destinationFile.setSize(source.length()); } else { if (rslaves.contains(rslave)) { // the master thought the slave had the file, it's not the same size anymore, remove it destinationFile.removeSlave(rslave); } createRemergedFile(source, rslave, true); logger.warn("In remerging " + rslave.getName() + ", a file on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a file on the master"); } } else { destinationFile.addSlave(rslave); } } else if (source.isDirectory() && destination.isDirectory()) { // this is good, do nothing other than take up this case } else { // we have a directory/name collision, let's find which one // :) if (source.isDirectory()) { // & destination.isFile() // we don't care about directories on the slaves, let's // just skip it logger.warn("In remerging " + rslave.getName() + ", a directory on the slave (" + getPath() + VirtualFileSystem.separator + source.getName() + ") collided with a file on the master"); } else { // source.isFile() && destination.isDirectory() // handle collision createRemergedFile(source, rslave, true); // set crc now? } } // advance both runners, they were equal if (destinationIter.hasNext()) { destination = destinationIter.next(); } else { destination = null; } if (sourceIter.hasNext()) { source = sourceIter.next(); } else { source = null; } } } }
diff --git a/extensions/search/src/main/java/uk/co/tfd/sm/search/es/ContentEventListener.java b/extensions/search/src/main/java/uk/co/tfd/sm/search/es/ContentEventListener.java index 4db94b3..6d347a3 100644 --- a/extensions/search/src/main/java/uk/co/tfd/sm/search/es/ContentEventListener.java +++ b/extensions/search/src/main/java/uk/co/tfd/sm/search/es/ContentEventListener.java @@ -1,288 +1,293 @@ package uk.co.tfd.sm.search.es; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.logging.ErrorManager; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.Activate; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Deactivate; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.client.Client; import org.elasticsearch.client.action.bulk.BulkRequestBuilder; import org.elasticsearch.client.action.index.IndexRequestBuilder; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.inject.CreationException; import org.elasticsearch.common.inject.spi.Message; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.ImmutableSettings.Builder; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeBuilder; import org.osgi.service.event.Event; import org.osgi.service.event.EventConstants; import org.osgi.service.event.EventHandler; import org.sakaiproject.nakamura.api.lite.ClientPoolException; import org.sakaiproject.nakamura.api.lite.Repository; import org.sakaiproject.nakamura.api.lite.Session; import org.sakaiproject.nakamura.api.lite.StorageClientException; import org.sakaiproject.nakamura.api.lite.accesscontrol.AccessDeniedException; import org.sakaiproject.nakamura.api.lite.util.Iterables; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.co.tfd.sm.api.search.IndexingHandler; import uk.co.tfd.sm.api.search.InputDocument; import uk.co.tfd.sm.api.search.RepositorySession; import uk.co.tfd.sm.api.search.TopicIndexer; import com.google.common.collect.Maps; import com.google.common.collect.Sets; /** * Indexes content using elastic search. Driven by Events expected to be * synchronous inside transactions. * * @author ieb * */ @Component(immediate = true, metatype = true) @Service(value = { EventHandler.class, TopicIndexer.class }) public class ContentEventListener implements EventHandler, TopicIndexer { @Property(value = { "org/sakaiproject/nakamura/lite/*" }, propertyPrivate = true) static final String TOPICS = EventConstants.EVENT_TOPIC; private static final String[] DEFAULT_ESCLUSTER = { "host1:port", "host2:port" }; @Property(value = { "host1:port", "host2:port" }) private static final String PROP_ESCLUSTER = "ec-cluster-hosts"; @Property(boolValue = true, description = "If set to true, the ES node is embedded and joins the cluster") private static final String PROP_EMBEDED = "embeded"; private static final String DEFAULT_CLUSTER_NAME = "smc-cluster"; @Property(value = DEFAULT_CLUSTER_NAME, description = "Name of the elsastic search cluster to join when embedded") private static final String PROP_CLUSTER_NAME = "clustername"; @Property(boolValue = true, description = "If set to true, the ES node should serve local shards") private static final String PROP_LOCAL_SHARDS = "local-shards"; private static final Logger LOGGER = LoggerFactory .getLogger(ContentEventListener.class); private Map<String, Collection<IndexingHandler>> handlers = Maps .newConcurrentMap(); /** * A protective lock surrounding adding and removing keys from the handlers * map. THis is there because we could have 2 threads adding to the same key * at the same time. Its not there to protect the map itself or access to * iterators on the objects in the map as those changes are still atomic. * see usage for detail. */ private Object handlersLock = new Object(); private Client client; private Node node; @Reference private Repository repository; @Activate protected void activate(Map<String, Object> properties) throws IOException, ClientPoolException, StorageClientException, AccessDeniedException { try { Boolean embeded = Utils.get(properties.get(PROP_EMBEDED), true); Boolean withData = Utils.get(properties.get(PROP_LOCAL_SHARDS), true); String clusterName = Utils.get(properties.get(PROP_CLUSTER_NAME), DEFAULT_CLUSTER_NAME); if (client == null) { LOGGER.error("Thread context classloader is {} ", Thread.currentThread().getContextClassLoader()); // Elastic search needs to come up this class so unfortunately we have to set the context classloader // as it will use that by default Thread thisThread = Thread.currentThread(); ClassLoader classloader = thisThread.getContextClassLoader(); try { thisThread.setContextClassLoader(this.getClass().getClassLoader()); if (embeded) { node = NodeBuilder.nodeBuilder().data(withData) .clusterName(clusterName).build(); client = node.client(); } else { Builder settingsBuilder = ImmutableSettings.settingsBuilder(); settingsBuilder.put("cluster.name", clusterName); TransportClient tclient = new TransportClient( settingsBuilder.build()); String[] clusterHosts = Utils.get( properties.get(PROP_ESCLUSTER), DEFAULT_ESCLUSTER); for (String s : clusterHosts) { String[] h = StringUtils.split(s, ":"); tclient.addTransportAddress(new InetSocketTransportAddress( h[0], Integer.parseInt(h[1]))); } client = tclient; } } finally { thisThread.setContextClassLoader(classloader); } } } catch ( Exception e ) { LOGGER.error("Failed to start Elastic search {} ",e.getClass()); for ( StackTraceElement se : e.getStackTrace()) { LOGGER.error("Error {} {} {} {} ", new Object[]{se.getClassName(), se.getFileName(), se.getLineNumber(), se.getMethodName()}); } Throwable c = e.getCause(); while (c != null) { LOGGER.error("Caused By : {} ",e.getClass()); for ( StackTraceElement se : c.getStackTrace()) { LOGGER.error("Error {} {} {} {} ", new Object[]{se.getClassName(), se.getFileName(), se.getLineNumber(), se.getMethodName()}); } } LOGGER.error("End of cause "); if ( e instanceof CreationException ) { CreationException ce = (CreationException) e; for ( Message m : ce.getErrorMessages()) { LOGGER.error("Error message {} ",m.getMessage()); } LOGGER.error(e.getMessage()); } throw new RuntimeException(e); } } @Deactivate protected void deactivate(Map<String, Object> properties) throws IOException { if (client != null) { client.close(); client = null; } if (node != null) { node.close(); node = null; } } /** * Handles an event from OSGi and indexes it. The indexing operation should * only index metadata and not bodies. Indexing of bodies is performed by a * seperate thread. * * @see org.osgi.service.event.EventHandler#handleEvent(org.osgi.service.event.Event) */ public void handleEvent(Event event) { String topic = event.getTopic(); Session session = (Session) event.getProperty(Session.class.getName()); RepositorySession repositoryRession = null; Thread thisThread = Thread.currentThread(); ClassLoader classloader = thisThread.getContextClassLoader(); // ES might load classes so we had better set the context classloader. try { thisThread.setContextClassLoader(this.getClass().getClassLoader()); try { repositoryRession = new RepositorySessionImpl(session, repository); } catch (ClientPoolException e1) { LOGGER.error(e1.getMessage(), e1); return; } catch (StorageClientException e1) { LOGGER.error(e1.getMessage(), e1); return; } catch (AccessDeniedException e1) { LOGGER.error(e1.getMessage(), e1); return; } LOGGER.debug("Got Event {} {} ", event, handlers); Collection<IndexingHandler> contentIndexHandler = handlers .get(topic); if (contentIndexHandler != null && contentIndexHandler.size() > 0) { BulkRequestBuilder bulk = client.prepareBulk(); + int added = 0; for (IndexingHandler indexingHandler : contentIndexHandler) { Collection<InputDocument> documents = indexingHandler .getDocuments(repositoryRession, event); for (InputDocument in : documents) { if (in.isDelete()) { bulk.add(client.prepareDelete(in.getIndexName(), in.getDocumentType(), in.getDocumentId())); + added++; } else { try { IndexRequestBuilder r = client.prepareIndex( in.getIndexName(), in.getDocumentType(), in.getDocumentId()); XContentBuilder d = XContentFactory .jsonBuilder(); d = d.startObject(); for (Entry<String, Object> e : in.getKeyData()) { d = d.field(e.getKey(), e.getValue()); } r.setSource(d.endObject()); bulk.add(r); + added++; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } } } - BulkResponse resp = bulk.execute().actionGet(); - if (resp.hasFailures()) { - for (BulkItemResponse br : Iterables.adaptTo(resp - .iterator())) { - if (br.failed()) { - LOGGER.error("Failed {} {} ", br.getId(), - br.getFailureMessage()); - // not going to retry at the moment, just log. + if ( added > 0 ) { + BulkResponse resp = bulk.execute().actionGet(); + if (resp.hasFailures()) { + for (BulkItemResponse br : Iterables.adaptTo(resp + .iterator())) { + if (br.failed()) { + LOGGER.error("Failed {} {} ", br.getId(), + br.getFailureMessage()); + // not going to retry at the moment, just log. + } } } } } } finally { if (repositoryRession != null) { repositoryRession.logout(); } thisThread.setContextClassLoader(classloader); } } public void addHandler(String topic, IndexingHandler handler) { synchronized (handlersLock) { Collection<IndexingHandler> topicHandlers = handlers.get(topic); if (topicHandlers == null) { topicHandlers = Sets.newHashSet(); } else { // make a copy to avoid concurrency issues in the topicHandler topicHandlers = Sets.newHashSet(topicHandlers); } topicHandlers.add(handler); handlers.put(topic, topicHandlers); } } public void removeHandler(String topic, IndexingHandler handler) { synchronized (handlersLock) { Collection<IndexingHandler> topicHandlers = handlers.get(topic); if (topicHandlers != null && topicHandlers.size() > 0) { topicHandlers = Sets.newHashSet(topicHandlers); topicHandlers.remove(handler); handlers.put(topic, topicHandlers); } } } }
false
true
public void handleEvent(Event event) { String topic = event.getTopic(); Session session = (Session) event.getProperty(Session.class.getName()); RepositorySession repositoryRession = null; Thread thisThread = Thread.currentThread(); ClassLoader classloader = thisThread.getContextClassLoader(); // ES might load classes so we had better set the context classloader. try { thisThread.setContextClassLoader(this.getClass().getClassLoader()); try { repositoryRession = new RepositorySessionImpl(session, repository); } catch (ClientPoolException e1) { LOGGER.error(e1.getMessage(), e1); return; } catch (StorageClientException e1) { LOGGER.error(e1.getMessage(), e1); return; } catch (AccessDeniedException e1) { LOGGER.error(e1.getMessage(), e1); return; } LOGGER.debug("Got Event {} {} ", event, handlers); Collection<IndexingHandler> contentIndexHandler = handlers .get(topic); if (contentIndexHandler != null && contentIndexHandler.size() > 0) { BulkRequestBuilder bulk = client.prepareBulk(); for (IndexingHandler indexingHandler : contentIndexHandler) { Collection<InputDocument> documents = indexingHandler .getDocuments(repositoryRession, event); for (InputDocument in : documents) { if (in.isDelete()) { bulk.add(client.prepareDelete(in.getIndexName(), in.getDocumentType(), in.getDocumentId())); } else { try { IndexRequestBuilder r = client.prepareIndex( in.getIndexName(), in.getDocumentType(), in.getDocumentId()); XContentBuilder d = XContentFactory .jsonBuilder(); d = d.startObject(); for (Entry<String, Object> e : in.getKeyData()) { d = d.field(e.getKey(), e.getValue()); } r.setSource(d.endObject()); bulk.add(r); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } } } BulkResponse resp = bulk.execute().actionGet(); if (resp.hasFailures()) { for (BulkItemResponse br : Iterables.adaptTo(resp .iterator())) { if (br.failed()) { LOGGER.error("Failed {} {} ", br.getId(), br.getFailureMessage()); // not going to retry at the moment, just log. } } } } } finally { if (repositoryRession != null) { repositoryRession.logout(); } thisThread.setContextClassLoader(classloader); } }
public void handleEvent(Event event) { String topic = event.getTopic(); Session session = (Session) event.getProperty(Session.class.getName()); RepositorySession repositoryRession = null; Thread thisThread = Thread.currentThread(); ClassLoader classloader = thisThread.getContextClassLoader(); // ES might load classes so we had better set the context classloader. try { thisThread.setContextClassLoader(this.getClass().getClassLoader()); try { repositoryRession = new RepositorySessionImpl(session, repository); } catch (ClientPoolException e1) { LOGGER.error(e1.getMessage(), e1); return; } catch (StorageClientException e1) { LOGGER.error(e1.getMessage(), e1); return; } catch (AccessDeniedException e1) { LOGGER.error(e1.getMessage(), e1); return; } LOGGER.debug("Got Event {} {} ", event, handlers); Collection<IndexingHandler> contentIndexHandler = handlers .get(topic); if (contentIndexHandler != null && contentIndexHandler.size() > 0) { BulkRequestBuilder bulk = client.prepareBulk(); int added = 0; for (IndexingHandler indexingHandler : contentIndexHandler) { Collection<InputDocument> documents = indexingHandler .getDocuments(repositoryRession, event); for (InputDocument in : documents) { if (in.isDelete()) { bulk.add(client.prepareDelete(in.getIndexName(), in.getDocumentType(), in.getDocumentId())); added++; } else { try { IndexRequestBuilder r = client.prepareIndex( in.getIndexName(), in.getDocumentType(), in.getDocumentId()); XContentBuilder d = XContentFactory .jsonBuilder(); d = d.startObject(); for (Entry<String, Object> e : in.getKeyData()) { d = d.field(e.getKey(), e.getValue()); } r.setSource(d.endObject()); bulk.add(r); added++; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } } } if ( added > 0 ) { BulkResponse resp = bulk.execute().actionGet(); if (resp.hasFailures()) { for (BulkItemResponse br : Iterables.adaptTo(resp .iterator())) { if (br.failed()) { LOGGER.error("Failed {} {} ", br.getId(), br.getFailureMessage()); // not going to retry at the moment, just log. } } } } } } finally { if (repositoryRession != null) { repositoryRession.logout(); } thisThread.setContextClassLoader(classloader); } }
diff --git a/src/main/java/freemarker/core/Include.java b/src/main/java/freemarker/core/Include.java index f0634d5e..5bcbea7d 100644 --- a/src/main/java/freemarker/core/Include.java +++ b/src/main/java/freemarker/core/Include.java @@ -1,216 +1,216 @@ /* * Copyright (c) 2003 The Visigoth Software Society. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowledgement: * "This product includes software developed by the * Visigoth Software Society (http://www.visigoths.org/)." * Alternately, this acknowledgement may appear in the software itself, * if and wherever such third-party acknowledgements normally appear. * * 4. Neither the name "FreeMarker", "Visigoth", nor any of the names of the * project contributors may be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "FreeMarker" or "Visigoth" * nor may "FreeMarker" or "Visigoth" appear in their names * without prior written permission of the Visigoth Software Society. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE VISIGOTH SOFTWARE SOCIETY OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Visigoth Software Society. For more * information on the Visigoth Software Society, please see * http://www.visigoths.org/ */ package freemarker.core; import java.io.IOException; import freemarker.cache.TemplateCache; import freemarker.template.*; import freemarker.template.utility.StringUtil; import freemarker.template.utility.UndeclaredThrowableException; /** * An instruction that gets another template * and processes it within the current template. */ final class Include extends TemplateElement { private Expression includedTemplateName, encodingExp, parseExp; private String encoding; private boolean parse; private final String templatePath; /** * @param template the template that this <tt>Include</tt> is a part of. * @param includedTemplateName the name of the template to be included. * @param encodingExp the encoding to be used or null, if it is a default. * @param parseExp whether the template should be parsed (or is raw text) */ Include(Template template, Expression includedTemplateName, Expression encodingExp, Expression parseExp) throws ParseException { String templatePath1 = template.getName(); int lastSlash = templatePath1.lastIndexOf('/'); templatePath = lastSlash == -1 ? "" : templatePath1.substring(0, lastSlash + 1); this.includedTemplateName = includedTemplateName; if (encodingExp instanceof StringLiteral) { encoding = encodingExp.toString(); encoding = encoding.substring(1, encoding.length() -1); } else { this.encodingExp = encodingExp; } if(parseExp == null) { parse = true; } else if(parseExp.isLiteral()) { try { if (parseExp instanceof StringLiteral) { parse = StringUtil.getYesNo(parseExp.getStringValue(null)); } else { try { parse = parseExp.isTrue(null); } catch(NonBooleanException e) { throw new ParseException("Expected a boolean or string as the value of the parse attribute", parseExp); } } } catch(TemplateException e) { // evaluation of literals must not throw a TemplateException throw new UndeclaredThrowableException(e); } } else { this.parseExp = parseExp; } } void accept(Environment env) throws TemplateException, IOException { String templateNameString = includedTemplateName.getStringValue(env); if( templateNameString == null ) { String msg = "Error " + getStartLocation() + "The expression " + includedTemplateName + " is undefined."; throw new InvalidReferenceException(msg, env); } String enc = encoding; if (encoding == null && encodingExp != null) { enc = encodingExp.getStringValue(env); } boolean parse = this.parse; if (parseExp != null) { TemplateModel tm = parseExp.getAsTemplateModel(env); if(tm == null) { if(env.isClassicCompatible()) { parse = false; } else { parseExp.assertNonNull(tm, env); } } if (tm instanceof TemplateScalarModel) { parse = getYesNo(EvaluationUtil.getString((TemplateScalarModel)tm, parseExp, env)); } else { parse = parseExp.isTrue(env); } } Template includedTemplate; try { templateNameString = TemplateCache.getFullTemplatePath(env, templatePath, templateNameString); includedTemplate = env.getTemplateForInclusion(templateNameString, enc, parse); } catch (ParseException pe) { String msg = "Error parsing included template " - + templateNameString + "\n" + pe.getMessage(); + + StringUtil.jQuote(templateNameString) + ":\n" + pe.getMessage(); throw new TemplateException(msg, pe, env); } catch (IOException ioe) { String msg = "Error reading included file " - + templateNameString; + + StringUtil.jQuote(templateNameString) + ":\n" + ioe; throw new TemplateException(msg, ioe, env); } env.include(includedTemplate); } public String getCanonicalForm() { StringBuffer buf = new StringBuffer("<#include "); buf.append(includedTemplateName); if (encoding != null) { buf.append(" encoding=\""); buf.append(encodingExp.getCanonicalForm()); buf.append("\""); } if(parseExp != null) { buf.append(" parse=" + parseExp.getCanonicalForm()); } else if (!parse) { buf.append(" parse=false"); } buf.append("/>"); return buf.toString(); } public String getDescription() { return "include " + includedTemplateName; } private boolean getYesNo(String s) throws ParseException { try { return StringUtil.getYesNo(s); } catch (IllegalArgumentException iae) { throw new ParseException("Error " + getStartLocation() + "\nValue of include parse parameter " + "must be boolean or one of these strings: " + "\"n\", \"no\", \"f\", \"false\", \"y\", \"yes\", \"t\", \"true\"" + "\nFound: " + parseExp, parseExp); } } /* boolean heedsOpeningWhitespace() { return true; } boolean heedsTrailingWhitespace() { return true; } */ }
false
true
void accept(Environment env) throws TemplateException, IOException { String templateNameString = includedTemplateName.getStringValue(env); if( templateNameString == null ) { String msg = "Error " + getStartLocation() + "The expression " + includedTemplateName + " is undefined."; throw new InvalidReferenceException(msg, env); } String enc = encoding; if (encoding == null && encodingExp != null) { enc = encodingExp.getStringValue(env); } boolean parse = this.parse; if (parseExp != null) { TemplateModel tm = parseExp.getAsTemplateModel(env); if(tm == null) { if(env.isClassicCompatible()) { parse = false; } else { parseExp.assertNonNull(tm, env); } } if (tm instanceof TemplateScalarModel) { parse = getYesNo(EvaluationUtil.getString((TemplateScalarModel)tm, parseExp, env)); } else { parse = parseExp.isTrue(env); } } Template includedTemplate; try { templateNameString = TemplateCache.getFullTemplatePath(env, templatePath, templateNameString); includedTemplate = env.getTemplateForInclusion(templateNameString, enc, parse); } catch (ParseException pe) { String msg = "Error parsing included template " + templateNameString + "\n" + pe.getMessage(); throw new TemplateException(msg, pe, env); } catch (IOException ioe) { String msg = "Error reading included file " + templateNameString; throw new TemplateException(msg, ioe, env); } env.include(includedTemplate); }
void accept(Environment env) throws TemplateException, IOException { String templateNameString = includedTemplateName.getStringValue(env); if( templateNameString == null ) { String msg = "Error " + getStartLocation() + "The expression " + includedTemplateName + " is undefined."; throw new InvalidReferenceException(msg, env); } String enc = encoding; if (encoding == null && encodingExp != null) { enc = encodingExp.getStringValue(env); } boolean parse = this.parse; if (parseExp != null) { TemplateModel tm = parseExp.getAsTemplateModel(env); if(tm == null) { if(env.isClassicCompatible()) { parse = false; } else { parseExp.assertNonNull(tm, env); } } if (tm instanceof TemplateScalarModel) { parse = getYesNo(EvaluationUtil.getString((TemplateScalarModel)tm, parseExp, env)); } else { parse = parseExp.isTrue(env); } } Template includedTemplate; try { templateNameString = TemplateCache.getFullTemplatePath(env, templatePath, templateNameString); includedTemplate = env.getTemplateForInclusion(templateNameString, enc, parse); } catch (ParseException pe) { String msg = "Error parsing included template " + StringUtil.jQuote(templateNameString) + ":\n" + pe.getMessage(); throw new TemplateException(msg, pe, env); } catch (IOException ioe) { String msg = "Error reading included file " + StringUtil.jQuote(templateNameString) + ":\n" + ioe; throw new TemplateException(msg, ioe, env); } env.include(includedTemplate); }
diff --git a/src/org/fudgemsg/proto/c/CClassCode.java b/src/org/fudgemsg/proto/c/CClassCode.java index 5512d35..214ead5 100644 --- a/src/org/fudgemsg/proto/c/CClassCode.java +++ b/src/org/fudgemsg/proto/c/CClassCode.java @@ -1,1683 +1,1683 @@ /* * Copyright 2009 by OpenGamma Inc and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fudgemsg.proto.c; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.fudgemsg.FudgeTypeDictionary; import org.fudgemsg.UTF8; import org.fudgemsg.proto.Compiler; import org.fudgemsg.proto.EnumDefinition; import org.fudgemsg.proto.FieldDefinition; import org.fudgemsg.proto.FieldType; import org.fudgemsg.proto.IndentWriter; import org.fudgemsg.proto.LiteralValue; import org.fudgemsg.proto.MessageDefinition; import org.fudgemsg.proto.TaxonomyDefinition; import org.fudgemsg.proto.TypeDefinition; import org.fudgemsg.proto.EnumDefinition.Type; import org.fudgemsg.proto.LiteralValue.IntegerValue; /** * Code generator for the C Fudge implementation * * @author Andrew */ /* package */class CClassCode extends CStyleClassCode { /* package */static final CClassCode INSTANCE = new CClassCode(); private CClassCode() { super(blockCodeDelegate(new CBlockCode(literalCodeDelegate(CLiteralCode.INSTANCE))), ".h", ".c"); } @Override public void writeHeaderFileHeader(final Compiler.Context context, final File targetFile, final IndentWriter writer) throws IOException { super.writeHeaderFileHeader(context, targetFile, writer); writer.write("#include <fudge/message.h>"); writer.newLine(); writer.write("#ifdef __cplusplus"); writer.newLine(); writer.write("extern \"C\" {"); writer.newLine(); writer.write("#endif /* ifdef __cplusplus */"); writer.newLine(); } @Override public void writeHeaderFileFooter(final Compiler.Context context, final File targetFile, final IndentWriter writer) throws IOException { writer.write("#ifdef __cplusplus"); writer.newLine(); writer.write("}"); writer.newLine(); writer.write("#endif /* ifdef __cplusplus */"); writer.newLine(); super.writeHeaderFileFooter(context, targetFile, writer); } @Override public void writeImplementationFileHeader(final Compiler.Context context, final File targetFile, final IndentWriter writer) throws IOException { super.writeImplementationFileHeader(context, targetFile, writer); writer.write("#define FUDGE_INTERNAL 1"); writer.newLine(); writer.write("#include <malloc.h>"); writer.newLine(); writer.write("#include <string.h>"); writer.newLine(); } @Override public void beginClassHeaderDeclaration(final Compiler.Context context, final MessageDefinition message, final IndentWriter writer) throws IOException { super.beginClassHeaderDeclaration(context, message, writer); writer.write("typedef struct _" + getIdentifier(message) + " " + getIdentifier(message)); endStmt(writer); writer.write("struct _" + getIdentifier(message)); beginBlock(writer); // struct if (message.getExtends() != null) { writer.write("struct _" + getIdentifier(message.getExtends()) + " fudgeParent"); } else { writer.write("int fudgeStructSize"); } endStmt(writer); } @Override public void endClassHeaderDeclaration(final Compiler.Context context, final MessageDefinition message, final IndentWriter writer) throws IOException { endBlock(writer); // struct endStmt(writer); // Message field accessor/mutators for (FieldDefinition field : message.getFieldDefinitions()) { if (field.getOverride() != null) { field = field.getOverride(); writer.write("#define " + getIdentifier(message) + "_get" + camelCaseFieldName(field) + " " + getIdentifier(field.getOuterMessage()) + "_get" + camelCaseFieldName(field)); writer.newLine(); writer.write("#define " + getIdentifier(message) + "_set" + camelCaseFieldName(field) + " " + getIdentifier(field.getOuterMessage()) + "_set" + camelCaseFieldName(field)); writer.newLine(); if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.FUDGE_MSG_TYPE_ID) { writer.write("#define " + getIdentifier(message) + "_getFudgeMsg" + camelCaseFieldName(field) + " " + getIdentifier(field.getOuterMessage()) + "_getFudgeMsg" + camelCaseFieldName(field)); writer.newLine(); writer.write("#define " + getIdentifier(message) + "_setFudgeMsg" + camelCaseFieldName(field) + " " + getIdentifier(field.getOuterMessage()) + "_setFudgeMsg" + camelCaseFieldName(field)); writer.newLine(); } } else { writer.write("FudgeStatus " + getIdentifier(message) + "_get" + camelCaseFieldName(field) + " (FudgeMsg msg, "); if (field.isRepeated()) { writer.write(typeString(field.getType(), false) + "** value, int *repeatCount"); } else { writer.write(typeString(field.getType(), false) + "* value"); } writer.write(")"); endStmt(writer); writer.write("FudgeStatus " + getIdentifier(message) + "_set" + camelCaseFieldName(field) + " (FudgeMsg msg, "); if (field.isRepeated()) { writer.write(typeString(field.getType(), false) + "* value, int repeatCount"); } else { writer.write(typeString(field.getType(), true) + " value"); } writer.write(")"); endStmt(writer); if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.FUDGE_MSG_TYPE_ID) { writer.write("FudgeStatus " + getIdentifier(message) + "_getFudgeMsg" + camelCaseFieldName(field) + " (FudgeMsg msg, FudgeMsg *subMsg)"); endStmt(writer); writer.write("FudgeStatus " + getIdentifier(message) + "_setFudgeMsg" + camelCaseFieldName(field) + " (FudgeMsg msg, FudgeMsg subMsg)"); endStmt(writer); } } } // Message struct operators if (!message.isAbstract()) { writer.write("void " + getIdentifier(message) + "_free (struct _" + getIdentifier(message) + " *ptr)"); endStmt(writer); writer.write("FudgeStatus " + getIdentifier(message) + "_fromFudgeMsg (FudgeMsg msg, struct _" + getIdentifier(message) + " **ptr)"); endStmt(writer); writer.write("FudgeStatus " + getIdentifier(message) + "_toFudgeMsg (struct _" + getIdentifier(message) + " *ptr, FudgeMsg *msg)"); endStmt(writer); } writer.write("FudgeStatus " + getIdentifier(message) + "_addClass (FudgeMsg msg)"); endStmt(writer); writer.write("fudge_bool " + getIdentifier(message) + "_isClass (FudgeMsg msg)"); endStmt(writer); writer.write("#ifdef FUDGE_INTERNAL"); writer.newLine(); writer.write("void " + getIdentifier(message) + "_freeImpl (struct _" + getIdentifier(message) + " *ptr)"); endStmt(writer); writer.write("FudgeStatus " + getIdentifier(message) + "_fromFudgeMsgImpl (FudgeMsg msg, struct _" + getIdentifier(message) + " *ptr)"); endStmt(writer); writer.write("FudgeStatus " + getIdentifier(message) + "_toFudgeMsgImpl (struct _" + getIdentifier(message) + " *ptr, FudgeMsg msg)"); endStmt(writer); writer.write("#endif /* ifdef FUDGE_INTERNAL */"); writer.newLine(); // Short name defines if (message.getNamespace() != null) { writer.write("#ifdef FUDGE_NO_NAMESPACE"); writer.newLine(); writer.write("#define " + message.getName() + " " + getIdentifier(message)); writer.newLine(); writer.write("#define " + message.getName() + "_Class TEXT(\"" + message.getIdentifier() + "\")"); writer.newLine(); for (FieldDefinition field : message.getFieldDefinitions()) { writer.write("#define " + message.getName() + "_" + field.getName()); if (field.getOrdinal() != null) { writer.write("_Ordinal " + field.getOrdinal()); } else { writer.write("_Key TEXT(\"" + field.getName() + "\")"); } writer.newLine(); writer.write("#define " + message.getName() + "_get" + camelCaseFieldName(field) + " " + getIdentifier(message) + "_get" + camelCaseFieldName(field)); writer.newLine(); writer.write("#define " + message.getName() + "_set" + camelCaseFieldName(field) + " " + getIdentifier(message) + "_set" + camelCaseFieldName(field)); writer.newLine(); if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.FUDGE_MSG_TYPE_ID) { writer.write("#define " + message.getName() + "_getFudgeMsg" + camelCaseFieldName(field) + " " + getIdentifier(message) + "_getFudgeMsg" + camelCaseFieldName(field)); writer.newLine(); writer.write("#define " + message.getName() + "_setFudgeMsg" + camelCaseFieldName(field) + " " + getIdentifier(message) + "_setFudgeMsg" + camelCaseFieldName(field)); writer.newLine(); } } if (!message.isAbstract()) { writer.write("#define " + message.getName() + "_free " + getIdentifier(message) + "_free"); writer.newLine(); writer.write("#define " + message.getName() + "_fromFudgeMsg " + getIdentifier(message) + "_fromFudgeMsg"); writer.newLine(); writer.write("#define " + message.getName() + "_toFudgeMsg " + getIdentifier(message) + "_toFudgeMsg"); writer.newLine(); } writer.write("#define " + message.getName() + "_addClass " + getIdentifier(message) + "_addClass"); writer.newLine(); writer.write("#define " + message.getName() + "_isClass " + getIdentifier(message) + "_isClass"); writer.newLine(); writer.write("#else /* ifndef FUDGE_NO_NAMESPACE */"); writer.newLine(); } writer.write("#define " + getIdentifier(message) + "_Class TEXT(\"" + message.getIdentifier() + "\")"); writer.newLine(); for (FieldDefinition field : message.getFieldDefinitions()) { writer.write("#define " + getIdentifier(message) + "_" + field.getName()); if (field.getOrdinal() != null) { writer.write("_Ordinal " + field.getOrdinal()); } else { writer.write("_Key TEXT(\"" + field.getName() + "\")"); } writer.newLine(); } if (message.getNamespace() != null) { writer.write("#endif /* ifndef FUDGE_NO_NAMESPACE else */"); writer.newLine(); } } @Override public void writeClassHeaderAttribute(final Compiler.Context context, final FieldDefinition field, final IndentWriter writer) throws IOException { if (field.getOverride() != null) { comment(writer, field.getName() + " declared in " + field.getOverride().getOuterMessage().getName()); } else { if (field.isRepeated()) { writer.write("int fudgeCount" + camelCaseFieldName(field)); endStmt(writer); writer.write(typeString(field.getType(), false) + "* " + privateFieldName(field)); } else { writer.write(typeString(field.getType(), true)); if (!field.isRequired() && !isPointerType(field.getType())) writer.write("*"); writer.write(" " + privateFieldName(field)); } endStmt(writer); } } @Override public void writeClassHeaderConstructor(final Compiler.Context context, final MessageDefinition message, final IndentWriter writer) throws IOException { // Nothing required } @Override public void writeClassHeaderAccessor(final Compiler.Context context, final FieldDefinition field, final IndentWriter writer) throws IOException { // Nothing required } private String getEnumValueIdentifier(final EnumDefinition enumDefinition, final String value) { // This is so that we can go to fully qualified enum values if needed return value; } @Override public void writeEnumHeaderDeclaration(final Compiler.Context context, final EnumDefinition enumDefinition, final IndentWriter writer) throws IOException { super.writeEnumHeaderDeclaration(context, enumDefinition, writer); writer.write("typedef enum _" + getIdentifier(enumDefinition) + " " + getIdentifier(enumDefinition)); endStmt(writer); writer.write("enum _" + getIdentifier(enumDefinition)); beginBlock(writer); boolean first = true; for (Map.Entry<String, LiteralValue> entry : enumDefinition.getElements()) { if (first) { first = false; } else { writer.write(","); writer.newLine(); } writer.write(getEnumValueIdentifier(enumDefinition, entry.getKey())); if (enumDefinition.getType() == Type.INTEGER_ENCODED) { writer.write(" = " + ((IntegerValue) entry.getValue()).get()); } } endBlock(writer); endStmt(writer); if (enumDefinition.getType() == Type.INTEGER_ENCODED) { writer.write("#define " + getIdentifier(enumDefinition) + "_toFudgeEncoding(_v_) ((int)(_v_))"); writer.newLine(); writer.write("#define " + getIdentifier(enumDefinition) + "_fromFudgeEncoding(_v_) ((" + getIdentifier(enumDefinition) + ")(_v_))"); writer.newLine(); } else { writer.write("FudgeString " + getIdentifier(enumDefinition) + "_toFudgeEncoding (" + getIdentifier(enumDefinition) + " value)"); endStmt(writer); writer.write(getIdentifier(enumDefinition) + " " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (FudgeString value)"); endStmt(writer); } if (enumDefinition.getNamespace() != null) { writer.write("#ifdef FUDGE_NO_NAMESPACE"); writer.newLine(); writer.write("#define " + enumDefinition.getName() + " " + getIdentifier(enumDefinition)); writer.newLine(); writer.write("#define " + enumDefinition.getName() + "_toFudgeEncoding " + getIdentifier(enumDefinition) + "_toFudgeEncoding"); writer.newLine(); writer.write("#define " + enumDefinition.getName() + "_fromFudgeEncoding " + getIdentifier(enumDefinition) + "_fromFudgeEncoding"); writer.newLine(); writer.write("#endif /* ifndef FUDGE_NO_NAMESPACE */"); writer.newLine(); } } @Override public void writeTaxonomyHeaderDeclaration(final Compiler.Context context, final TaxonomyDefinition taxonomyDefinition, final IndentWriter writer) throws IOException { comment(writer, "TODO taxonomy header declaration"); } @Override public void writeTypedefHeaderDeclaration(final Compiler.Context context, final TypeDefinition typedef, final IndentWriter writer) throws IOException { comment(writer, "TODO typedef header declaration"); } @Override public void beginClassImplementationDeclaration(final Compiler.Context context, final MessageDefinition message, final IndentWriter writer) throws IOException { super.beginClassImplementationDeclaration(context, message, writer); // nothing required } @Override public void endClassImplementationDeclaration(final Compiler.Context context, final MessageDefinition message, final IndentWriter writer) throws IOException { // nothing required } @Override public void writeClassImplementationAttribute(final Compiler.Context context, final FieldDefinition field, final IndentWriter writer) throws IOException { // Nothing required } private void unwindStmts(final IndentWriter writer, final Stack<String> unwind) throws IOException { for (String stmt : unwind) { writer.write(stmt); endStmt(writer); } } private void returnAndUnwindStmt(final IndentWriter writer, final Stack<String> unwind, final String returnValue) throws IOException { if (!unwind.isEmpty()) { beginBlock(writer); unwindStmts(writer, unwind); } writer.write("return " + returnValue); endStmt(writer); if (!unwind.isEmpty()) endBlock(writer); } private void fieldValueToString(final IndentWriter writer, final String source, final String target, final Stack<String> unwind, final boolean allowNull, final String varLength) throws IOException { if (allowNull) { // If we're allowing nulls, we're in an array and the memory is already zero'd out writer.write("if (" + source + ".type != FUDGE_TYPE_INDICATOR)"); beginBlock(writer); } writer.write("if (" + source + ".type != FUDGE_TYPE_STRING)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write(target + " = (TCHAR*)malloc (((" + varLength + " = FudgeString_getLength (" + source + ".data.string)) + 1) * sizeof (TCHAR))"); endStmt(writer); writer.write("if (!" + target + ")"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("FudgeString_copyTo (" + target + ", " + varLength + " * sizeof (TCHAR), " + source + ".data.string)"); endStmt(writer); writer.write("(" + target + ")[" + varLength + "] = 0"); endStmt(writer); if (allowNull) { endBlock(writer); } } private void decodeArrayValue(final IndentWriter writer, final String source, final String target, final String fudgeType, final String cType, final Stack<String> unwind) throws IOException { writer.write("if (((" + source + ".type != " + fudgeType + ") && (status = FUDGE_INVALID_TYPE_COERCION)) || (!(*" + target + " = (" + cType + "*)malloc (" + source + ".numbytes + sizeof (" + cType + "))) && (status = FUDGE_OUT_OF_MEMORY)))"); returnAndUnwindStmt(writer, unwind, "status"); writer.write("memcpy (*" + target + ", " + source + ".data.bytes, " + source + ".numbytes)"); endStmt(writer); writer.write("(*" + target + ")[" + source + ".numbytes / sizeof (" + cType + ")] = 0"); endStmt(writer); } private void decodeFieldValue(final IndentWriter writer, final FieldType type, final String source, final String target, final Stack<String> unwind, final boolean allowNull) throws IOException { if (type instanceof FieldType.MessageType) { writer.write("if (" + source + ".type == FUDGE_TYPE_FUDGE_MSG)"); beginBlock(writer); writer.write("if ((status = "); if (type instanceof FieldType.AnonMessageType) { writer.write("FudgeMsg_retain (*" + target + " = " + source + ".data.message"); } else { writer.write(getIdentifier(((FieldType.MessageType) type).getMessageDefinition()) + "_fromFudgeMsg (" + source + ".data.message, " + target); } writer.write(")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); endBlock(writer); if (allowNull) { writer.write("else if (" + source + ".type == FUDGE_TYPE_INDICATOR) *" + target + " = 0"); endStmt(writer); } writer.write("else "); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); } else if (type instanceof FieldType.ArrayType) { final FieldType.ArrayType arrayType = (FieldType.ArrayType) type; switch (arrayType.getFudgeFieldType()) { case FudgeTypeDictionary.BYTE_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_4_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_4", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_8_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_8", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_16_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_16", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_20_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_20", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_32_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_32", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_64_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_64", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_128_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_128", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_256_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_256", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_512_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_512", "fudge_byte", unwind); break; case FudgeTypeDictionary.INT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_INT_ARRAY", "fudge_i32", unwind); break; case FudgeTypeDictionary.LONG_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_LONG_ARRAY", "fudge_i64", unwind); break; case FudgeTypeDictionary.SHORT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_SHORT_ARRAY", "fudge_i16", unwind); break; case FudgeTypeDictionary.FLOAT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_FLOAT_ARRAY", "fudge_f32", unwind); break; case FudgeTypeDictionary.DOUBLE_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_DOUBLE_ARRAY", "fudge_f64", unwind); break; case FudgeTypeDictionary.FUDGE_MSG_TYPE_ID: final String cType = typeString(arrayType.getBaseType(), false); final String varI = "i" + unwind.size(); final String varN = "n" + unwind.size(); final String varFields = "fields" + unwind.size(); writer.write("int " + varI + ", " + varN); endStmt(writer); writer.write("if (" + source + ".type != FUDGE_TYPE_FUDGE_MSG)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write(varN + " = FudgeMsg_numFields (" + source + ".data.message)"); endStmt(writer); writer.write("if (" + varN + " > 0)"); beginBlock(writer); // if writer.write("FudgeField *" + varFields); endStmt(writer); writer.write("if ((" + varFields + " = (FudgeField*)malloc (sizeof (FudgeField) * " + varN + ")) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); unwind.push("free (" + varFields + ")"); writer.write("if (FudgeMsg_getFields (" + varFields + ", " + varN + ", " + source + ".data.message) <= 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write("if ((*" + target + " = (" + cType + "*)malloc (sizeof (" + cType + ") * (" + varN + " + 1))) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*" + target + ", 0, sizeof (" + cType + ") * (" + varN + " + 1))"); endStmt(writer); if (unwind.size() == 1) { final StringBuilder sb = new StringBuilder(); if (isPointerType(arrayType.getBaseType())) { sb.append("do "); sb.append(getFreeFieldValueStmt(arrayType.getBaseType(), "*(*" + target + " + " + varI + ")", false, 0)); if (sb.charAt(sb.length() - 1) != '}') { sb.append(';'); } sb.append(" while (--" + varI + " >= 0); "); } sb.append("free (*" + target + "); *" + target + " = 0"); unwind.push(sb.toString()); } writer.write("for (" + varI + " = 0; " + varI + " < " + varN + "; " + varI + "++)"); beginBlock(writer); // for decodeFieldValue(writer, arrayType.getBaseType(), varFields + "[" + varI + "]", "(*" + target + " + " + varI + ")", unwind, true); endBlock(writer); // for if (unwind.size() == 2) { unwind.pop(); // memory allocation release } writer.write(unwind.pop()); endStmt(writer); endBlock(writer); // if writer.write("else"); beginBlock(writer); // else writer.write("if ((*" + target + " = (" + cType + "*)malloc (sizeof (" + cType + "))) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*" + target + ", 0, sizeof (" + cType + "))"); endStmt(writer); endBlock(writer); // else break; default: throw new IllegalStateException("Type " + arrayType + " is not expected type"); } } else if (type instanceof FieldType.EnumType) { final EnumDefinition enumDefinition = ((FieldType.EnumType) type).getEnumDefinition(); if (enumDefinition.getType() == EnumDefinition.Type.INTEGER_ENCODED) { final String varI = "i" + unwind.size(); writer.write("int " + varI); endStmt(writer); writer.write("if ((status = FudgeMsg_getFieldAsI32 (&" + source + ", &" + varI + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); writer.write("*" + target + " = " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (" + varI + ")"); endStmt(writer); } else { writer.write("if (" + source + ".type == FUDGE_TYPE_STRING) *" + target + " = " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (" + source + ".data.string)"); endStmt(writer); if (allowNull) { writer.write("else if (" + source + ".type == FUDGE_TYPE_INDICATOR) *" + target + " = 0"); endStmt(writer); } writer.write("else "); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); } } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: // No code needed break; case FudgeTypeDictionary.BOOLEAN_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsBoolean (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.BYTE_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsByte (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.SHORT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI16 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.INT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI32 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.LONG_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI64 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.FLOAT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsF32 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.DOUBLE_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsF64 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.STRING_TYPE_ID: final String varLen = "len" + unwind.size(); - writer.write("int " + varLen); + writer.write("size_t " + varLen); endStmt(writer); fieldValueToString(writer, source, "*" + target, unwind, allowNull, varLen); break; case FudgeTypeDictionary.DATE_TYPE_ID: comment(writer, "TODO date type"); break; case FudgeTypeDictionary.DATETIME_TYPE_ID: comment(writer, "TODO datetime type"); break; case FudgeTypeDictionary.TIME_TYPE_ID: comment(writer, "TODO time type"); break; default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } } private void writeIfFieldMatches(final IndentWriter writer, final FieldDefinition field, final String fieldRef) throws IOException { if (field.getOrdinal() != null) { writer.write("if ((" + fieldRef + ".flags & FUDGE_FIELD_HAS_ORDINAL) && (" + fieldRef + ".ordinal == " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Ordinal))"); } else { writer.write("if (0 /* TODO: test field name */)"); } } private void writeAccessor(final IndentWriter writer, final FieldDefinition field) throws IOException { // Accessor writer.write("FudgeStatus " + getIdentifier(field.getOuterMessage()) + "_get" + camelCaseFieldName(field) + " (FudgeMsg msg, "); if (field.isRepeated()) { writer.write(typeString(field.getType(), false) + "** value, int *repeatCount"); } else { writer.write(typeString(field.getType(), false) + "* value"); } writer.write(")"); beginBlock(writer); // method if (field.isRepeated()) { writer.write("int numFields"); } else { writer.write("FudgeField field"); } endStmt(writer); writer.write("FudgeStatus status"); endStmt(writer); if (field.getOrdinal() == null) { writer.write("FudgeString fieldName"); endStmt(writer); } writer.write("if (!msg || !value"); if (field.isRepeated()) writer.write(" || !repeatCount"); writer.write(") return FUDGE_NULL_POINTER"); endStmt(writer); final Stack<String> unwind = new Stack<String>(); if (field.getOrdinal() == null) { writer.write("if ((status = FudgeString_createFrom (&fieldName, " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Key, " + field.getName().length() + " * sizeof (TCHAR))) != FUDGE_OK) return status"); endStmt(writer); unwind.push("FudgeString_release (fieldName)"); } if (field.isRepeated()) { writer.write("if ((numFields = FudgeMsg_numFields (msg)) > 0)"); beginBlock(writer); // if total > 0 writer.write("FudgeField *fields = (FudgeField*)malloc (sizeof (FudgeField) * numFields)"); endStmt(writer); writer.write("int i, j"); endStmt(writer); writer.write("if (!fields)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); unwind.push("free (fields)"); writer.write("if (FudgeMsg_getFields (fields, numFields, msg) <= 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write("j = 0"); endStmt(writer); writer.write("for (i = 0; i < numFields; i++)"); beginBlock(writer); // for writeIfFieldMatches(writer, field, "fields[i]"); writer.write("j++"); endStmt(writer); endBlock(writer); // for writer.write("if (j > 0)"); beginBlock(writer); // if count > 0 writer.write("if (!(*value = (" + typeString(field.getType(), false) + "*)malloc (sizeof (" + typeString(field.getType(), false) + ") * j)))"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*value, 0, sizeof (" + typeString(field.getType(), false) + ") * j)"); endStmt(writer); writer.write("j = 0"); endStmt(writer); final StringBuilder sb = new StringBuilder(); if (isPointerType(field.getType())) { sb.append("do "); sb.append(getFreeFieldValueStmt(field.getType(), "*(*value + j)", false, 0)); if (sb.charAt(sb.length() - 1) != '}') { sb.append(';'); } sb.append(" while (--j >= 0); "); } sb.append("free (*value)"); unwind.push(sb.toString()); writer.write("for (i = 0; i < numFields; i++)"); beginBlock(writer); // for writeIfFieldMatches(writer, field, "fields[i]"); beginBlock(writer); // if decodeFieldValue(writer, field.getType(), "fields[i]", "(*value + j)", unwind, false); writer.write("j++"); endStmt(writer); endBlock(writer); // if assert (unwind.size() <= 3); // it should be 2 or 3 endBlock(writer); // for writer.write("*repeatCount = j"); endStmt(writer); unwind.pop(); // free (*value) unwind.pop(); // free (fields) writer.write("free (fields)"); endStmt(writer); writer.write("return FUDGE_OK"); endStmt(writer); endBlock(writer); // if count > 0 writer.write("free (fields)"); endStmt(writer); endBlock(writer); // if total > 0 if (field.getDefaultValue() != null) { comment(writer, "TODO: load default value"); } else { writer.write("*repeatCount = 0"); endStmt(writer); writer.write("*value = 0"); endStmt(writer); } } else { if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.INDICATOR_TYPE_ID) { writer.write("*value = ("); } else { writer.write("if ((status = "); } writer.write("FudgeMsg_getFieldBy"); if (field.getOrdinal() != null) { writer.write("Ordinal (&field, msg, " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Ordinal"); } else { writer.write("Name (&field, msg, fieldName"); } writer.write(")"); if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.INDICATOR_TYPE_ID) { writer.write(" == FUDGE_OK)"); endStmt(writer); } else { writer.write(") == FUDGE_OK)"); beginBlock(writer); // if decodeFieldValue(writer, field.getType(), "field", "value", unwind, false); assert (unwind.size() <= 1); endBlock(writer); // if writer.write("else "); if (field.getDefaultValue() != null) { writer.write("*value = " + getLiteral(field.getDefaultValue())); endStmt(writer); } else { returnAndUnwindStmt(writer, unwind, "status"); } } } unwindStmts(writer, unwind); writer.write("return FUDGE_OK"); endStmt(writer); endBlock(writer); // method unwind.clear(); } private void writeSubMessageAccessor(final IndentWriter writer, final FieldDefinition field) throws IOException { final Stack<String> unwind = new Stack<String>(); writer.write("FudgeStatus " + getIdentifier(field.getOuterMessage()) + "_getFudgeMsg" + camelCaseFieldName(field) + " (FudgeMsg msg, FudgeMsg *subMsg)"); beginBlock(writer); // method writer.write("FudgeStatus status"); endStmt(writer); writer.write("FudgeField field"); endStmt(writer); if (field.getOrdinal() == null) { writer.write("FudgeString fieldName"); endStmt(writer); } writer.write("if (!msg || !subMsg) return FUDGE_NULL_POINTER"); endStmt(writer); if (field.getOrdinal() == null) { writer.write("if ((status = FudgeString_createFrom (&fieldName, " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Key, " + field.getName().length() + " * sizeof (TCHAR))) != FUDGE_OK) return status"); endStmt(writer); unwind.push("FudgeString_release (fieldName)"); } writer.write("if (((status = FudgeMsg_getFieldBy"); if (field.getOrdinal() == null) { writer.write("Name (&field, msg, fieldName"); } else { writer.write("Ordinal (&field, msg, " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Ordinal"); } writer .write(")) != FUDGE_OK) || ((field.type != FUDGE_TYPE_FUDGE_MSG) && (status = FUDGE_INVALID_TYPE_COERCION)))"); returnAndUnwindStmt(writer, unwind, "status"); unwindStmts(writer, unwind); writer.write("return FudgeMsg_retain (*subMsg = field.data.message)"); endStmt(writer); endBlock(writer); // method unwind.clear(); } private String safeIndex(final String value, final String index) { if (value.charAt(0) == '*') { return "(" + value + ")[" + index + "]"; } else { return value + "[" + index + "]"; } } // TODO: note the array logic is nicely flawed, relying on nulls or zeros to terminate them which is not good in the general case private String withArrayLength(final IndentWriter writer, final String array, final int arrayDepth) throws IOException { writer.write("n" + arrayDepth + " = 0"); endStmt(writer); writer.write("while (" + safeIndex(array, "n" + arrayDepth) + ") n" + arrayDepth + "++"); endStmt(writer); return array + ", n" + arrayDepth; } private String isNullCheck (final String value, final FieldType type) { if (type instanceof FieldType.ArrayType) { return value; // pointer } else if (type instanceof FieldType.EnumType) { return value; // enum scalar } else if (type instanceof FieldType.MessageType) { return value; // pointer } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: case FudgeTypeDictionary.BOOLEAN_TYPE_ID: case FudgeTypeDictionary.BYTE_TYPE_ID: case FudgeTypeDictionary.SHORT_TYPE_ID: case FudgeTypeDictionary.INT_TYPE_ID: case FudgeTypeDictionary.LONG_TYPE_ID: case FudgeTypeDictionary.FLOAT_TYPE_ID: case FudgeTypeDictionary.DOUBLE_TYPE_ID: return value; // scalar case FudgeTypeDictionary.STRING_TYPE_ID: return value; // pointer case FudgeTypeDictionary.DATE_TYPE_ID: return value + ".year"; // no year 0; -1 = 1BC, 1 = 1AD case FudgeTypeDictionary.DATETIME_TYPE_ID: return value + ".date.year"; // no year 0; -1 = 1BC, 1 = 1AD case FudgeTypeDictionary.TIME_TYPE_ID: return value + ".precision"; // precision 0 not valid on a time alone default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } } private void encodeFieldValue(final IndentWriter writer, final String msg, final String nameOrdinal, String value, final FieldType fieldType, final Stack<String> unwind, final int arrayDepth) throws IOException { String type = null; int mark = unwind.size(); if (fieldType instanceof FieldType.AnonMessageType) { type = "Msg"; } else if (fieldType instanceof FieldType.MessageType) { writer.write("if ((status = " + getIdentifier(((FieldType.MessageType) fieldType).getMessageDefinition()) + "_toFudgeMsg (" + value + ", &subMsg)) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); unwind.push("FudgeMsg_release (subMsg)"); type = "Msg"; value = "subMsg"; } else if (fieldType instanceof FieldType.ArrayType) { switch (fieldType.getFudgeFieldType()) { case FudgeTypeDictionary.BYTE_ARRAY_TYPE_ID: value = withArrayLength(writer, value, arrayDepth); type = "ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_4_TYPE_ID: type = "4ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_8_TYPE_ID: type = "8ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_16_TYPE_ID: type = "16ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_20_TYPE_ID: type = "20ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_32_TYPE_ID: type = "32ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_64_TYPE_ID: type = "64ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_128_TYPE_ID: type = "128ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_256_TYPE_ID: type = "256ByteArray"; break; case FudgeTypeDictionary.BYTE_ARR_512_TYPE_ID: type = "512ByteArray"; break; case FudgeTypeDictionary.INT_ARRAY_TYPE_ID: value = withArrayLength(writer, value, arrayDepth); type = "I32Array"; break; case FudgeTypeDictionary.LONG_ARRAY_TYPE_ID: value = withArrayLength(writer, value, arrayDepth); type = "I64Array"; break; case FudgeTypeDictionary.SHORT_ARRAY_TYPE_ID: value = withArrayLength(writer, value, arrayDepth); type = "I16Array"; break; case FudgeTypeDictionary.FLOAT_ARRAY_TYPE_ID: value = withArrayLength(writer, value, arrayDepth); type = "F32Array"; break; case FudgeTypeDictionary.DOUBLE_ARRAY_TYPE_ID: value = withArrayLength(writer, value, arrayDepth); type = "F64Array"; break; case FudgeTypeDictionary.FUDGE_MSG_TYPE_ID: writer.write("if ((status = FudgeMsg_create (&arrMsg" + arrayDepth + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); unwind.push("FudgeMsg_release (arrMsg" + arrayDepth + ")"); writer.write("for (n" + arrayDepth + " = 0; " + isNullCheck(safeIndex(value, "n" + arrayDepth), ((FieldType.ArrayType) fieldType).getBaseType()) + "; n" + arrayDepth + "++)"); beginBlock(writer); // for encodeFieldValue(writer, "arrMsg" + arrayDepth, "0, 0", safeIndex(value, "n" + arrayDepth), ((FieldType.ArrayType) fieldType).getBaseType(), unwind, arrayDepth + 1); endBlock(writer); // for type = "Msg"; value = "arrMsg" + arrayDepth; break; default: throw new IllegalStateException("Type " + fieldType + " is not expected type"); } } else if (fieldType instanceof FieldType.EnumType) { final EnumDefinition enumDefinition = ((FieldType.EnumType) fieldType).getEnumDefinition(); value = getIdentifier(enumDefinition) + "_toFudgeEncoding (" + value + ")"; if (enumDefinition.getType() == EnumDefinition.Type.INTEGER_ENCODED) { type = "I32"; } else { type = "String"; } } else { switch (fieldType.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: writer.write("if (value) "); type = "Indicator"; value = null; break; case FudgeTypeDictionary.BOOLEAN_TYPE_ID: type = "Bool"; break; case FudgeTypeDictionary.BYTE_TYPE_ID: type = "Byte"; break; case FudgeTypeDictionary.SHORT_TYPE_ID: type = "I16"; break; case FudgeTypeDictionary.INT_TYPE_ID: type = "I32"; break; case FudgeTypeDictionary.LONG_TYPE_ID: type = "I64"; break; case FudgeTypeDictionary.FLOAT_TYPE_ID: type = "F32"; break; case FudgeTypeDictionary.DOUBLE_TYPE_ID: type = "F64"; break; case FudgeTypeDictionary.STRING_TYPE_ID: writer.write("if ((status = FudgeString_createFrom (&str, " + value + ", FUDGE_STRING_LENGTH (" + value + ") * sizeof (TCHAR))) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); unwind.push("FudgeString_release (str)"); type = "String"; value = "str"; break; case FudgeTypeDictionary.DATE_TYPE_ID: comment(writer, "TODO date type"); break; case FudgeTypeDictionary.DATETIME_TYPE_ID: comment(writer, "TODO datetime type"); break; case FudgeTypeDictionary.TIME_TYPE_ID: comment(writer, "TODO time type"); break; default: throw new IllegalStateException("type '" + fieldType + "' is not an expected type (fudge field type " + fieldType.getFudgeFieldType() + ")"); } } if (type != null) { writer.write("status = FudgeMsg_addField" + type + " (" + msg + ", " + nameOrdinal); if (value != null) { writer.write(", " + value); } writer.write(")"); endStmt(writer); } while (unwind.size() > mark) { writer.write(unwind.pop()); endStmt(writer); } if (type != null) { writer.write("if (status != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); } } private void writeLocalMutatorVariables(final IndentWriter writer, final FieldType type, final int count) throws IOException { if (type instanceof FieldType.ArrayType) { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.BYTE_ARR_4_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_8_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_16_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_20_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_32_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_64_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_128_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_256_TYPE_ID: case FudgeTypeDictionary.BYTE_ARR_512_TYPE_ID: // No additional variables needed break; case FudgeTypeDictionary.FUDGE_MSG_TYPE_ID: writer.write("FudgeMsg arrMsg" + count); endStmt(writer); writer.write("int n" + count); endStmt(writer); writeLocalMutatorVariables(writer, ((FieldType.ArrayType) type).getBaseType(), count + 1); break; default: writer.write("int n" + count); endStmt(writer); break; } } else if (type instanceof FieldType.MessageType) { if (!(type instanceof FieldType.AnonMessageType)) { writer.write("FudgeMsg subMsg"); endStmt(writer); } } else if (!(type instanceof FieldType.EnumType) && (type.getFudgeFieldType() == FudgeTypeDictionary.STRING_TYPE_ID)) { writer.write("FudgeString str"); endStmt(writer); } } private void writeMutator(final IndentWriter writer, final FieldDefinition field) throws IOException { final Stack<String> unwind = new Stack<String>(); final FieldType type = field.getType(); writer.write("FudgeStatus " + getIdentifier(field.getOuterMessage()) + "_set" + camelCaseFieldName(field) + " (FudgeMsg msg, "); if (field.isRepeated()) { writer.write(typeString(type, false) + "* value, int repeatCount"); } else { writer.write(typeString(type, true) + " value"); } writer.write(")"); beginBlock(writer); // method if (field.getOrdinal() != null) { writer .write("fudge_i16 ordinal = " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Ordinal"); } else { writer.write("FudgeString fieldName"); } endStmt(writer); writer.write("FudgeStatus status"); endStmt(writer); writeLocalMutatorVariables(writer, type, 0); writer.write("if (!msg"); if (field.isRepeated()) { writer.write(" || ((repeatCount > 0) && !value)"); if (field.isRequired()) { writer.write(" || (repeatCount == 0)"); } } else { if (field.isRequired() && isPointerType(type)) { writer.write(" || !value"); } } writer.write(") return FUDGE_NULL_POINTER"); endStmt(writer); // TODO: clear any previously set fields if (!field.isRequired()) { if (field.isRepeated()) { writer.write("if (repeatCount == 0) return FUDGE_OK"); endStmt(writer); } else { if (isPointerType(type)) { writer.write("if (!value) return FUDGE_OK"); endStmt(writer); } } } if (field.getOrdinal() == null) { writer.write("if ((status = FudgeString_createFrom (&fieldName, " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Key, " + field.getName().length() + " * sizeof (TCHAR))) != FUDGE_OK) return status"); endStmt(writer); unwind.push("FudgeString_release (fieldName)"); } String value; if (field.isRepeated()) { writer.write("while (repeatCount-- > 0)"); beginBlock(writer); // while value = "*value"; } else { value = "value"; } encodeFieldValue(writer, "msg", field.getOrdinal() != null ? "0, &ordinal" : "fieldName, 0", value, type, unwind, 0); if (field.isRepeated()) { writer.write("value++"); endStmt(writer); endBlock(writer); // while } unwindStmts(writer, unwind); writer.write("return FUDGE_OK"); endStmt(writer); endBlock(writer); // method unwind.clear(); } private void writeSubMessageMutator(final IndentWriter writer, final FieldDefinition field) throws IOException { writer.write("FudgeStatus " + getIdentifier(field.getOuterMessage()) + "_setFudgeMsg" + camelCaseFieldName(field) + " (FudgeMsg msg, FudgeMsg subMsg)"); beginBlock(writer); // method if (field.getOrdinal() != null) { writer.write("fudge_i16 ordinal = " + field.getOrdinal()); } else { writer.write("FudgeString fieldName"); } endStmt(writer); writer.write("FudgeStatus status"); endStmt(writer); writer.write("if (!msg || !subMsg) return FUDGE_NULL_POINTER"); endStmt(writer); if (field.getOrdinal() == null) { writer.write("if ((status = FudgeString_createFrom (&fieldName, " + getIdentifier(field.getOuterMessage()) + "_" + field.getName() + "_Key, " + field.getName().length() + " * sizeof (TCHAR))) != FUDGE_OK) return status"); endStmt(writer); } writer.write("status = FudgeMsg_addFieldMsg (msg, "); if (field.getOrdinal() == null) { writer.write("fieldName, 0"); } else { writer.write("0, &ordinal"); } writer.write(", subMsg)"); endStmt(writer); if (field.getOrdinal() == null) { writer.write("FudgeString_release (fieldName)"); endStmt(writer); } writer.write("return status"); endStmt(writer); endBlock(writer); // method } @Override public void writeClassImplementationAccessor(final Compiler.Context context, final FieldDefinition field, final IndentWriter writer) throws IOException { if (field.getOverride() != null) { return; } writeAccessor(writer, field); if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.FUDGE_MSG_TYPE_ID) { writeSubMessageAccessor(writer, field); } writeMutator(writer, field); if (field.getType().getFudgeFieldType() == FudgeTypeDictionary.FUDGE_MSG_TYPE_ID) { writeSubMessageMutator(writer, field); } } private boolean isPointerType(final FieldType type) { if (type instanceof FieldType.ArrayType) { return true; } else if (type instanceof FieldType.EnumType) { return false; } else if (type instanceof FieldType.MessageType) { return true; } else if (type instanceof FieldType.UserType) { return isPointerType(((FieldType.UserType) type).getTypeDefinition().getUnderlyingType()); } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: case FudgeTypeDictionary.BOOLEAN_TYPE_ID: case FudgeTypeDictionary.BYTE_TYPE_ID: case FudgeTypeDictionary.SHORT_TYPE_ID: case FudgeTypeDictionary.INT_TYPE_ID: case FudgeTypeDictionary.LONG_TYPE_ID: case FudgeTypeDictionary.FLOAT_TYPE_ID: case FudgeTypeDictionary.DOUBLE_TYPE_ID: case FudgeTypeDictionary.DATE_TYPE_ID: case FudgeTypeDictionary.DATETIME_TYPE_ID: case FudgeTypeDictionary.TIME_TYPE_ID: return false; case FudgeTypeDictionary.STRING_TYPE_ID: return true; default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } } private String getFreeFieldValueStmt(final FieldType type, final String value, final boolean constantStringPointer, final int depthCount) { final StringBuilder sb = new StringBuilder(); sb.append("if (").append(value).append(") "); if (type instanceof FieldType.ArrayType) { final FieldType elementType = ((FieldType.ArrayType) type).getBaseType(); if (isPointerType(elementType)) { final String varF = "f" + depthCount; final String valueElement = safeIndex(value, varF); sb.append("{ int ").append(varF).append("; for (").append(varF).append(" = 0; ").append( isNullCheck(valueElement, elementType)).append("; ").append(varF).append("++) ").append( getFreeFieldValueStmt(elementType, valueElement, constantStringPointer, depthCount + 1)).append("; "); } sb.append("free (").append(value).append(")"); if (isPointerType(elementType)) { sb.append("; }"); } } else if (type instanceof FieldType.AnonMessageType) { sb.append("FudgeMsg_release (").append(value).append(")"); } else if (type instanceof FieldType.MessageType) { sb.append(getIdentifier(((FieldType.MessageType) type).getMessageDefinition())).append("_free (").append(value) .append(")"); } else if (type instanceof FieldType.UserType) { sb.append(getFreeFieldValueStmt(((FieldType.UserType) type).getTypeDefinition().getUnderlyingType(), value, constantStringPointer, depthCount)); } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.STRING_TYPE_ID: sb.append("free ("); if (constantStringPointer) { sb.append("(TCHAR*)"); } sb.append(value).append(")"); break; default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } return sb.toString(); } private void writeMessageFree(final IndentWriter writer, final MessageDefinition message) throws IOException { if (!message.isAbstract()) { // Public free function writer.write("void " + getIdentifier(message) + "_free (struct _" + getIdentifier(message) + " *ptr)"); beginBlock(writer); // free writer.write("if (!ptr) return"); endStmt(writer); writer.write(getIdentifier(message) + "_freeImpl (ptr)"); endStmt(writer); writer.write("free (ptr)"); endStmt(writer); endBlock(writer); // free } // Private free function writer.write("void " + getIdentifier(message) + "_freeImpl (struct _" + getIdentifier(message) + " *ptr)"); beginBlock(writer); // free if (message.getExtends() != null) { writer.write(getIdentifier(message.getExtends()) + "_freeImpl (&ptr->fudgeParent)"); endStmt(writer); } for (FieldDefinition field : message.getFieldDefinitions()) { if (field.getOverride() != null) { continue; } if (field.isRepeated()) { writer.write("if (ptr->fudgeCount" + camelCaseFieldName(field) + ")"); beginBlock(writer); // if if (isPointerType(field.getType())) { writer.write("int i"); endStmt(writer); writer.write("for (i = 0; i < ptr->fudgeCount" + camelCaseFieldName(field) + "; i++)"); beginBlock(writer); // for writer.write(getFreeFieldValueStmt(field.getType(), "ptr->" + privateFieldName(field) + "[i]", false, 0)); endStmt(writer); endBlock(writer); // for } writer.write("free (ptr->" + privateFieldName(field) + ")"); endStmt(writer); endBlock(writer); // if } else if (isPointerType(field.getType())) { writer.write(getFreeFieldValueStmt(field.getType(), "ptr->" + privateFieldName(field), true, 0)); endStmt(writer); } else if (!field.isRequired()) { writer.write("if (ptr->" + privateFieldName(field) + ") free (ptr->" + privateFieldName(field) + ")"); endStmt(writer); } } endBlock(writer); // free } private void writeMessageFromFudgeMsg(final IndentWriter writer, final MessageDefinition message) throws IOException { if (!message.isAbstract()) { // Public fromFudgeMsg function writer.write("FudgeStatus " + getIdentifier(message) + "_fromFudgeMsg (FudgeMsg msg, struct _" + getIdentifier(message) + " **ptr)"); beginBlock(writer); // fromFudgeMsg writer.write("FudgeStatus status"); endStmt(writer); writer.write("if (!msg || !ptr) return FUDGE_NULL_POINTER"); endStmt(writer); writer.write("*ptr = (struct _" + getIdentifier(message) + "*)malloc (sizeof (struct _" + getIdentifier(message) + "))"); endStmt(writer); writer.write("if (!*ptr) return FUDGE_OUT_OF_MEMORY"); endStmt(writer); writer.write("memset (*ptr, 0, sizeof (struct _" + getIdentifier(message) + "))"); endStmt(writer); writer.write("(*ptr)->"); MessageDefinition parent = message.getExtends(); while (parent != null) { writer.write("fudgeParent."); parent = parent.getExtends(); } writer.write("fudgeStructSize = sizeof (struct _" + getIdentifier(message) + ")"); endStmt(writer); writer.write("if ((status = " + getIdentifier(message) + "_fromFudgeMsgImpl (msg, *ptr)) != FUDGE_OK)"); beginBlock(writer); // if writer.write(getIdentifier(message) + "_free (*ptr)"); endStmt(writer); writer.write("*ptr = 0"); endStmt(writer); endBlock(writer); // if writer.write("return status"); endStmt(writer); endBlock(writer); // fromFudgeMsg } // Private fromFudgeMsg function writer.write("FudgeStatus " + getIdentifier(message) + "_fromFudgeMsgImpl (FudgeMsg msg, struct _" + getIdentifier(message) + " *ptr)"); beginBlock(writer); // fromFudgeMsgImpl boolean needsStatus = (message.getExtends() != null); final Map<FieldType, String> typesDeclared = new HashMap<FieldType, String>(); for (FieldDefinition field : message.getFieldDefinitions()) { if (field.getOverride() != null) { continue; } if (field.isRequired()) { needsStatus = true; } else { if (!field.isRepeated() && !isPointerType(field.getType())) { if (!typesDeclared.containsKey(field.getType())) { final String name = "val" + typesDeclared.size(); typesDeclared.put(field.getType(), name); writer.write(typeString(field.getType(), false) + " " + name); endStmt(writer); needsStatus = true; } } } } if (needsStatus) { writer.write("FudgeStatus status"); endStmt(writer); } if (message.getExtends() != null) { writer.write("if ((status = " + getIdentifier(message.getExtends()) + "_fromFudgeMsgImpl (msg, &ptr->fudgeParent)) != FUDGE_OK) return status"); endStmt(writer); } for (FieldDefinition field : message.getFieldDefinitions()) { if (field.getOverride() != null) { continue; } if (field.isRepeated() || field.isRequired() || isPointerType(field.getType())) { if (field.isRequired()) { writer.write("if ((status = "); } writer.write(getIdentifier(message) + "_get" + camelCaseFieldName(field) + " (msg, "); if (!field.isRepeated() && !(field.getType() instanceof FieldType.EnumType) && (field.getType().getFudgeFieldType() == FudgeTypeDictionary.STRING_TYPE_ID)) { writer.write("(TCHAR**)"); } writer.write("&ptr->" + privateFieldName(field)); if (field.isRepeated()) { writer.write(", &ptr->fudgeCount" + camelCaseFieldName(field)); } writer.write(")"); if (field.isRequired()) { writer.write(") != FUDGE_OK) return status"); } endStmt(writer); } else { final String tmp = typesDeclared.get(field.getType()); writer.write("if ((status = " + getIdentifier(message) + "_get" + camelCaseFieldName(field) + " (msg, &" + tmp + ")) == FUDGE_OK)"); beginBlock(writer); writer.write("if (!(ptr->" + privateFieldName(field) + " = (" + typeString(field.getType(), false) + "*)malloc (sizeof (" + typeString(field.getType(), false) + ")))) return FUDGE_OUT_OF_MEMORY"); endStmt(writer); writer.write("*ptr->" + privateFieldName(field) + " = " + tmp); endStmt(writer); endBlock(writer); } } writer.write("return FUDGE_OK"); endStmt(writer); endBlock(writer); // fromFudgeMsgImpl } private void writeMessageIsClass(final IndentWriter writer, final MessageDefinition message) throws IOException { // public isClass function - tests if the message contains this class name writer.write("fudge_bool " + getIdentifier(message) + "_isClass (FudgeMsg msg)"); beginBlock(writer); // isClass writer.write("FudgeString className"); endStmt(writer); writer.write("FudgeField *fields"); endStmt(writer); writer.write("int i, n"); endStmt(writer); writer.write("fudge_bool result = FUDGE_FALSE"); endStmt(writer); writer .write("if (((n = FudgeMsg_numFields (msg)) > 0) && ((fields = (FudgeField*)malloc (sizeof (FudgeField) * n)) != NULL))"); beginBlock(writer); // malloc-if writer.write("if (FudgeString_createFrom (&className, " + getIdentifier(message) + "_Class, " + message.getIdentifier().length() + " * sizeof (TCHAR)) == FUDGE_OK)"); beginBlock(writer); // createFrom-if writer.write("if (FudgeMsg_getFields (fields, n, msg) > 0)"); beginBlock(writer); // getFields-if writer.write("for (i = 0; i < n; i++)"); beginBlock(writer); // for writer .write("if ((fields[i].flags & FUDGE_FIELD_HAS_ORDINAL) && (fields[i].ordinal == 0) && (fields[i].type == FUDGE_TYPE_STRING) && !FudgeString_compare (className, fields[i].data.string))"); beginBlock(writer); // if writer.write("result = FUDGE_TRUE"); endStmt(writer); writer.write("break"); endStmt(writer); endBlock(writer); // if endBlock(writer); // for endBlock(writer); // getFields-if writer.write("FudgeString_release (className)"); endStmt(writer); endBlock(writer); // createFrom-if writer.write("free (fields)"); endStmt(writer); endBlock(writer); // malloc-if writer.write("return result"); endStmt(writer); endBlock(writer); // isClass } private void writeMessageToFudgeMsg(final IndentWriter writer, final MessageDefinition message) throws IOException { if (!message.isAbstract()) { // Public toFudgeMsg function writer.write("FudgeStatus " + getIdentifier(message) + "_toFudgeMsg (struct _" + getIdentifier(message) + " *ptr, FudgeMsg *msg)"); beginBlock(writer); // toFudgeMsg writer.write("FudgeStatus status"); endStmt(writer); writer.write("if (!ptr || !msg) return FUDGE_NULL_POINTER"); endStmt(writer); writer.write("if ((status = FudgeMsg_create (msg)) != FUDGE_OK) return status"); endStmt(writer); writer.write("if ((status = " + getIdentifier(message) + "_toFudgeMsgImpl (ptr, *msg)) != FUDGE_OK) FudgeMsg_release (*msg)"); endStmt(writer); writer.write("return status"); endStmt(writer); endBlock(writer); // toFudgeMsg } // Private toFudgeMsg function writer.write("FudgeStatus " + getIdentifier(message) + "_toFudgeMsgImpl (struct _" + getIdentifier(message) + " *ptr, FudgeMsg msg)"); beginBlock(writer); // toFudgeMsg writer.write("FudgeStatus status"); endStmt(writer); writer.write("if ((status = " + getIdentifier(message) + "_addClass (msg)) != FUDGE_OK) return status"); endStmt(writer); if (message.getExtends() != null) { writer.write("if ((status = " + getIdentifier(message.getExtends()) + "_toFudgeMsgImpl (&ptr->fudgeParent, msg)) != FUDGE_OK) return status"); endStmt(writer); } for (FieldDefinition field : message.getFieldDefinitions()) { if (field.getOverride() != null) { continue; } writer.write("if ("); if (!field.isRequired()) { writer.write("ptr->" + privateFieldName(field) + " && "); } writer.write("(status = " + getIdentifier(message) + "_set" + camelCaseFieldName(field) + " (msg, "); if (!field.isRepeated() && !field.isRequired() && !isPointerType(field.getType())) writer.write("*"); writer.write("ptr->" + privateFieldName(field)); if (field.isRepeated()) { writer.write(", ptr->fudgeCount" + camelCaseFieldName(field)); } writer.write(")) != FUDGE_OK) return status"); endStmt(writer); } writer.write("return FUDGE_OK"); endStmt(writer); endBlock(writer); // toFudgeMsg } private void writeMessageAddClass(final IndentWriter writer, final MessageDefinition message) throws IOException { writer.write("FudgeStatus " + getIdentifier(message) + "_addClass (FudgeMsg msg)"); beginBlock(writer); // addClass writer.write("FudgeStatus status"); endStmt(writer); writer.write("fudge_i16 ordinal = 0"); endStmt(writer); writer.write("FudgeString className"); endStmt(writer); writer.write("if ((status = FudgeString_createFrom (&className, " + getIdentifier(message) + "_Class, " + message.getIdentifier().length() + " * sizeof (TCHAR))) != FUDGE_OK) return status"); endStmt(writer); writer.write("status = FudgeMsg_addFieldString (msg, 0, &ordinal, className)"); endStmt(writer); writer.write("FudgeString_release (className)"); endStmt(writer); writer.write("return status"); endStmt(writer); endBlock(writer); // addClass } @Override public void writeClassImplementationConstructor(final Compiler.Context context, final MessageDefinition message, final IndentWriter writer) throws IOException { writeMessageFree(writer, message); writeMessageFromFudgeMsg(writer, message); writeMessageIsClass(writer, message); writeMessageToFudgeMsg(writer, message); writeMessageAddClass(writer, message); } @Override public void writeEnumImplementationDeclaration(final Compiler.Context context, final EnumDefinition enumDefinition, final IndentWriter writer) throws IOException { super.writeEnumImplementationDeclaration(context, enumDefinition, writer); if (enumDefinition.getType() == Type.INTEGER_ENCODED) return; // no conversion functions (macros) // String constants for (Map.Entry<String, LiteralValue> entry : enumDefinition.getElements()) { LiteralValue value = entry.getValue(); if (value instanceof LiteralValue.NullValue) { value = ((LiteralValue.NullValue) value).inferString(entry.getKey()); } else { value = value.assignmentTo(context, FieldType.STRING_TYPE); } final byte[] utf8 = UTF8.encode(((LiteralValue.StringValue) value).get()); writer.write("static FudgeStringStatic _" + getIdentifier(enumDefinition) + "_" + entry.getKey() + " = { 0, \""); for (int i = 0; i < utf8.length; i++) { if (utf8[i] < 0) { writer.write("\\" + Integer.toOctalString(256 + utf8[i])); } else if (utf8[i] < 8) { writer.write("\\00" + Integer.toOctalString(256 + utf8[i])); } else if (utf8[i] < 32) { writer.write("\\0" + Integer.toOctalString(256 + utf8[i])); } else { writer.write((char) utf8[i]); } } writer.write("\", " + utf8.length + " }"); endStmt(writer); } writer.write("FudgeString " + getIdentifier(enumDefinition) + "_toFudgeEncoding (" + getIdentifier(enumDefinition) + " value)"); beginBlock(writer); // toFudgeEncoding writer.write("switch (value)"); beginBlock(writer); // switch for (Map.Entry<String, LiteralValue> entry : enumDefinition.getElements()) { writer.write("case " + getEnumValueIdentifier(enumDefinition, entry.getKey()) + " : return FudgeString_fromStatic (&_" + getIdentifier(enumDefinition) + "_" + entry.getKey() + ")"); endStmt(writer); } writer.write("default : return 0"); endStmt(writer); endBlock(writer); // switch endBlock(writer); // toFudgeEncoding writer.write(getIdentifier(enumDefinition) + " " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (FudgeString value)"); beginBlock(writer); // fromFudgeEncoding writer.write("if (!value) return (" + getIdentifier(enumDefinition) + ")-1"); endStmt(writer); for (Map.Entry<String, LiteralValue> entry : enumDefinition.getElements()) { writer.write("if (!FudgeString_compare (FudgeString_fromStatic (&_" + getIdentifier(enumDefinition) + "_" + entry.getKey() + "), value)) return " + getEnumValueIdentifier(enumDefinition, entry.getKey())); endStmt(writer); } writer.write("return (" + getIdentifier(enumDefinition) + ")-1"); endStmt(writer); endBlock(writer); // fromFudgeEncoding } @Override public void writeTaxonomyImplementationDeclaration(final Compiler.Context context, final TaxonomyDefinition taxonomyDefinition, final IndentWriter writer) throws IOException { comment(writer, "TODO taxonomy implementation declaration"); } @Override public void writeTypedefImplementationDeclaration(final Compiler.Context context, final TypeDefinition typedef, final IndentWriter writer) throws IOException { // no-op } private String messageType(final MessageDefinition message) { if (message == MessageDefinition.ANONYMOUS) { return "FudgeMsg"; } else { return "struct _" + getIdentifier(message) + '*'; } } private String typeString(final FieldType type, final boolean stringConstantPointer) { if (type instanceof FieldType.ArrayType) { final FieldType.ArrayType array = (FieldType.ArrayType) type; final StringBuilder sb = new StringBuilder(); sb.append(typeString(array.getBaseType(), false)); sb.append('*'); return sb.toString(); } else if (type instanceof FieldType.EnumType) { return "enum _" + getIdentifier(((FieldType.EnumType) type).getEnumDefinition()); } else if (type instanceof FieldType.MessageType) { return messageType(((FieldType.MessageType) type).getMessageDefinition()); } else if (type instanceof FieldType.UserType) { return typeString(((FieldType.UserType) type).getTypeDefinition().getUnderlyingType(), stringConstantPointer); } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: // We'll handle indicators as a boolean - was it in the message or not return "int"; case FudgeTypeDictionary.BOOLEAN_TYPE_ID: return "fudge_bool"; case FudgeTypeDictionary.BYTE_TYPE_ID: return "fudge_byte"; case FudgeTypeDictionary.SHORT_TYPE_ID: return "fudge_i16"; case FudgeTypeDictionary.INT_TYPE_ID: return "fudge_i32"; case FudgeTypeDictionary.LONG_TYPE_ID: return "fudge_i64"; case FudgeTypeDictionary.FLOAT_TYPE_ID: return "fudge_f32"; case FudgeTypeDictionary.DOUBLE_TYPE_ID: return "fudge_f64"; case FudgeTypeDictionary.STRING_TYPE_ID: return (stringConstantPointer ? "const " : "") + "TCHAR*"; case FudgeTypeDictionary.DATE_TYPE_ID: return "FudgeDate"; case FudgeTypeDictionary.DATETIME_TYPE_ID: return "FudgeDateTime"; case FudgeTypeDictionary.TIME_TYPE_ID: return "FudgeTime"; default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } } }
true
true
private void decodeFieldValue(final IndentWriter writer, final FieldType type, final String source, final String target, final Stack<String> unwind, final boolean allowNull) throws IOException { if (type instanceof FieldType.MessageType) { writer.write("if (" + source + ".type == FUDGE_TYPE_FUDGE_MSG)"); beginBlock(writer); writer.write("if ((status = "); if (type instanceof FieldType.AnonMessageType) { writer.write("FudgeMsg_retain (*" + target + " = " + source + ".data.message"); } else { writer.write(getIdentifier(((FieldType.MessageType) type).getMessageDefinition()) + "_fromFudgeMsg (" + source + ".data.message, " + target); } writer.write(")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); endBlock(writer); if (allowNull) { writer.write("else if (" + source + ".type == FUDGE_TYPE_INDICATOR) *" + target + " = 0"); endStmt(writer); } writer.write("else "); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); } else if (type instanceof FieldType.ArrayType) { final FieldType.ArrayType arrayType = (FieldType.ArrayType) type; switch (arrayType.getFudgeFieldType()) { case FudgeTypeDictionary.BYTE_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_4_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_4", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_8_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_8", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_16_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_16", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_20_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_20", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_32_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_32", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_64_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_64", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_128_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_128", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_256_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_256", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_512_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_512", "fudge_byte", unwind); break; case FudgeTypeDictionary.INT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_INT_ARRAY", "fudge_i32", unwind); break; case FudgeTypeDictionary.LONG_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_LONG_ARRAY", "fudge_i64", unwind); break; case FudgeTypeDictionary.SHORT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_SHORT_ARRAY", "fudge_i16", unwind); break; case FudgeTypeDictionary.FLOAT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_FLOAT_ARRAY", "fudge_f32", unwind); break; case FudgeTypeDictionary.DOUBLE_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_DOUBLE_ARRAY", "fudge_f64", unwind); break; case FudgeTypeDictionary.FUDGE_MSG_TYPE_ID: final String cType = typeString(arrayType.getBaseType(), false); final String varI = "i" + unwind.size(); final String varN = "n" + unwind.size(); final String varFields = "fields" + unwind.size(); writer.write("int " + varI + ", " + varN); endStmt(writer); writer.write("if (" + source + ".type != FUDGE_TYPE_FUDGE_MSG)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write(varN + " = FudgeMsg_numFields (" + source + ".data.message)"); endStmt(writer); writer.write("if (" + varN + " > 0)"); beginBlock(writer); // if writer.write("FudgeField *" + varFields); endStmt(writer); writer.write("if ((" + varFields + " = (FudgeField*)malloc (sizeof (FudgeField) * " + varN + ")) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); unwind.push("free (" + varFields + ")"); writer.write("if (FudgeMsg_getFields (" + varFields + ", " + varN + ", " + source + ".data.message) <= 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write("if ((*" + target + " = (" + cType + "*)malloc (sizeof (" + cType + ") * (" + varN + " + 1))) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*" + target + ", 0, sizeof (" + cType + ") * (" + varN + " + 1))"); endStmt(writer); if (unwind.size() == 1) { final StringBuilder sb = new StringBuilder(); if (isPointerType(arrayType.getBaseType())) { sb.append("do "); sb.append(getFreeFieldValueStmt(arrayType.getBaseType(), "*(*" + target + " + " + varI + ")", false, 0)); if (sb.charAt(sb.length() - 1) != '}') { sb.append(';'); } sb.append(" while (--" + varI + " >= 0); "); } sb.append("free (*" + target + "); *" + target + " = 0"); unwind.push(sb.toString()); } writer.write("for (" + varI + " = 0; " + varI + " < " + varN + "; " + varI + "++)"); beginBlock(writer); // for decodeFieldValue(writer, arrayType.getBaseType(), varFields + "[" + varI + "]", "(*" + target + " + " + varI + ")", unwind, true); endBlock(writer); // for if (unwind.size() == 2) { unwind.pop(); // memory allocation release } writer.write(unwind.pop()); endStmt(writer); endBlock(writer); // if writer.write("else"); beginBlock(writer); // else writer.write("if ((*" + target + " = (" + cType + "*)malloc (sizeof (" + cType + "))) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*" + target + ", 0, sizeof (" + cType + "))"); endStmt(writer); endBlock(writer); // else break; default: throw new IllegalStateException("Type " + arrayType + " is not expected type"); } } else if (type instanceof FieldType.EnumType) { final EnumDefinition enumDefinition = ((FieldType.EnumType) type).getEnumDefinition(); if (enumDefinition.getType() == EnumDefinition.Type.INTEGER_ENCODED) { final String varI = "i" + unwind.size(); writer.write("int " + varI); endStmt(writer); writer.write("if ((status = FudgeMsg_getFieldAsI32 (&" + source + ", &" + varI + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); writer.write("*" + target + " = " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (" + varI + ")"); endStmt(writer); } else { writer.write("if (" + source + ".type == FUDGE_TYPE_STRING) *" + target + " = " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (" + source + ".data.string)"); endStmt(writer); if (allowNull) { writer.write("else if (" + source + ".type == FUDGE_TYPE_INDICATOR) *" + target + " = 0"); endStmt(writer); } writer.write("else "); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); } } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: // No code needed break; case FudgeTypeDictionary.BOOLEAN_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsBoolean (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.BYTE_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsByte (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.SHORT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI16 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.INT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI32 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.LONG_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI64 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.FLOAT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsF32 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.DOUBLE_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsF64 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.STRING_TYPE_ID: final String varLen = "len" + unwind.size(); writer.write("int " + varLen); endStmt(writer); fieldValueToString(writer, source, "*" + target, unwind, allowNull, varLen); break; case FudgeTypeDictionary.DATE_TYPE_ID: comment(writer, "TODO date type"); break; case FudgeTypeDictionary.DATETIME_TYPE_ID: comment(writer, "TODO datetime type"); break; case FudgeTypeDictionary.TIME_TYPE_ID: comment(writer, "TODO time type"); break; default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } }
private void decodeFieldValue(final IndentWriter writer, final FieldType type, final String source, final String target, final Stack<String> unwind, final boolean allowNull) throws IOException { if (type instanceof FieldType.MessageType) { writer.write("if (" + source + ".type == FUDGE_TYPE_FUDGE_MSG)"); beginBlock(writer); writer.write("if ((status = "); if (type instanceof FieldType.AnonMessageType) { writer.write("FudgeMsg_retain (*" + target + " = " + source + ".data.message"); } else { writer.write(getIdentifier(((FieldType.MessageType) type).getMessageDefinition()) + "_fromFudgeMsg (" + source + ".data.message, " + target); } writer.write(")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); endBlock(writer); if (allowNull) { writer.write("else if (" + source + ".type == FUDGE_TYPE_INDICATOR) *" + target + " = 0"); endStmt(writer); } writer.write("else "); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); } else if (type instanceof FieldType.ArrayType) { final FieldType.ArrayType arrayType = (FieldType.ArrayType) type; switch (arrayType.getFudgeFieldType()) { case FudgeTypeDictionary.BYTE_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_4_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_4", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_8_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_8", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_16_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_16", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_20_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_20", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_32_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_32", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_64_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_64", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_128_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_128", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_256_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_256", "fudge_byte", unwind); break; case FudgeTypeDictionary.BYTE_ARR_512_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_BYTE_ARRAY_512", "fudge_byte", unwind); break; case FudgeTypeDictionary.INT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_INT_ARRAY", "fudge_i32", unwind); break; case FudgeTypeDictionary.LONG_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_LONG_ARRAY", "fudge_i64", unwind); break; case FudgeTypeDictionary.SHORT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_SHORT_ARRAY", "fudge_i16", unwind); break; case FudgeTypeDictionary.FLOAT_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_FLOAT_ARRAY", "fudge_f32", unwind); break; case FudgeTypeDictionary.DOUBLE_ARRAY_TYPE_ID: decodeArrayValue(writer, source, target, "FUDGE_TYPE_DOUBLE_ARRAY", "fudge_f64", unwind); break; case FudgeTypeDictionary.FUDGE_MSG_TYPE_ID: final String cType = typeString(arrayType.getBaseType(), false); final String varI = "i" + unwind.size(); final String varN = "n" + unwind.size(); final String varFields = "fields" + unwind.size(); writer.write("int " + varI + ", " + varN); endStmt(writer); writer.write("if (" + source + ".type != FUDGE_TYPE_FUDGE_MSG)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write(varN + " = FudgeMsg_numFields (" + source + ".data.message)"); endStmt(writer); writer.write("if (" + varN + " > 0)"); beginBlock(writer); // if writer.write("FudgeField *" + varFields); endStmt(writer); writer.write("if ((" + varFields + " = (FudgeField*)malloc (sizeof (FudgeField) * " + varN + ")) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); unwind.push("free (" + varFields + ")"); writer.write("if (FudgeMsg_getFields (" + varFields + ", " + varN + ", " + source + ".data.message) <= 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); writer.write("if ((*" + target + " = (" + cType + "*)malloc (sizeof (" + cType + ") * (" + varN + " + 1))) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*" + target + ", 0, sizeof (" + cType + ") * (" + varN + " + 1))"); endStmt(writer); if (unwind.size() == 1) { final StringBuilder sb = new StringBuilder(); if (isPointerType(arrayType.getBaseType())) { sb.append("do "); sb.append(getFreeFieldValueStmt(arrayType.getBaseType(), "*(*" + target + " + " + varI + ")", false, 0)); if (sb.charAt(sb.length() - 1) != '}') { sb.append(';'); } sb.append(" while (--" + varI + " >= 0); "); } sb.append("free (*" + target + "); *" + target + " = 0"); unwind.push(sb.toString()); } writer.write("for (" + varI + " = 0; " + varI + " < " + varN + "; " + varI + "++)"); beginBlock(writer); // for decodeFieldValue(writer, arrayType.getBaseType(), varFields + "[" + varI + "]", "(*" + target + " + " + varI + ")", unwind, true); endBlock(writer); // for if (unwind.size() == 2) { unwind.pop(); // memory allocation release } writer.write(unwind.pop()); endStmt(writer); endBlock(writer); // if writer.write("else"); beginBlock(writer); // else writer.write("if ((*" + target + " = (" + cType + "*)malloc (sizeof (" + cType + "))) == 0)"); returnAndUnwindStmt(writer, unwind, "FUDGE_OUT_OF_MEMORY"); writer.write("memset (*" + target + ", 0, sizeof (" + cType + "))"); endStmt(writer); endBlock(writer); // else break; default: throw new IllegalStateException("Type " + arrayType + " is not expected type"); } } else if (type instanceof FieldType.EnumType) { final EnumDefinition enumDefinition = ((FieldType.EnumType) type).getEnumDefinition(); if (enumDefinition.getType() == EnumDefinition.Type.INTEGER_ENCODED) { final String varI = "i" + unwind.size(); writer.write("int " + varI); endStmt(writer); writer.write("if ((status = FudgeMsg_getFieldAsI32 (&" + source + ", &" + varI + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); writer.write("*" + target + " = " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (" + varI + ")"); endStmt(writer); } else { writer.write("if (" + source + ".type == FUDGE_TYPE_STRING) *" + target + " = " + getIdentifier(enumDefinition) + "_fromFudgeEncoding (" + source + ".data.string)"); endStmt(writer); if (allowNull) { writer.write("else if (" + source + ".type == FUDGE_TYPE_INDICATOR) *" + target + " = 0"); endStmt(writer); } writer.write("else "); returnAndUnwindStmt(writer, unwind, "FUDGE_INVALID_TYPE_COERCION"); } } else { switch (type.getFudgeFieldType()) { case FudgeTypeDictionary.INDICATOR_TYPE_ID: // No code needed break; case FudgeTypeDictionary.BOOLEAN_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsBoolean (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.BYTE_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsByte (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.SHORT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI16 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.INT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI32 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.LONG_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsI64 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.FLOAT_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsF32 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.DOUBLE_TYPE_ID: writer.write("if ((status = FudgeMsg_getFieldAsF64 (&" + source + ", " + target + ")) != FUDGE_OK)"); returnAndUnwindStmt(writer, unwind, "status"); break; case FudgeTypeDictionary.STRING_TYPE_ID: final String varLen = "len" + unwind.size(); writer.write("size_t " + varLen); endStmt(writer); fieldValueToString(writer, source, "*" + target, unwind, allowNull, varLen); break; case FudgeTypeDictionary.DATE_TYPE_ID: comment(writer, "TODO date type"); break; case FudgeTypeDictionary.DATETIME_TYPE_ID: comment(writer, "TODO datetime type"); break; case FudgeTypeDictionary.TIME_TYPE_ID: comment(writer, "TODO time type"); break; default: throw new IllegalStateException("type '" + type + "' is not an expected type (fudge field type " + type.getFudgeFieldType() + ")"); } } }
diff --git a/src/com/iBank/iBank.java b/src/com/iBank/iBank.java index 46ab584..9eccac7 100644 --- a/src/com/iBank/iBank.java +++ b/src/com/iBank/iBank.java @@ -1,528 +1,528 @@ package com.iBank; import java.io.File; import java.io.InputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.logging.Level; import java.util.logging.Logger; import net.milkbowl.vault.economy.Economy; import net.milkbowl.vault.permission.Permission; import org.bukkit.Location; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Listener; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import com.iBank.Commands.BankRootCommand; import com.iBank.Commands.CommandAddRegion; import com.iBank.Commands.CommandBalance; import com.iBank.Commands.CommandClose; import com.iBank.Commands.CommandDelRegion; import com.iBank.Commands.CommandDelete; import com.iBank.Commands.CommandDeposit; import com.iBank.Commands.CommandGive; import com.iBank.Commands.CommandHelp; import com.iBank.Commands.CommandList; import com.iBank.Commands.CommandLoan; import com.iBank.Commands.CommandLoanEdit; import com.iBank.Commands.CommandLoanInfo; import com.iBank.Commands.CommandManager; import com.iBank.Commands.CommandOpenAccount; import com.iBank.Commands.CommandOwners; import com.iBank.Commands.CommandPayBack; import com.iBank.Commands.CommandRegion; import com.iBank.Commands.CommandReload; import com.iBank.Commands.CommandTransfer; import com.iBank.Commands.CommandUsers; import com.iBank.Commands.CommandWithdraw; import com.iBank.Database.DataSource; import com.iBank.Database.DataSource.Drivers; import com.iBank.Listeners.iBankListener; import com.iBank.system.Bank; import com.iBank.system.CommandHandler; import com.iBank.system.CommandTake; import com.iBank.system.Commands; import com.iBank.system.Configuration; import com.iBank.system.Region; import com.iBank.utils.Mathematics; import com.iBank.utils.StreamUtils; /** * IBank * @author steffengy * @copyright Copyright steffengy (C) 2012 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class iBank extends JavaPlugin { private YamlConfiguration StringConfig = null; private YamlConfiguration Config = null; private File ConfigFile = null; private File StringFile = null; private static final Logger log = Logger.getLogger("Minecraft"); public static PluginDescriptionFile description = null; public Listener Listener = new iBankListener(); private static Permission permission = null; public static Economy economy = null; public static String CodeName = "Weezle"; public static DataSource data = new DataSource(); private Timer Loan = null; private Timer Interest = null; public static List<String> connected = new ArrayList<String>(); public static HashMap<String, String> loggedinto = new HashMap<String, String>(); @Override public void onEnable() { if(!(getDataFolder().exists())) getDataFolder().mkdir(); // Load configuration + strings reloadConfig(); loadStrings(); Configuration.init(Config); Configuration.stringinit(StringConfig); if(!Configuration.Entry.Enabled.getBoolean()) { System.out.println("[iBank] Disabled as configured in configuration"); getServer().getPluginManager().disablePlugin(this); return; } // Load permissions + economy system via Vault if(!setupEconomy()) { log.log(Level.SEVERE, String.format("[%s] - Disabled due to no Vault/economy dependency found!", getDescription().getName())); getServer().getPluginManager().disablePlugin(this); } setupPermissions(); //Register Commands Commands.setVarSource(this); Commands.addRootCommand("bank"); Commands.setTag("&g&[&w&Bank&g&] "); Commands.addSubCommand("bank", "help"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.HelpDescription.getValue()); Commands.setHandler(new CommandHelp("bank")); Commands.setHelpArgs("(site)"); Commands.addSubCommand("bank", ""); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.BankDescription.getValue()); Commands.setHandler(new BankRootCommand()); Commands.addSubCommand("bank", "addregion"); Commands.setPermission("iBank.regions"); Commands.setHelp(Configuration.StringEntry.AddRegionDescription.getValue()); Commands.setHandler(new CommandAddRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "delregion"); Commands.setPermission("iBank.regions"); Commands.setHelp(Configuration.StringEntry.DelRegionDescription.getValue()); Commands.setHandler(new CommandDelRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "region"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.RegionDescription.getValue()); Commands.setHandler(new CommandRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "open"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.OpenAccountDescription.getValue()); Commands.setHandler(new CommandOpenAccount()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "balance"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.BalanceDescription.getValue()); Commands.setHandler(new CommandBalance()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "list"); Commands.setPermission("iBank.list"); Commands.setHelp(Configuration.StringEntry.ListDescription.getValue()); Commands.setHandler(new CommandList()); Commands.setHelpArgs("(Player)"); Commands.addSubCommand("bank", "deposit"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.DepositDescription.getValue()); Commands.setHandler(new CommandDeposit()); Commands.setHelpArgs("[Name] [Amount]"); Commands.addSubCommand("bank", "withdraw"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.WithdrawDescription.getValue()); Commands.setHandler(new CommandWithdraw()); Commands.setHelpArgs("[Name] [Amount]"); Commands.addSubCommand("bank", "transfer"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.TransferDescription.getValue()); Commands.setHandler(new CommandTransfer()); Commands.setHelpArgs("[Src] [Dest] [Amount]"); Commands.addSubCommand("bank", "account"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.AccountDescription.getValue()); Commands.setHandler(new CommandManager()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "owners"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.OwnersDescription.getValue()); Commands.setHandler(new CommandOwners()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "users"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.UsersDescription.getValue()); Commands.setHandler(new CommandUsers()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "give"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.GiveDescription.getValue()); Commands.setHandler(new CommandGive()); Commands.setHelpArgs("[Player] [Amount]"); Commands.addSubCommand("bank", "take"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.TakeDescription.getValue()); Commands.setHandler(new CommandTake()); Commands.setHelpArgs("[Player] [Amount]"); Commands.addSubCommand("bank", "delete"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.DeleteDescription.getValue()); Commands.setHandler(new CommandDelete()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "close"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.CloseDescription.getValue()); Commands.setHandler(new CommandClose()); Commands.setHelpArgs("[Name]"); if(Configuration.Entry.Loan.getBoolean()) { Commands.addSubCommand("bank", "loan"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.LoanDescription.getValue()); Commands.setHandler(new CommandLoan()); Commands.setHelpArgs("[Amount]"); Commands.addSubCommand("bank", "loaninfo"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.LoanInfoDescription.getValue()); Commands.setHandler(new CommandLoanInfo()); - Commands.setHelpArgs("(:Site|Player)"); + Commands.setHelpArgs("(Site|Player)"); Commands.addSubCommand("bank", "loanedit"); Commands.setPermission("iBank.loanedit"); Commands.setHelp(Configuration.StringEntry.LoanEditDescription.getValue()); Commands.setHandler(new CommandLoanEdit()); Commands.setHelpArgs("[id] (Key) (Value)"); Commands.addSubCommand("bank", "payback"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.PayBackDescription.getValue()); Commands.setHandler(new CommandPayBack()); Commands.setHelpArgs("(id) [amount]"); } Commands.addSubCommand("bank", "reload"); Commands.setPermission("iBank.reload"); Commands.setHelp(Configuration.StringEntry.ReloadDescription.getValue()); Commands.setHandler(new CommandReload()); description = this.getDescription(); //DB if(Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("sqlite") || Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("mysql")) { if(Configuration.Entry.DatabaseUrl.getValue().toString() != null) { // connect Drivers driver = DataSource.Drivers.SQLite; if(Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("mysql")) { driver = DataSource.Drivers.MYSQL; } if(!DataSource.setup(driver, Configuration.Entry.DatabaseUrl.getValue().toString(), this)) { System.out.println("[iBank] Database connection failed! Shuting down iBank..."); getServer().getPluginManager().disablePlugin(this); return; } }else{ System.out.println("[iBank] Database connection failed! No File specified!"); } }else{ if(Configuration.Entry.DatabaseUrl.getValue().toString() != null) { // connect if(!DataSource.setup(DataSource.Drivers.SQLite, Configuration.Entry.DatabaseUrl.getValue().toString(), this)) { System.out.println("[iBank] Database connection failed! Shuting down iBank..."); getServer().getPluginManager().disablePlugin(this); return; } }else{ getServer().getPluginManager().disablePlugin(this); return; } } //Register events getServer().getPluginManager().registerEvents(Listener, this); //start interest syncer if(Configuration.Entry.InterestEnabled.getBoolean()) { new Thread(new Runnable() { @Override public void run() { long time = 60L * 1000L; Interest = new Timer(); Interest.scheduleAtFixedRate(new BankInterest(), time, time); } }).start(); } //start loan syncer if(Configuration.Entry.Loan.getBoolean()) { new Thread(new Runnable() { @Override public void run() { long time = 60L * 1000L; Loan = new Timer(); Loan.scheduleAtFixedRate(new BankLoan(), time, time); } }).start(); } System.out.println("[iBank] Version "+description.getVersion()+" "+CodeName+" loaded successfully!"); } @Override public void onDisable() { DataSource.shutdown(); //Kill timers if(Interest != null) { Interest.cancel(); Interest.purge(); Interest = null; } if(Loan != null) { Loan.cancel(); Loan.purge(); Loan = null; } System.out.println("[iBank] unloaded"); } /** * Reloads the config */ public void reloadConfig() { if(ConfigFile == null) { ConfigFile = new File(getDataFolder(), "config.yml"); } if(ConfigFile.exists()) { Config = YamlConfiguration.loadConfiguration(ConfigFile); }else{ if(StreamUtils.copy(getResource("config.yml"), ConfigFile)) { Config = YamlConfiguration.loadConfiguration(ConfigFile); }else{ System.out.println("[iBank] OOPS! Failed loading config!"); } } } /** * Loads the strings file */ private void loadStrings() { if(StringFile == null) { StringFile = new File(getDataFolder(), "strings.yml"); } StringConfig = YamlConfiguration.loadConfiguration(StringFile); //Get default config InputStream defConfigStream = getResource("strings.yml"); if (defConfigStream != null) { YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream); StringConfig.setDefaults(defConfig); } } /** * Vault Function to setup the permissions */ private Boolean setupPermissions() { RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.permission.Permission.class); if (permissionProvider != null) { permission = permissionProvider.getProvider(); } return (permission != null); } /**0 * Vault function to setup Economy */ private Boolean setupEconomy() { if (getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class); if (economyProvider != null) { economy = economyProvider.getProvider(); } return (economy != null); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { return CommandHandler.parse(cmd.getName(), args, sender); } /** * Checks if a player can execute this command * !NO PERMISSION CHECK! * @param l The location of the player * @param p The player * @return boolean */ public static boolean canExecuteCommand(Player p) { if(!Configuration.Entry.BoundToRegion.getBoolean()) return true; if(hasPermission(p, "iBank.global")) return true; Location l = p.getLocation(); return regionAt(l) == null ? false : true; } /** * Gets a region at given location * @param l The location * @return Name of region or null */ public static String regionAt(Location l) { double x = l.getX(); double y = l.getY(); double z = l.getZ(); Region tmp; for(String i : Bank.getRegions()) { tmp = Bank.getRegion(i); if(l.getWorld() == tmp.getFirstLocation().getWorld()) { if(Mathematics.isInBox(x,y,z,tmp.getFirstLocation().getX(),tmp.getFirstLocation().getY(),tmp.getFirstLocation().getZ(),tmp.getSecondLocation().getX(),tmp.getSecondLocation().getY(),tmp.getSecondLocation().getZ())) { return i; } } } return null; } /** * Formats an big Integer * @param todp The amount * @return String * (probalby wrong formated due to BigInteger/double limits */ public static String format(BigDecimal todp) { return economy.format(todp.doubleValue()); } /** * Calculates the fee by a given fee and a config-string * @param fee The to apply fee * @param due The value, which shall be applied to * @return BigDecimal The fee value */ public static BigDecimal parseFee(String fee, BigDecimal due) { BigDecimal val = new BigDecimal("0.00"); //check if percentage or static amount if(fee.contains("+")) { String[] plus = fee.split("+"); val = val.add(parseFeeString(plus[0], due)); val = val.add(parseFeeString(plus[1], due)); }else if(fee.contains("-")) { String[] minus = fee.split("-"); val = val.subtract(parseFeeString(minus[0], due)); val = val.subtract(parseFeeString(minus[1], due)); }else{ val = parseFeeString(fee, due); } return val; } /** * Parses a single part of a feestring * @param part The part * @param due The due * @return */ public static BigDecimal parseFeeString(String part, BigDecimal due) { BigDecimal tmp = new BigDecimal("0.00"); if(part.endsWith("%")) { tmp = tmp.add(due.multiply(new BigDecimal(Double.parseDouble(part.replace("%","")) / 100))); }else{ tmp = tmp.add(new BigDecimal(Double.parseDouble(part))); } return tmp; } /** * Checks if an user has a permission * @param user The Player * @param permission The permission * @return boolean */ public static boolean hasPermission(Player user, String permission) { if(iBank.permission.isEnabled()) { return iBank.permission.has(user, permission); }else{ return (user).hasPermission(permission); } } /** * Checks if a command sender has a permission * @param user CommandSender * @param permission Permission * @return boolean */ public static boolean hasPermission(CommandSender user, String permission) { if(!(user instanceof Player)) return true; return hasPermission((Player)user, permission); } /** * Disables all commands of a player, and connects him with * the directbank * @param player * @param what What to login? */ public static void login(String player) { connected.add(player); } /** * Debinds a player from directbank * @param player */ public static void logout(String player) { if(connected.contains(player)) connected.remove(player); } }
true
true
public void onEnable() { if(!(getDataFolder().exists())) getDataFolder().mkdir(); // Load configuration + strings reloadConfig(); loadStrings(); Configuration.init(Config); Configuration.stringinit(StringConfig); if(!Configuration.Entry.Enabled.getBoolean()) { System.out.println("[iBank] Disabled as configured in configuration"); getServer().getPluginManager().disablePlugin(this); return; } // Load permissions + economy system via Vault if(!setupEconomy()) { log.log(Level.SEVERE, String.format("[%s] - Disabled due to no Vault/economy dependency found!", getDescription().getName())); getServer().getPluginManager().disablePlugin(this); } setupPermissions(); //Register Commands Commands.setVarSource(this); Commands.addRootCommand("bank"); Commands.setTag("&g&[&w&Bank&g&] "); Commands.addSubCommand("bank", "help"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.HelpDescription.getValue()); Commands.setHandler(new CommandHelp("bank")); Commands.setHelpArgs("(site)"); Commands.addSubCommand("bank", ""); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.BankDescription.getValue()); Commands.setHandler(new BankRootCommand()); Commands.addSubCommand("bank", "addregion"); Commands.setPermission("iBank.regions"); Commands.setHelp(Configuration.StringEntry.AddRegionDescription.getValue()); Commands.setHandler(new CommandAddRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "delregion"); Commands.setPermission("iBank.regions"); Commands.setHelp(Configuration.StringEntry.DelRegionDescription.getValue()); Commands.setHandler(new CommandDelRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "region"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.RegionDescription.getValue()); Commands.setHandler(new CommandRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "open"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.OpenAccountDescription.getValue()); Commands.setHandler(new CommandOpenAccount()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "balance"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.BalanceDescription.getValue()); Commands.setHandler(new CommandBalance()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "list"); Commands.setPermission("iBank.list"); Commands.setHelp(Configuration.StringEntry.ListDescription.getValue()); Commands.setHandler(new CommandList()); Commands.setHelpArgs("(Player)"); Commands.addSubCommand("bank", "deposit"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.DepositDescription.getValue()); Commands.setHandler(new CommandDeposit()); Commands.setHelpArgs("[Name] [Amount]"); Commands.addSubCommand("bank", "withdraw"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.WithdrawDescription.getValue()); Commands.setHandler(new CommandWithdraw()); Commands.setHelpArgs("[Name] [Amount]"); Commands.addSubCommand("bank", "transfer"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.TransferDescription.getValue()); Commands.setHandler(new CommandTransfer()); Commands.setHelpArgs("[Src] [Dest] [Amount]"); Commands.addSubCommand("bank", "account"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.AccountDescription.getValue()); Commands.setHandler(new CommandManager()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "owners"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.OwnersDescription.getValue()); Commands.setHandler(new CommandOwners()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "users"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.UsersDescription.getValue()); Commands.setHandler(new CommandUsers()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "give"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.GiveDescription.getValue()); Commands.setHandler(new CommandGive()); Commands.setHelpArgs("[Player] [Amount]"); Commands.addSubCommand("bank", "take"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.TakeDescription.getValue()); Commands.setHandler(new CommandTake()); Commands.setHelpArgs("[Player] [Amount]"); Commands.addSubCommand("bank", "delete"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.DeleteDescription.getValue()); Commands.setHandler(new CommandDelete()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "close"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.CloseDescription.getValue()); Commands.setHandler(new CommandClose()); Commands.setHelpArgs("[Name]"); if(Configuration.Entry.Loan.getBoolean()) { Commands.addSubCommand("bank", "loan"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.LoanDescription.getValue()); Commands.setHandler(new CommandLoan()); Commands.setHelpArgs("[Amount]"); Commands.addSubCommand("bank", "loaninfo"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.LoanInfoDescription.getValue()); Commands.setHandler(new CommandLoanInfo()); Commands.setHelpArgs("(:Site|Player)"); Commands.addSubCommand("bank", "loanedit"); Commands.setPermission("iBank.loanedit"); Commands.setHelp(Configuration.StringEntry.LoanEditDescription.getValue()); Commands.setHandler(new CommandLoanEdit()); Commands.setHelpArgs("[id] (Key) (Value)"); Commands.addSubCommand("bank", "payback"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.PayBackDescription.getValue()); Commands.setHandler(new CommandPayBack()); Commands.setHelpArgs("(id) [amount]"); } Commands.addSubCommand("bank", "reload"); Commands.setPermission("iBank.reload"); Commands.setHelp(Configuration.StringEntry.ReloadDescription.getValue()); Commands.setHandler(new CommandReload()); description = this.getDescription(); //DB if(Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("sqlite") || Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("mysql")) { if(Configuration.Entry.DatabaseUrl.getValue().toString() != null) { // connect Drivers driver = DataSource.Drivers.SQLite; if(Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("mysql")) { driver = DataSource.Drivers.MYSQL; } if(!DataSource.setup(driver, Configuration.Entry.DatabaseUrl.getValue().toString(), this)) { System.out.println("[iBank] Database connection failed! Shuting down iBank..."); getServer().getPluginManager().disablePlugin(this); return; } }else{ System.out.println("[iBank] Database connection failed! No File specified!"); } }else{ if(Configuration.Entry.DatabaseUrl.getValue().toString() != null) { // connect if(!DataSource.setup(DataSource.Drivers.SQLite, Configuration.Entry.DatabaseUrl.getValue().toString(), this)) { System.out.println("[iBank] Database connection failed! Shuting down iBank..."); getServer().getPluginManager().disablePlugin(this); return; } }else{ getServer().getPluginManager().disablePlugin(this); return; } } //Register events getServer().getPluginManager().registerEvents(Listener, this); //start interest syncer if(Configuration.Entry.InterestEnabled.getBoolean()) { new Thread(new Runnable() { @Override public void run() { long time = 60L * 1000L; Interest = new Timer(); Interest.scheduleAtFixedRate(new BankInterest(), time, time); } }).start(); } //start loan syncer if(Configuration.Entry.Loan.getBoolean()) { new Thread(new Runnable() { @Override public void run() { long time = 60L * 1000L; Loan = new Timer(); Loan.scheduleAtFixedRate(new BankLoan(), time, time); } }).start(); } System.out.println("[iBank] Version "+description.getVersion()+" "+CodeName+" loaded successfully!"); }
public void onEnable() { if(!(getDataFolder().exists())) getDataFolder().mkdir(); // Load configuration + strings reloadConfig(); loadStrings(); Configuration.init(Config); Configuration.stringinit(StringConfig); if(!Configuration.Entry.Enabled.getBoolean()) { System.out.println("[iBank] Disabled as configured in configuration"); getServer().getPluginManager().disablePlugin(this); return; } // Load permissions + economy system via Vault if(!setupEconomy()) { log.log(Level.SEVERE, String.format("[%s] - Disabled due to no Vault/economy dependency found!", getDescription().getName())); getServer().getPluginManager().disablePlugin(this); } setupPermissions(); //Register Commands Commands.setVarSource(this); Commands.addRootCommand("bank"); Commands.setTag("&g&[&w&Bank&g&] "); Commands.addSubCommand("bank", "help"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.HelpDescription.getValue()); Commands.setHandler(new CommandHelp("bank")); Commands.setHelpArgs("(site)"); Commands.addSubCommand("bank", ""); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.BankDescription.getValue()); Commands.setHandler(new BankRootCommand()); Commands.addSubCommand("bank", "addregion"); Commands.setPermission("iBank.regions"); Commands.setHelp(Configuration.StringEntry.AddRegionDescription.getValue()); Commands.setHandler(new CommandAddRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "delregion"); Commands.setPermission("iBank.regions"); Commands.setHelp(Configuration.StringEntry.DelRegionDescription.getValue()); Commands.setHandler(new CommandDelRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "region"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.RegionDescription.getValue()); Commands.setHandler(new CommandRegion()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "open"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.OpenAccountDescription.getValue()); Commands.setHandler(new CommandOpenAccount()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "balance"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.BalanceDescription.getValue()); Commands.setHandler(new CommandBalance()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "list"); Commands.setPermission("iBank.list"); Commands.setHelp(Configuration.StringEntry.ListDescription.getValue()); Commands.setHandler(new CommandList()); Commands.setHelpArgs("(Player)"); Commands.addSubCommand("bank", "deposit"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.DepositDescription.getValue()); Commands.setHandler(new CommandDeposit()); Commands.setHelpArgs("[Name] [Amount]"); Commands.addSubCommand("bank", "withdraw"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.WithdrawDescription.getValue()); Commands.setHandler(new CommandWithdraw()); Commands.setHelpArgs("[Name] [Amount]"); Commands.addSubCommand("bank", "transfer"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.TransferDescription.getValue()); Commands.setHandler(new CommandTransfer()); Commands.setHelpArgs("[Src] [Dest] [Amount]"); Commands.addSubCommand("bank", "account"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.AccountDescription.getValue()); Commands.setHandler(new CommandManager()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "owners"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.OwnersDescription.getValue()); Commands.setHandler(new CommandOwners()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "users"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.UsersDescription.getValue()); Commands.setHandler(new CommandUsers()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "give"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.GiveDescription.getValue()); Commands.setHandler(new CommandGive()); Commands.setHelpArgs("[Player] [Amount]"); Commands.addSubCommand("bank", "take"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.TakeDescription.getValue()); Commands.setHandler(new CommandTake()); Commands.setHelpArgs("[Player] [Amount]"); Commands.addSubCommand("bank", "delete"); Commands.setPermission("iBank.manage"); Commands.setHelp(Configuration.StringEntry.DeleteDescription.getValue()); Commands.setHandler(new CommandDelete()); Commands.setHelpArgs("[Name]"); Commands.addSubCommand("bank", "close"); Commands.setPermission("iBank.access"); Commands.setHelp(Configuration.StringEntry.CloseDescription.getValue()); Commands.setHandler(new CommandClose()); Commands.setHelpArgs("[Name]"); if(Configuration.Entry.Loan.getBoolean()) { Commands.addSubCommand("bank", "loan"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.LoanDescription.getValue()); Commands.setHandler(new CommandLoan()); Commands.setHelpArgs("[Amount]"); Commands.addSubCommand("bank", "loaninfo"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.LoanInfoDescription.getValue()); Commands.setHandler(new CommandLoanInfo()); Commands.setHelpArgs("(Site|Player)"); Commands.addSubCommand("bank", "loanedit"); Commands.setPermission("iBank.loanedit"); Commands.setHelp(Configuration.StringEntry.LoanEditDescription.getValue()); Commands.setHandler(new CommandLoanEdit()); Commands.setHelpArgs("[id] (Key) (Value)"); Commands.addSubCommand("bank", "payback"); Commands.setPermission("iBank.loan"); Commands.setHelp(Configuration.StringEntry.PayBackDescription.getValue()); Commands.setHandler(new CommandPayBack()); Commands.setHelpArgs("(id) [amount]"); } Commands.addSubCommand("bank", "reload"); Commands.setPermission("iBank.reload"); Commands.setHelp(Configuration.StringEntry.ReloadDescription.getValue()); Commands.setHandler(new CommandReload()); description = this.getDescription(); //DB if(Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("sqlite") || Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("mysql")) { if(Configuration.Entry.DatabaseUrl.getValue().toString() != null) { // connect Drivers driver = DataSource.Drivers.SQLite; if(Configuration.Entry.DatabaseType.getValue().toString().equalsIgnoreCase("mysql")) { driver = DataSource.Drivers.MYSQL; } if(!DataSource.setup(driver, Configuration.Entry.DatabaseUrl.getValue().toString(), this)) { System.out.println("[iBank] Database connection failed! Shuting down iBank..."); getServer().getPluginManager().disablePlugin(this); return; } }else{ System.out.println("[iBank] Database connection failed! No File specified!"); } }else{ if(Configuration.Entry.DatabaseUrl.getValue().toString() != null) { // connect if(!DataSource.setup(DataSource.Drivers.SQLite, Configuration.Entry.DatabaseUrl.getValue().toString(), this)) { System.out.println("[iBank] Database connection failed! Shuting down iBank..."); getServer().getPluginManager().disablePlugin(this); return; } }else{ getServer().getPluginManager().disablePlugin(this); return; } } //Register events getServer().getPluginManager().registerEvents(Listener, this); //start interest syncer if(Configuration.Entry.InterestEnabled.getBoolean()) { new Thread(new Runnable() { @Override public void run() { long time = 60L * 1000L; Interest = new Timer(); Interest.scheduleAtFixedRate(new BankInterest(), time, time); } }).start(); } //start loan syncer if(Configuration.Entry.Loan.getBoolean()) { new Thread(new Runnable() { @Override public void run() { long time = 60L * 1000L; Loan = new Timer(); Loan.scheduleAtFixedRate(new BankLoan(), time, time); } }).start(); } System.out.println("[iBank] Version "+description.getVersion()+" "+CodeName+" loaded successfully!"); }
diff --git a/src/net/rptools/maptool/model/vision/FacingConicVision.java b/src/net/rptools/maptool/model/vision/FacingConicVision.java index 4b20274c..92c512b9 100644 --- a/src/net/rptools/maptool/model/vision/FacingConicVision.java +++ b/src/net/rptools/maptool/model/vision/FacingConicVision.java @@ -1,81 +1,81 @@ package net.rptools.maptool.model.vision; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.Ellipse2D; import net.rptools.maptool.client.MapTool; import net.rptools.maptool.model.GUID; import net.rptools.maptool.model.Token; import net.rptools.maptool.model.Vision; import net.rptools.maptool.model.Zone; import net.rptools.maptool.model.Vision.Anchor; public class FacingConicVision extends Vision { private Integer lastFacing; private GUID tokenGUID; public FacingConicVision(GUID tokenGUID) { this(tokenGUID, 0); } public FacingConicVision(GUID tokenGUID, int distance) { setDistance(distance); this.tokenGUID = tokenGUID; } @Override public Anchor getAnchor() { return Vision.Anchor.CENTER; } @Override public Area getArea(Zone zone) { Token token = getToken(); if (token == null) { return null; } if (lastFacing != null && !lastFacing.equals(token.getFacing())) { flush(); } return super.getArea(zone); } @Override protected Area createArea(Zone zone) { Token token = getToken(); if (token == null || token.getFacing() == null) { return null; } // Start round int size = getDistance() * getZonePointsPerCell(zone) * 2; int half = size/2; Area area = new Area(new Ellipse2D.Float(-half, -half, size, size)); // Cut off the part that isn't in the cone - area.subtract(new Area(new Rectangle(-1000, 1, 2000, 2000))); - area.subtract(new Area(new Rectangle(-1000, -1000, 999, 2000))); + area.subtract(new Area(new Rectangle(-100000, 1, 200000, 200000))); + area.subtract(new Area(new Rectangle(-100000, -100000, 99999, 200000))); // Rotate int angle = (-token.getFacing() + 45); area.transform(AffineTransform.getRotateInstance(Math.toRadians(angle))); lastFacing = token.getFacing(); return area; } private Token getToken() { return MapTool.getFrame().getCurrentZoneRenderer().getZone().getToken(tokenGUID); } @Override public String toString() { return "Conic Facing"; } }
true
true
protected Area createArea(Zone zone) { Token token = getToken(); if (token == null || token.getFacing() == null) { return null; } // Start round int size = getDistance() * getZonePointsPerCell(zone) * 2; int half = size/2; Area area = new Area(new Ellipse2D.Float(-half, -half, size, size)); // Cut off the part that isn't in the cone area.subtract(new Area(new Rectangle(-1000, 1, 2000, 2000))); area.subtract(new Area(new Rectangle(-1000, -1000, 999, 2000))); // Rotate int angle = (-token.getFacing() + 45); area.transform(AffineTransform.getRotateInstance(Math.toRadians(angle))); lastFacing = token.getFacing(); return area; }
protected Area createArea(Zone zone) { Token token = getToken(); if (token == null || token.getFacing() == null) { return null; } // Start round int size = getDistance() * getZonePointsPerCell(zone) * 2; int half = size/2; Area area = new Area(new Ellipse2D.Float(-half, -half, size, size)); // Cut off the part that isn't in the cone area.subtract(new Area(new Rectangle(-100000, 1, 200000, 200000))); area.subtract(new Area(new Rectangle(-100000, -100000, 99999, 200000))); // Rotate int angle = (-token.getFacing() + 45); area.transform(AffineTransform.getRotateInstance(Math.toRadians(angle))); lastFacing = token.getFacing(); return area; }
diff --git a/src/java/org/jdesktop/swingx/plaf/JXTaskPaneAddon.java b/src/java/org/jdesktop/swingx/plaf/JXTaskPaneAddon.java index 7a25a5f5..31230246 100644 --- a/src/java/org/jdesktop/swingx/plaf/JXTaskPaneAddon.java +++ b/src/java/org/jdesktop/swingx/plaf/JXTaskPaneAddon.java @@ -1,253 +1,252 @@ /* * $Id$ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package org.jdesktop.swingx.plaf; import java.awt.Color; import java.awt.Font; import java.awt.SystemColor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import javax.swing.plaf.metal.MetalLookAndFeel; import org.jdesktop.swingx.JXTaskPane; import org.jdesktop.swingx.plaf.ComponentAddon; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.aqua.AquaLookAndFeelAddons; import org.jdesktop.swingx.plaf.basic.BasicLookAndFeelAddons; import org.jdesktop.swingx.plaf.metal.MetalLookAndFeelAddons; import org.jdesktop.swingx.plaf.windows.WindowsClassicLookAndFeelAddons; import org.jdesktop.swingx.plaf.windows.WindowsLookAndFeelAddons; import org.jdesktop.swingx.util.JVM; import org.jdesktop.swingx.util.OS; /** * Addon for <code>JXTaskPane</code>.<br> * */ public class JXTaskPaneAddon implements ComponentAddon { public String getName() { return "JXTaskPane"; } public void initialize(LookAndFeelAddons addon) { addon.loadDefaults(getDefaults(addon)); } public void uninitialize(LookAndFeelAddons addon) { addon.unloadDefaults(getDefaults(addon)); } private Object[] getDefaults(LookAndFeelAddons addon) { List defaults = new ArrayList(); if (addon instanceof BasicLookAndFeelAddons) { Color menuBackground = new ColorUIResource(SystemColor.menu); defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.basic.BasicTaskPaneUI", "TaskPane.font", new FontUIResource( UIManager.getFont("Label.font").deriveFont(Font.BOLD)), "TaskPane.background", UIManager.getColor("List.background"), "TaskPane.specialTitleBackground", new ColorUIResource(menuBackground.darker()), "TaskPane.titleBackgroundGradientStart", menuBackground, "TaskPane.titleBackgroundGradientEnd", menuBackground, "TaskPane.titleForeground", new ColorUIResource(SystemColor.menuText), "TaskPane.specialTitleForeground", new ColorUIResource(SystemColor.menuText).brighter(), "TaskPane.animate", Boolean.TRUE, "TaskPane.focusInputMap", new UIDefaults.LazyInputMap( new Object[] { "ENTER", "toggleExpanded", "SPACE", "toggleExpanded" }), })); } if (addon instanceof MetalLookAndFeelAddons) { // if using Ocean, use the Glossy l&f String taskPaneGroupUI = "org.jdesktop.swingx.plaf.metal.MetalTaskPaneUI"; if (JVM.current().isOrLater(JVM.JDK1_5)) { try { - Method method = MetalLookAndFeel.class.getMethod("getCurrentTheme", - null); - Object currentTheme = method.invoke(null, null); + Method method = MetalLookAndFeel.class.getMethod("getCurrentTheme"); + Object currentTheme = method.invoke(null); if (Class.forName("javax.swing.plaf.metal.OceanTheme").isInstance( currentTheme)) { taskPaneGroupUI = "org.jdesktop.swingx.plaf.misc.GlossyTaskPaneUI"; } } catch (Exception e) { } } defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, taskPaneGroupUI, "TaskPane.foreground", UIManager.getColor("activeCaptionText"), "TaskPane.background", MetalLookAndFeel.getControl(), "TaskPane.specialTitleBackground", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleBackgroundGradientStart", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleBackgroundGradientEnd", MetalLookAndFeel.getPrimaryControlHighlight(), "TaskPane.titleForeground", MetalLookAndFeel.getControlTextColor(), "TaskPane.specialTitleForeground", MetalLookAndFeel.getControlTextColor(), "TaskPane.borderColor", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleOver", MetalLookAndFeel.getControl().darker(), "TaskPane.specialTitleOver", MetalLookAndFeel.getPrimaryControlHighlight() })); } if (addon instanceof WindowsLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.windows.WindowsTaskPaneUI"})); String xpStyle = OS.getWindowsVisualStyle(); if (WindowsLookAndFeelAddons.HOMESTEAD_VISUAL_STYLE .equalsIgnoreCase(xpStyle)) { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(86, 102, 45), "TaskPane.background", new ColorUIResource(246, 246, 236), "TaskPane.specialTitleBackground", new ColorUIResource(224, 231, 184), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(255, 255, 255), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(224, 231, 184), "TaskPane.titleForeground", new ColorUIResource(86, 102, 45), "TaskPane.titleOver", new ColorUIResource(114, 146, 29), "TaskPane.specialTitleForeground", new ColorUIResource(86, 102, 45), "TaskPane.specialTitleOver", new ColorUIResource(114, 146, 29), "TaskPane.borderColor", new ColorUIResource(255, 255, 255), })); } else if (WindowsLookAndFeelAddons.SILVER_VISUAL_STYLE .equalsIgnoreCase(xpStyle)) { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(Color.black), "TaskPane.background", new ColorUIResource(240, 241, 245), "TaskPane.specialTitleBackground", new ColorUIResource(222, 222, 222), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(Color.white), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(214, 215, 224), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.titleOver", new ColorUIResource(126, 124, 124), "TaskPane.specialTitleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleOver", new ColorUIResource(126, 124, 124), "TaskPane.borderColor", new ColorUIResource(Color.white), })); } else { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(Color.white), "TaskPane.background", new ColorUIResource(214, 223, 247), "TaskPane.specialTitleBackground", new ColorUIResource(33, 89, 201), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(Color.white), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(199, 212, 247), "TaskPane.titleForeground", new ColorUIResource(33, 89, 201), "TaskPane.specialTitleForeground", new ColorUIResource(Color.white), "TaskPane.borderColor", new ColorUIResource(Color.white), })); } } if (addon instanceof WindowsClassicLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.windows.WindowsClassicTaskPaneUI", "TaskPane.foreground", new ColorUIResource(Color.black), "TaskPane.background", new ColorUIResource(Color.white), "TaskPane.specialTitleBackground", new ColorUIResource(10, 36, 106), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(212, 208, 200), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(212, 208, 200), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleForeground", new ColorUIResource(Color.white), "TaskPane.borderColor", new ColorUIResource(212, 208, 200), })); } if (addon instanceof AquaLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.misc.GlossyTaskPaneUI", "TaskPane.background", new ColorUIResource(245, 245, 245), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleBackground", new ColorUIResource(188,188,188), "TaskPane.specialTitleForeground", new ColorUIResource(Color.black), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(250,250,250), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(188,188,188), "TaskPane.borderColor", new ColorUIResource(97, 97, 97), "TaskPane.titleOver", new ColorUIResource(125, 125, 97), "TaskPane.specialTitleOver", new ColorUIResource(125, 125, 97), })); } return defaults.toArray(); } }
true
true
private Object[] getDefaults(LookAndFeelAddons addon) { List defaults = new ArrayList(); if (addon instanceof BasicLookAndFeelAddons) { Color menuBackground = new ColorUIResource(SystemColor.menu); defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.basic.BasicTaskPaneUI", "TaskPane.font", new FontUIResource( UIManager.getFont("Label.font").deriveFont(Font.BOLD)), "TaskPane.background", UIManager.getColor("List.background"), "TaskPane.specialTitleBackground", new ColorUIResource(menuBackground.darker()), "TaskPane.titleBackgroundGradientStart", menuBackground, "TaskPane.titleBackgroundGradientEnd", menuBackground, "TaskPane.titleForeground", new ColorUIResource(SystemColor.menuText), "TaskPane.specialTitleForeground", new ColorUIResource(SystemColor.menuText).brighter(), "TaskPane.animate", Boolean.TRUE, "TaskPane.focusInputMap", new UIDefaults.LazyInputMap( new Object[] { "ENTER", "toggleExpanded", "SPACE", "toggleExpanded" }), })); } if (addon instanceof MetalLookAndFeelAddons) { // if using Ocean, use the Glossy l&f String taskPaneGroupUI = "org.jdesktop.swingx.plaf.metal.MetalTaskPaneUI"; if (JVM.current().isOrLater(JVM.JDK1_5)) { try { Method method = MetalLookAndFeel.class.getMethod("getCurrentTheme", null); Object currentTheme = method.invoke(null, null); if (Class.forName("javax.swing.plaf.metal.OceanTheme").isInstance( currentTheme)) { taskPaneGroupUI = "org.jdesktop.swingx.plaf.misc.GlossyTaskPaneUI"; } } catch (Exception e) { } } defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, taskPaneGroupUI, "TaskPane.foreground", UIManager.getColor("activeCaptionText"), "TaskPane.background", MetalLookAndFeel.getControl(), "TaskPane.specialTitleBackground", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleBackgroundGradientStart", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleBackgroundGradientEnd", MetalLookAndFeel.getPrimaryControlHighlight(), "TaskPane.titleForeground", MetalLookAndFeel.getControlTextColor(), "TaskPane.specialTitleForeground", MetalLookAndFeel.getControlTextColor(), "TaskPane.borderColor", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleOver", MetalLookAndFeel.getControl().darker(), "TaskPane.specialTitleOver", MetalLookAndFeel.getPrimaryControlHighlight() })); } if (addon instanceof WindowsLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.windows.WindowsTaskPaneUI"})); String xpStyle = OS.getWindowsVisualStyle(); if (WindowsLookAndFeelAddons.HOMESTEAD_VISUAL_STYLE .equalsIgnoreCase(xpStyle)) { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(86, 102, 45), "TaskPane.background", new ColorUIResource(246, 246, 236), "TaskPane.specialTitleBackground", new ColorUIResource(224, 231, 184), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(255, 255, 255), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(224, 231, 184), "TaskPane.titleForeground", new ColorUIResource(86, 102, 45), "TaskPane.titleOver", new ColorUIResource(114, 146, 29), "TaskPane.specialTitleForeground", new ColorUIResource(86, 102, 45), "TaskPane.specialTitleOver", new ColorUIResource(114, 146, 29), "TaskPane.borderColor", new ColorUIResource(255, 255, 255), })); } else if (WindowsLookAndFeelAddons.SILVER_VISUAL_STYLE .equalsIgnoreCase(xpStyle)) { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(Color.black), "TaskPane.background", new ColorUIResource(240, 241, 245), "TaskPane.specialTitleBackground", new ColorUIResource(222, 222, 222), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(Color.white), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(214, 215, 224), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.titleOver", new ColorUIResource(126, 124, 124), "TaskPane.specialTitleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleOver", new ColorUIResource(126, 124, 124), "TaskPane.borderColor", new ColorUIResource(Color.white), })); } else { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(Color.white), "TaskPane.background", new ColorUIResource(214, 223, 247), "TaskPane.specialTitleBackground", new ColorUIResource(33, 89, 201), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(Color.white), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(199, 212, 247), "TaskPane.titleForeground", new ColorUIResource(33, 89, 201), "TaskPane.specialTitleForeground", new ColorUIResource(Color.white), "TaskPane.borderColor", new ColorUIResource(Color.white), })); } } if (addon instanceof WindowsClassicLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.windows.WindowsClassicTaskPaneUI", "TaskPane.foreground", new ColorUIResource(Color.black), "TaskPane.background", new ColorUIResource(Color.white), "TaskPane.specialTitleBackground", new ColorUIResource(10, 36, 106), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(212, 208, 200), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(212, 208, 200), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleForeground", new ColorUIResource(Color.white), "TaskPane.borderColor", new ColorUIResource(212, 208, 200), })); } if (addon instanceof AquaLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.misc.GlossyTaskPaneUI", "TaskPane.background", new ColorUIResource(245, 245, 245), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleBackground", new ColorUIResource(188,188,188), "TaskPane.specialTitleForeground", new ColorUIResource(Color.black), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(250,250,250), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(188,188,188), "TaskPane.borderColor", new ColorUIResource(97, 97, 97), "TaskPane.titleOver", new ColorUIResource(125, 125, 97), "TaskPane.specialTitleOver", new ColorUIResource(125, 125, 97), })); } return defaults.toArray(); }
private Object[] getDefaults(LookAndFeelAddons addon) { List defaults = new ArrayList(); if (addon instanceof BasicLookAndFeelAddons) { Color menuBackground = new ColorUIResource(SystemColor.menu); defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.basic.BasicTaskPaneUI", "TaskPane.font", new FontUIResource( UIManager.getFont("Label.font").deriveFont(Font.BOLD)), "TaskPane.background", UIManager.getColor("List.background"), "TaskPane.specialTitleBackground", new ColorUIResource(menuBackground.darker()), "TaskPane.titleBackgroundGradientStart", menuBackground, "TaskPane.titleBackgroundGradientEnd", menuBackground, "TaskPane.titleForeground", new ColorUIResource(SystemColor.menuText), "TaskPane.specialTitleForeground", new ColorUIResource(SystemColor.menuText).brighter(), "TaskPane.animate", Boolean.TRUE, "TaskPane.focusInputMap", new UIDefaults.LazyInputMap( new Object[] { "ENTER", "toggleExpanded", "SPACE", "toggleExpanded" }), })); } if (addon instanceof MetalLookAndFeelAddons) { // if using Ocean, use the Glossy l&f String taskPaneGroupUI = "org.jdesktop.swingx.plaf.metal.MetalTaskPaneUI"; if (JVM.current().isOrLater(JVM.JDK1_5)) { try { Method method = MetalLookAndFeel.class.getMethod("getCurrentTheme"); Object currentTheme = method.invoke(null); if (Class.forName("javax.swing.plaf.metal.OceanTheme").isInstance( currentTheme)) { taskPaneGroupUI = "org.jdesktop.swingx.plaf.misc.GlossyTaskPaneUI"; } } catch (Exception e) { } } defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, taskPaneGroupUI, "TaskPane.foreground", UIManager.getColor("activeCaptionText"), "TaskPane.background", MetalLookAndFeel.getControl(), "TaskPane.specialTitleBackground", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleBackgroundGradientStart", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleBackgroundGradientEnd", MetalLookAndFeel.getPrimaryControlHighlight(), "TaskPane.titleForeground", MetalLookAndFeel.getControlTextColor(), "TaskPane.specialTitleForeground", MetalLookAndFeel.getControlTextColor(), "TaskPane.borderColor", MetalLookAndFeel.getPrimaryControl(), "TaskPane.titleOver", MetalLookAndFeel.getControl().darker(), "TaskPane.specialTitleOver", MetalLookAndFeel.getPrimaryControlHighlight() })); } if (addon instanceof WindowsLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.windows.WindowsTaskPaneUI"})); String xpStyle = OS.getWindowsVisualStyle(); if (WindowsLookAndFeelAddons.HOMESTEAD_VISUAL_STYLE .equalsIgnoreCase(xpStyle)) { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(86, 102, 45), "TaskPane.background", new ColorUIResource(246, 246, 236), "TaskPane.specialTitleBackground", new ColorUIResource(224, 231, 184), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(255, 255, 255), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(224, 231, 184), "TaskPane.titleForeground", new ColorUIResource(86, 102, 45), "TaskPane.titleOver", new ColorUIResource(114, 146, 29), "TaskPane.specialTitleForeground", new ColorUIResource(86, 102, 45), "TaskPane.specialTitleOver", new ColorUIResource(114, 146, 29), "TaskPane.borderColor", new ColorUIResource(255, 255, 255), })); } else if (WindowsLookAndFeelAddons.SILVER_VISUAL_STYLE .equalsIgnoreCase(xpStyle)) { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(Color.black), "TaskPane.background", new ColorUIResource(240, 241, 245), "TaskPane.specialTitleBackground", new ColorUIResource(222, 222, 222), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(Color.white), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(214, 215, 224), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.titleOver", new ColorUIResource(126, 124, 124), "TaskPane.specialTitleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleOver", new ColorUIResource(126, 124, 124), "TaskPane.borderColor", new ColorUIResource(Color.white), })); } else { defaults.addAll(Arrays.asList(new Object[]{ "TaskPane.foreground", new ColorUIResource(Color.white), "TaskPane.background", new ColorUIResource(214, 223, 247), "TaskPane.specialTitleBackground", new ColorUIResource(33, 89, 201), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(Color.white), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(199, 212, 247), "TaskPane.titleForeground", new ColorUIResource(33, 89, 201), "TaskPane.specialTitleForeground", new ColorUIResource(Color.white), "TaskPane.borderColor", new ColorUIResource(Color.white), })); } } if (addon instanceof WindowsClassicLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.windows.WindowsClassicTaskPaneUI", "TaskPane.foreground", new ColorUIResource(Color.black), "TaskPane.background", new ColorUIResource(Color.white), "TaskPane.specialTitleBackground", new ColorUIResource(10, 36, 106), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(212, 208, 200), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(212, 208, 200), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleForeground", new ColorUIResource(Color.white), "TaskPane.borderColor", new ColorUIResource(212, 208, 200), })); } if (addon instanceof AquaLookAndFeelAddons) { defaults.addAll(Arrays.asList(new Object[]{ JXTaskPane.uiClassID, "org.jdesktop.swingx.plaf.misc.GlossyTaskPaneUI", "TaskPane.background", new ColorUIResource(245, 245, 245), "TaskPane.titleForeground", new ColorUIResource(Color.black), "TaskPane.specialTitleBackground", new ColorUIResource(188,188,188), "TaskPane.specialTitleForeground", new ColorUIResource(Color.black), "TaskPane.titleBackgroundGradientStart", new ColorUIResource(250,250,250), "TaskPane.titleBackgroundGradientEnd", new ColorUIResource(188,188,188), "TaskPane.borderColor", new ColorUIResource(97, 97, 97), "TaskPane.titleOver", new ColorUIResource(125, 125, 97), "TaskPane.specialTitleOver", new ColorUIResource(125, 125, 97), })); } return defaults.toArray(); }
diff --git a/javagit/src/test/java/edu/nyu/cs/javagit/api/TestGitFileSystem.java b/javagit/src/test/java/edu/nyu/cs/javagit/api/TestGitFileSystem.java index 359c232..32290aa 100644 --- a/javagit/src/test/java/edu/nyu/cs/javagit/api/TestGitFileSystem.java +++ b/javagit/src/test/java/edu/nyu/cs/javagit/api/TestGitFileSystem.java @@ -1,182 +1,184 @@ /* * ==================================================================== * Copyright (c) 2008 JavaGit Project. All rights reserved. * * This software is licensed using the GNU LGPL v2.1 license. A copy * of the license is included with the distribution of this source * code in the LICENSE.txt file. The text of the license can also * be obtained at: * * http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * * For more information on the JavaGit project, see: * * http://www.javagit.com * ==================================================================== */ package edu.nyu.cs.javagit.api; import java.io.File; import java.io.IOException; import java.util.List; import junit.framework.TestCase; import org.junit.After; import org.junit.Before; import org.junit.Test; import edu.nyu.cs.javagit.api.JavaGitException; import edu.nyu.cs.javagit.api.DotGit; import edu.nyu.cs.javagit.api.WorkingTree; import edu.nyu.cs.javagit.api.GitFileSystemObject; import edu.nyu.cs.javagit.api.GitFileSystemObject.Status; import edu.nyu.cs.javagit.api.commands.GitInit; import edu.nyu.cs.javagit.api.commands.GitStatusResponse; import edu.nyu.cs.javagit.api.GitFile; //import edu.nyu.cs.javagit.api.GitDirectory; import edu.nyu.cs.javagit.test.utilities.FileUtilities; import edu.nyu.cs.javagit.test.utilities.HelperGitCommands; public class TestGitFileSystem extends TestCase { private File repositoryDirectory; private DotGit dotGit; private WorkingTree workingTree; @Before public void setUp() throws JavaGitException, IOException { repositoryDirectory = FileUtilities.createTempDirectory("GitFileSystemTest_dir"); GitInit gitInit = new GitInit(); gitInit.init(repositoryDirectory); dotGit = DotGit.getInstance(repositoryDirectory); workingTree = WorkingTree.getInstance(repositoryDirectory); } /** * creates a single file and runs a series of tests on it */ @Test public void testSingleGitFile() throws IOException, JavaGitException { //Create a file FileUtilities.createFile(repositoryDirectory, "abc.txt", "Some data"); //check contents List<GitFileSystemObject> children = workingTree.getTree(); assertEquals("Error. Expecting only one file.", 1, children.size()); GitFileSystemObject currentFile = children.get(0); assertEquals("Error. Expecting instance of GitFile.", GitFile.class, currentFile.getClass()); GitFile gitFile = (GitFile)currentFile; assertEquals("Error. Expecting UNTRACKED status for the single file.", Status.UNTRACKED, gitFile.getStatus()); gitFile.add(); assertEquals("Error. Expecting NEW_TO_COMMIT status for the single file.", Status.NEW_TO_COMMIT, gitFile.getStatus()); workingTree.getFile(new File("x")); gitFile.commit("commit message"); assertEquals("Error. Expecting IN_REPOSITORY status for the single file.", Status.IN_REPOSITORY, gitFile.getStatus()); FileUtilities.modifyFileContents(gitFile.getFile(), "more data"); assertEquals("Error. Expecting MODIFIED status for the single file.", Status.MODIFIED, gitFile.getStatus()); gitFile.add(); assertEquals("Error. Expecting MODIFIED_TO_COMMIT status for the single file.", Status.MODIFIED_TO_COMMIT, gitFile.getStatus()); gitFile.commit("commit message"); assertEquals("Error. Expecting IN_REPOSITORY status for the single file.", Status.IN_REPOSITORY, gitFile.getStatus()); } @Test /** * Adds more file system objects */ public void testGitFileSystem() throws IOException, JavaGitException { //Add another file FileUtilities.createFile(repositoryDirectory, "file1", "Some data"); FileUtilities.createFile(repositoryDirectory, "file2", "Some data"); //check contents List<GitFileSystemObject> children = workingTree.getTree(); assertEquals("Error. Expecting 2 files.", 2, children.size()); //attempt to commit (but without anything on the index) try { workingTree.commit("commit comment"); fail("JavaGitException not thrown"); } catch(JavaGitException e) { } //get children GitFile gitFile1 = (GitFile)children.get(0); GitFile gitFile2 = (GitFile)children.get(1); //both should be untracked assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //another way to see the same thing File file1 = new File("file1"); File file2 = new File("file2"); GitStatusResponse statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //stage one file gitFile1.add(); //check status - assertEquals("Error. Expecting .NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, gitFile1.getStatus()); + /* + assertEquals("Error. Expecting NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); + */ //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //commit everything added to the index workingTree.commitAll("commit comment"); //check status assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //commit everything workingTree.addAndCommitAll("commit comment"); //check status assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile1.getStatus()); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file2)); } @After public void tearDown() throws Exception { if ( repositoryDirectory.exists() ) { FileUtilities.removeDirectoryRecursivelyAndForcefully(repositoryDirectory); } } }
false
true
public void testGitFileSystem() throws IOException, JavaGitException { //Add another file FileUtilities.createFile(repositoryDirectory, "file1", "Some data"); FileUtilities.createFile(repositoryDirectory, "file2", "Some data"); //check contents List<GitFileSystemObject> children = workingTree.getTree(); assertEquals("Error. Expecting 2 files.", 2, children.size()); //attempt to commit (but without anything on the index) try { workingTree.commit("commit comment"); fail("JavaGitException not thrown"); } catch(JavaGitException e) { } //get children GitFile gitFile1 = (GitFile)children.get(0); GitFile gitFile2 = (GitFile)children.get(1); //both should be untracked assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //another way to see the same thing File file1 = new File("file1"); File file2 = new File("file2"); GitStatusResponse statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //stage one file gitFile1.add(); //check status assertEquals("Error. Expecting .NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //commit everything added to the index workingTree.commitAll("commit comment"); //check status assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //commit everything workingTree.addAndCommitAll("commit comment"); //check status assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile1.getStatus()); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file2)); }
public void testGitFileSystem() throws IOException, JavaGitException { //Add another file FileUtilities.createFile(repositoryDirectory, "file1", "Some data"); FileUtilities.createFile(repositoryDirectory, "file2", "Some data"); //check contents List<GitFileSystemObject> children = workingTree.getTree(); assertEquals("Error. Expecting 2 files.", 2, children.size()); //attempt to commit (but without anything on the index) try { workingTree.commit("commit comment"); fail("JavaGitException not thrown"); } catch(JavaGitException e) { } //get children GitFile gitFile1 = (GitFile)children.get(0); GitFile gitFile2 = (GitFile)children.get(1); //both should be untracked assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //another way to see the same thing File file1 = new File("file1"); File file2 = new File("file2"); GitStatusResponse statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //stage one file gitFile1.add(); //check status /* assertEquals("Error. Expecting NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); */ //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting NEW_TO_COMMIT.", Status.NEW_TO_COMMIT, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //commit everything added to the index workingTree.commitAll("commit comment"); //check status assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile1.getStatus()); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting UNTRACKED.", Status.UNTRACKED, statusResponse.getFileStatus(file2)); //commit everything workingTree.addAndCommitAll("commit comment"); //check status assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile1.getStatus()); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, gitFile2.getStatus()); //alternative way statusResponse = workingTree.getStatus(); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file1)); assertEquals("Error. Expecting IN_REPOSITORY.", Status.IN_REPOSITORY, statusResponse.getFileStatus(file2)); }
diff --git a/kohola/src/edu/hawaii/ihale/frontend/page/lighting/Lighting.java b/kohola/src/edu/hawaii/ihale/frontend/page/lighting/Lighting.java index 1dda725..65f8024 100644 --- a/kohola/src/edu/hawaii/ihale/frontend/page/lighting/Lighting.java +++ b/kohola/src/edu/hawaii/ihale/frontend/page/lighting/Lighting.java @@ -1,628 +1,628 @@ package edu.hawaii.ihale.frontend.page.lighting; import java.util.Arrays; import java.util.Date; import java.util.List; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.ajax.markup.html.form.AjaxButton; import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator; import org.apache.wicket.behavior.AbstractBehavior; import org.apache.wicket.markup.ComponentTag; //import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.TextField; //import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.HiddenField; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.PageableListView; import org.apache.wicket.model.Model; import org.apache.wicket.model.PropertyModel; import org.apache.wicket.util.time.Duration; import edu.hawaii.ihale.api.ApiDictionary.IHaleCommandType; import edu.hawaii.ihale.api.ApiDictionary.IHaleRoom; import edu.hawaii.ihale.api.ApiDictionary.IHaleSystem; import edu.hawaii.ihale.api.repository.SystemStatusMessage; import edu.hawaii.ihale.api.repository.impl.Repository; import edu.hawaii.ihale.backend.IHaleBackend; import edu.hawaii.ihale.frontend.SolarDecathlonApplication; import edu.hawaii.ihale.frontend.SolarDecathlonSession; import edu.hawaii.ihale.frontend.page.Header; /** * The lighting page. * * @author Noah Woodden * @author Kevin Leong * @author Anthony Kinsey * @author Kylan Hughes * @author Chuan Lun Hung */ public class Lighting extends Header { /** Support serialization. */ private static final long serialVersionUID = 1L; private boolean DEBUG = true; // String literals for pmd private static final String brightID = "amountBright"; private static final String white = "#FFFFFF"; private static final String yellowTag = "<font color=\"#FF9900\">("; private static final String yellowTagEnd = "%)</font>"; private static final String greenTagEnd = "%)</font>"; private static final String greenTag = "<font color=\"green\">("; private static final String CLASS = "class"; private static final String LIVING_ROOM = "Living Room"; private static final String DINING_ROOM = "Dining Room"; private static final String KITCHEN = "Kitchen"; private static final String BATHROOM = "Bathroom"; private boolean livingState; private boolean diningState; private boolean kitchenState; private boolean bathroomState; private String buttonOn = "green-button"; private String buttonOff = "gray-button"; private HiddenField<String> colorChange; private TextField<String> intensity; private int setLivingIntensity; private int setDiningIntensity; private int setKitchenIntensity; private int setBathroomIntensity; private int desiredLivingIntensity = 0; private int desiredDiningIntensity = 0; private int desiredKitchenIntensity = 0; private int desiredBathroomIntensity = 0; // private Label colorFeedback; private Label intensityFeedback; private String setColor = white; private String desiredLivingColor = white; private String desiredDiningColor = white; private String desiredKitchenColor = white; private String desiredBathroomColor = white; private DropDownChoice<String> roomChoices; private static final List<String> rooms = Arrays.asList(new String[] { LIVING_ROOM, DINING_ROOM, KITCHEN, BATHROOM }); private String currentRoom = ((SolarDecathlonSession) getSession()).getLightingSession() .getRoom(); private Link<String> onButton; private Link<String> offButton; /** * Layout of page. */ public Lighting() { ((SolarDecathlonSession) getSession()).getHeaderSession().setActiveTab(3); Repository repository = new Repository(); livingState = repository.getLightingEnabled(IHaleRoom.LIVING).getValue(); diningState = repository.getLightingEnabled(IHaleRoom.DINING).getValue(); kitchenState = repository.getLightingEnabled(IHaleRoom.KITCHEN).getValue(); bathroomState = repository.getLightingEnabled(IHaleRoom.BATHROOM).getValue(); Form<String> form = new Form<String>("form"); // Add the control for the intensity slider setLivingIntensity = repository.getLightingLevel(IHaleRoom.LIVING).getValue(); setDiningIntensity = repository.getLightingLevel(IHaleRoom.DINING).getValue(); setKitchenIntensity = repository.getLightingLevel(IHaleRoom.KITCHEN).getValue(); setBathroomIntensity = repository.getLightingLevel(IHaleRoom.BATHROOM).getValue(); desiredLivingColor = repository.getLightingColor(IHaleRoom.LIVING).getValue(); desiredDiningColor = repository.getLightingColor(IHaleRoom.DINING).getValue(); desiredKitchenColor = repository.getLightingColor(IHaleRoom.KITCHEN).getValue(); desiredBathroomColor = repository.getLightingColor(IHaleRoom.BATHROOM).getValue(); // Messages // Add messages as a list view to each page // Get all messages applicable to this page List<SystemStatusMessage> msgs = SolarDecathlonApplication.getMessages().getMessages(IHaleSystem.LIGHTING); // Create wrapper container for pageable list view WebMarkupContainer systemLog = new WebMarkupContainer("LightingSystemLogContainer"); systemLog.setOutputMarkupId(true); // Create Listview PageableListView<SystemStatusMessage> listView = new PageableListView<SystemStatusMessage>("LightingStatusMessages", msgs, 10) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<SystemStatusMessage> item) { SystemStatusMessage msg = item.getModelObject(); // If only the empty message is in the list, then // display "No Messages" if (msg.getType() == null) { item.add(new Label("LightingMessageType", "-")); item.add(new Label("LightingTimestamp", "-")); item.add(new Label("LightingMessageContent", "No Messages")); } // Populate data else { item.add(new Label("LightingTimestamp", new Date(msg.getTimestamp()).toString())); item.add(new Label("LightingMessageType", msg.getType().toString())); item.add(new Label("LightingMessageContent", msg.getMessage())); } } }; systemLog.add(listView); systemLog.add(new AjaxPagingNavigator("paginatorLighting", listView)); // Update log every 5 seconds. systemLog.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)) { private static final long serialVersionUID = 1L; }); systemLog.setVersioned(false); add(systemLog); // End messages section if (LIVING_ROOM.equals(currentRoom)) { setColor = desiredLivingColor; intensity = new TextField<String>(brightID, new Model<String>(setLivingIntensity + "%")); } else if (DINING_ROOM.equals(currentRoom)) { setColor = desiredDiningColor; intensity = new TextField<String>(brightID, new Model<String>(setDiningIntensity + "%")); } else if (KITCHEN.equals(currentRoom)) { setColor = desiredKitchenColor; intensity = new TextField<String>(brightID, new Model<String>(setKitchenIntensity + "%")); } else { setColor = desiredBathroomColor; intensity = new TextField<String>(brightID, new Model<String>(setBathroomIntensity + "%")); } // Added for jquery control. intensity.setMarkupId(intensity.getId()); intensity.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * Updates the model when the value is changed on screen. */ @Override protected void onUpdate(AjaxRequestTarget target) { if (LIVING_ROOM.equals(currentRoom)) { setLivingIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setLivingIntensity: " + setLivingIntensity); } } else if (DINING_ROOM.equals(currentRoom)) { setDiningIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setDiningIntensity: " + setDiningIntensity); } } else if (KITCHEN.equals(currentRoom)) { setKitchenIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setKitchenIntensity: " + setKitchenIntensity); } } else if (BATHROOM.equals(currentRoom)) { setBathroomIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setBathroomIntensity: " + setBathroomIntensity); } } } }); // airTemp.setOutputMarkupId(true); form.add(intensity); form.add(new AjaxButton("SubmitIntensity") { // support serializable private static final long serialVersionUID = 1L; /** Provide user feeback after they set a new desired temperature */ @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { IHaleSystem system = IHaleSystem.HVAC; IHaleCommandType command = IHaleCommandType.SET_LIGHTING_LEVEL; IHaleRoom room; if (LIVING_ROOM.equals(currentRoom)) { if (setLivingIntensity == desiredLivingIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredLivingIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredLivingIntensity = setLivingIntensity; room = IHaleRoom.LIVING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredLivingIntensity); if (DEBUG) { System.out.println("do command sent for living " + "room lights intensity with level: " + desiredLivingIntensity + "%"); } intensityFeedback .setDefaultModelObject(greenTag + desiredLivingIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (DINING_ROOM.equals(currentRoom)) { if (setDiningIntensity == desiredDiningIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredDiningIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredDiningIntensity = setDiningIntensity; room = IHaleRoom.DINING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredDiningIntensity); if (DEBUG) { System.out.println("do command sent for dining " + "room lights intensity with level: " + desiredDiningIntensity + "%"); } intensityFeedback .setDefaultModelObject(greenTag + desiredDiningIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (KITCHEN.equals(currentRoom)) { if (setKitchenIntensity == desiredKitchenIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredKitchenIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredKitchenIntensity = setKitchenIntensity; room = IHaleRoom.KITCHEN; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredKitchenIntensity); if (DEBUG) { System.out.println("do command sent for kitchen room lights intensity with level: " + desiredKitchenIntensity + "%"); } intensityFeedback.setDefaultModelObject(greenTag + desiredKitchenIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (BATHROOM.equals(currentRoom)) { if (setBathroomIntensity == desiredBathroomIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredBathroomIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredBathroomIntensity = setBathroomIntensity; room = IHaleRoom.BATHROOM; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredBathroomIntensity); if (DEBUG) { System.out.println("do command sent for bathroom " + "room lights intensity with level: " + desiredBathroomIntensity + "%"); } intensityFeedback.setDefaultModelObject(greenTag + desiredBathroomIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } } }); form.setOutputMarkupId(true); // the on button onButton = new Link<String>("OnButton") { private static final long serialVersionUID = 1L; @Override /** * Turn on the light in this room. */ public void onClick() { handleRoomState(currentRoom, true); } }; // set markup id to true for ajax update onButton.setOutputMarkupId(true); // the off button offButton = new Link<String>("OffButton") { private static final long serialVersionUID = 1L; @Override /** * Turn off the light in this room. */ public void onClick() { handleRoomState(currentRoom, false); } }; // set markup id to true for ajax update offButton.setOutputMarkupId(true); // set the buttons according to user's current dropdownchoice if (LIVING_ROOM.equals(currentRoom)) { setButtons(livingState); } if (DINING_ROOM.equals(currentRoom)) { setButtons(diningState); } if (KITCHEN.equals(currentRoom)) { setButtons(kitchenState); } if (BATHROOM.equals(currentRoom)) { setButtons(bathroomState); } // create feedback for intensity - intensityFeedback = new Label("intensityfeedback", "<font color=\"white\">(xxx%)</font>"); + intensityFeedback = new Label("intensityfeedback", "<font color=\"white\">&nbsp;</font>"); intensityFeedback.setEscapeModelStrings(false); intensityFeedback.setOutputMarkupId(true); colorChange = new HiddenField<String>("colorchange", new Model<String>(setColor)); // Added for jquery control. colorChange.setMarkupId(colorChange.getId()); colorChange.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * Updates the model when the value is changed on screen. */ @Override protected void onUpdate(AjaxRequestTarget target) { setColor = colorChange.getValue(); IHaleSystem system = IHaleSystem.LIGHTING; IHaleCommandType command = IHaleCommandType.SET_LIGHTING_COLOR; IHaleRoom room; if (LIVING_ROOM.equals(currentRoom)) { if (desiredLivingColor.equals(setColor)) { return; } else { desiredLivingColor = setColor; room = IHaleRoom.LIVING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredLivingColor); if (DEBUG) { System.out.println("do command sent for living room lights color with color: " + desiredLivingColor); } return; } } else if (DINING_ROOM.equals(currentRoom)) { if (desiredDiningColor.equals(setColor)) { return; } else { desiredDiningColor = setColor; room = IHaleRoom.DINING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredDiningColor); if (DEBUG) { System.out.println("do command sent for dining room lights color with color: " + desiredDiningColor); } return; } } else if (KITCHEN.equals(currentRoom)) { if (desiredKitchenColor.equals(setColor)) { return; } else { desiredKitchenColor = setColor; room = IHaleRoom.KITCHEN; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredKitchenColor); if (DEBUG) { System.out.println("do command sent for kitchen room lights color with color: " + desiredKitchenColor); } return; } } else if (BATHROOM.equals(currentRoom)) { if (desiredBathroomColor.equals(setColor)) { return; } else { desiredBathroomColor = setColor; room = IHaleRoom.BATHROOM; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredBathroomColor); if (DEBUG) { System.out.println("do command sent for bathroom room lights color with color: " + desiredBathroomColor); } return; } } } }); add(colorChange); form.add(intensityFeedback); add(form); roomChoices = new DropDownChoice<String>("room", new PropertyModel<String>(this, "currentRoom"), rooms); roomChoices.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 1L; /** * For when user chooses new room. */ @Override protected void onUpdate(AjaxRequestTarget target) { Repository repository = new Repository(); String newSelection = roomChoices.getDefaultModelObjectAsString(); currentRoom = newSelection; System.out.println("new room selection: " + newSelection); if (LIVING_ROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(LIVING_ROOM); // set button to living state livingState = repository.getLightingEnabled(IHaleRoom.LIVING).getValue(); setButtons(livingState); // set intensity to living state } else if (DINING_ROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(DINING_ROOM); // set button to dining state diningState = repository.getLightingEnabled(IHaleRoom.DINING).getValue(); setButtons(diningState); // set intensity to dining state } else if (KITCHEN.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(KITCHEN); // set button to kitchen state kitchenState = repository.getLightingEnabled(IHaleRoom.KITCHEN).getValue(); setButtons(kitchenState); // set intensity to kitchen state } else if (BATHROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(BATHROOM); // set button to bathroom state bathroomState = repository.getLightingEnabled(IHaleRoom.BATHROOM).getValue(); setButtons(bathroomState); // set intensity to bathroom state } // reset feedback intensityFeedback.setDefaultModelObject(""); // add components in the page we want to update to the target. target.addComponent(intensityFeedback); target.addComponent(onButton); target.addComponent(offButton); setResponsePage(Lighting.class); } }); add(roomChoices.setRequired(true)); add(onButton); add(offButton); // add(form); } /** * Set the light switch according to the state of the selected room. * * @param enabled Whether the lights are on. */ private void setButtons(final boolean enabled) { onButton.add(new AbstractBehavior() { // support serialization private static final long serialVersionUID = 1L; public void onComponentTag(Component component, ComponentTag tag) { if (enabled) { tag.put(CLASS, buttonOn); } else { tag.put(CLASS, buttonOff); } } }); offButton.add(new AbstractBehavior() { // support serialization private static final long serialVersionUID = 1L; public void onComponentTag(Component component, ComponentTag tag) { if (enabled) { tag.put(CLASS, buttonOff); } else { tag.put(CLASS, buttonOn); } } }); } /** * Set the light switch and send a command to the house system. * * @param roomName The room name. * @param enabled Whether the light is enabled. */ private void handleRoomState(String roomName, boolean enabled) { IHaleBackend backend = new IHaleBackend(); if (LIVING_ROOM.equals(roomName)) { livingState = enabled; backend.doCommand(IHaleSystem.LIGHTING, IHaleRoom.LIVING, IHaleCommandType.SET_LIGHTING_ENABLED, enabled); } if (DINING_ROOM.equals(roomName)) { diningState = enabled; backend.doCommand(IHaleSystem.LIGHTING, IHaleRoom.DINING, IHaleCommandType.SET_LIGHTING_ENABLED, enabled); } if (KITCHEN.equals(roomName)) { kitchenState = enabled; backend.doCommand(IHaleSystem.LIGHTING, IHaleRoom.KITCHEN, IHaleCommandType.SET_LIGHTING_ENABLED, enabled); } if (BATHROOM.equals(roomName)) { bathroomState = enabled; backend.doCommand(IHaleSystem.LIGHTING, IHaleRoom.BATHROOM, IHaleCommandType.SET_LIGHTING_ENABLED, true); } if (enabled) { System.out.println("Command { ON } sent to " + roomName); } else { System.out.println("Command {OFF} sent to " + roomName); } intensityFeedback.setDefaultModelObject(""); setButtons(enabled); } }
true
true
public Lighting() { ((SolarDecathlonSession) getSession()).getHeaderSession().setActiveTab(3); Repository repository = new Repository(); livingState = repository.getLightingEnabled(IHaleRoom.LIVING).getValue(); diningState = repository.getLightingEnabled(IHaleRoom.DINING).getValue(); kitchenState = repository.getLightingEnabled(IHaleRoom.KITCHEN).getValue(); bathroomState = repository.getLightingEnabled(IHaleRoom.BATHROOM).getValue(); Form<String> form = new Form<String>("form"); // Add the control for the intensity slider setLivingIntensity = repository.getLightingLevel(IHaleRoom.LIVING).getValue(); setDiningIntensity = repository.getLightingLevel(IHaleRoom.DINING).getValue(); setKitchenIntensity = repository.getLightingLevel(IHaleRoom.KITCHEN).getValue(); setBathroomIntensity = repository.getLightingLevel(IHaleRoom.BATHROOM).getValue(); desiredLivingColor = repository.getLightingColor(IHaleRoom.LIVING).getValue(); desiredDiningColor = repository.getLightingColor(IHaleRoom.DINING).getValue(); desiredKitchenColor = repository.getLightingColor(IHaleRoom.KITCHEN).getValue(); desiredBathroomColor = repository.getLightingColor(IHaleRoom.BATHROOM).getValue(); // Messages // Add messages as a list view to each page // Get all messages applicable to this page List<SystemStatusMessage> msgs = SolarDecathlonApplication.getMessages().getMessages(IHaleSystem.LIGHTING); // Create wrapper container for pageable list view WebMarkupContainer systemLog = new WebMarkupContainer("LightingSystemLogContainer"); systemLog.setOutputMarkupId(true); // Create Listview PageableListView<SystemStatusMessage> listView = new PageableListView<SystemStatusMessage>("LightingStatusMessages", msgs, 10) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<SystemStatusMessage> item) { SystemStatusMessage msg = item.getModelObject(); // If only the empty message is in the list, then // display "No Messages" if (msg.getType() == null) { item.add(new Label("LightingMessageType", "-")); item.add(new Label("LightingTimestamp", "-")); item.add(new Label("LightingMessageContent", "No Messages")); } // Populate data else { item.add(new Label("LightingTimestamp", new Date(msg.getTimestamp()).toString())); item.add(new Label("LightingMessageType", msg.getType().toString())); item.add(new Label("LightingMessageContent", msg.getMessage())); } } }; systemLog.add(listView); systemLog.add(new AjaxPagingNavigator("paginatorLighting", listView)); // Update log every 5 seconds. systemLog.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)) { private static final long serialVersionUID = 1L; }); systemLog.setVersioned(false); add(systemLog); // End messages section if (LIVING_ROOM.equals(currentRoom)) { setColor = desiredLivingColor; intensity = new TextField<String>(brightID, new Model<String>(setLivingIntensity + "%")); } else if (DINING_ROOM.equals(currentRoom)) { setColor = desiredDiningColor; intensity = new TextField<String>(brightID, new Model<String>(setDiningIntensity + "%")); } else if (KITCHEN.equals(currentRoom)) { setColor = desiredKitchenColor; intensity = new TextField<String>(brightID, new Model<String>(setKitchenIntensity + "%")); } else { setColor = desiredBathroomColor; intensity = new TextField<String>(brightID, new Model<String>(setBathroomIntensity + "%")); } // Added for jquery control. intensity.setMarkupId(intensity.getId()); intensity.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * Updates the model when the value is changed on screen. */ @Override protected void onUpdate(AjaxRequestTarget target) { if (LIVING_ROOM.equals(currentRoom)) { setLivingIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setLivingIntensity: " + setLivingIntensity); } } else if (DINING_ROOM.equals(currentRoom)) { setDiningIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setDiningIntensity: " + setDiningIntensity); } } else if (KITCHEN.equals(currentRoom)) { setKitchenIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setKitchenIntensity: " + setKitchenIntensity); } } else if (BATHROOM.equals(currentRoom)) { setBathroomIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setBathroomIntensity: " + setBathroomIntensity); } } } }); // airTemp.setOutputMarkupId(true); form.add(intensity); form.add(new AjaxButton("SubmitIntensity") { // support serializable private static final long serialVersionUID = 1L; /** Provide user feeback after they set a new desired temperature */ @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { IHaleSystem system = IHaleSystem.HVAC; IHaleCommandType command = IHaleCommandType.SET_LIGHTING_LEVEL; IHaleRoom room; if (LIVING_ROOM.equals(currentRoom)) { if (setLivingIntensity == desiredLivingIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredLivingIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredLivingIntensity = setLivingIntensity; room = IHaleRoom.LIVING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredLivingIntensity); if (DEBUG) { System.out.println("do command sent for living " + "room lights intensity with level: " + desiredLivingIntensity + "%"); } intensityFeedback .setDefaultModelObject(greenTag + desiredLivingIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (DINING_ROOM.equals(currentRoom)) { if (setDiningIntensity == desiredDiningIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredDiningIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredDiningIntensity = setDiningIntensity; room = IHaleRoom.DINING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredDiningIntensity); if (DEBUG) { System.out.println("do command sent for dining " + "room lights intensity with level: " + desiredDiningIntensity + "%"); } intensityFeedback .setDefaultModelObject(greenTag + desiredDiningIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (KITCHEN.equals(currentRoom)) { if (setKitchenIntensity == desiredKitchenIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredKitchenIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredKitchenIntensity = setKitchenIntensity; room = IHaleRoom.KITCHEN; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredKitchenIntensity); if (DEBUG) { System.out.println("do command sent for kitchen room lights intensity with level: " + desiredKitchenIntensity + "%"); } intensityFeedback.setDefaultModelObject(greenTag + desiredKitchenIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (BATHROOM.equals(currentRoom)) { if (setBathroomIntensity == desiredBathroomIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredBathroomIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredBathroomIntensity = setBathroomIntensity; room = IHaleRoom.BATHROOM; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredBathroomIntensity); if (DEBUG) { System.out.println("do command sent for bathroom " + "room lights intensity with level: " + desiredBathroomIntensity + "%"); } intensityFeedback.setDefaultModelObject(greenTag + desiredBathroomIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } } }); form.setOutputMarkupId(true); // the on button onButton = new Link<String>("OnButton") { private static final long serialVersionUID = 1L; @Override /** * Turn on the light in this room. */ public void onClick() { handleRoomState(currentRoom, true); } }; // set markup id to true for ajax update onButton.setOutputMarkupId(true); // the off button offButton = new Link<String>("OffButton") { private static final long serialVersionUID = 1L; @Override /** * Turn off the light in this room. */ public void onClick() { handleRoomState(currentRoom, false); } }; // set markup id to true for ajax update offButton.setOutputMarkupId(true); // set the buttons according to user's current dropdownchoice if (LIVING_ROOM.equals(currentRoom)) { setButtons(livingState); } if (DINING_ROOM.equals(currentRoom)) { setButtons(diningState); } if (KITCHEN.equals(currentRoom)) { setButtons(kitchenState); } if (BATHROOM.equals(currentRoom)) { setButtons(bathroomState); } // create feedback for intensity intensityFeedback = new Label("intensityfeedback", "<font color=\"white\">(xxx%)</font>"); intensityFeedback.setEscapeModelStrings(false); intensityFeedback.setOutputMarkupId(true); colorChange = new HiddenField<String>("colorchange", new Model<String>(setColor)); // Added for jquery control. colorChange.setMarkupId(colorChange.getId()); colorChange.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * Updates the model when the value is changed on screen. */ @Override protected void onUpdate(AjaxRequestTarget target) { setColor = colorChange.getValue(); IHaleSystem system = IHaleSystem.LIGHTING; IHaleCommandType command = IHaleCommandType.SET_LIGHTING_COLOR; IHaleRoom room; if (LIVING_ROOM.equals(currentRoom)) { if (desiredLivingColor.equals(setColor)) { return; } else { desiredLivingColor = setColor; room = IHaleRoom.LIVING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredLivingColor); if (DEBUG) { System.out.println("do command sent for living room lights color with color: " + desiredLivingColor); } return; } } else if (DINING_ROOM.equals(currentRoom)) { if (desiredDiningColor.equals(setColor)) { return; } else { desiredDiningColor = setColor; room = IHaleRoom.DINING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredDiningColor); if (DEBUG) { System.out.println("do command sent for dining room lights color with color: " + desiredDiningColor); } return; } } else if (KITCHEN.equals(currentRoom)) { if (desiredKitchenColor.equals(setColor)) { return; } else { desiredKitchenColor = setColor; room = IHaleRoom.KITCHEN; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredKitchenColor); if (DEBUG) { System.out.println("do command sent for kitchen room lights color with color: " + desiredKitchenColor); } return; } } else if (BATHROOM.equals(currentRoom)) { if (desiredBathroomColor.equals(setColor)) { return; } else { desiredBathroomColor = setColor; room = IHaleRoom.BATHROOM; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredBathroomColor); if (DEBUG) { System.out.println("do command sent for bathroom room lights color with color: " + desiredBathroomColor); } return; } } } }); add(colorChange); form.add(intensityFeedback); add(form); roomChoices = new DropDownChoice<String>("room", new PropertyModel<String>(this, "currentRoom"), rooms); roomChoices.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 1L; /** * For when user chooses new room. */ @Override protected void onUpdate(AjaxRequestTarget target) { Repository repository = new Repository(); String newSelection = roomChoices.getDefaultModelObjectAsString(); currentRoom = newSelection; System.out.println("new room selection: " + newSelection); if (LIVING_ROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(LIVING_ROOM); // set button to living state livingState = repository.getLightingEnabled(IHaleRoom.LIVING).getValue(); setButtons(livingState); // set intensity to living state } else if (DINING_ROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(DINING_ROOM); // set button to dining state diningState = repository.getLightingEnabled(IHaleRoom.DINING).getValue(); setButtons(diningState); // set intensity to dining state } else if (KITCHEN.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(KITCHEN); // set button to kitchen state kitchenState = repository.getLightingEnabled(IHaleRoom.KITCHEN).getValue(); setButtons(kitchenState); // set intensity to kitchen state } else if (BATHROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(BATHROOM); // set button to bathroom state bathroomState = repository.getLightingEnabled(IHaleRoom.BATHROOM).getValue(); setButtons(bathroomState); // set intensity to bathroom state } // reset feedback intensityFeedback.setDefaultModelObject(""); // add components in the page we want to update to the target. target.addComponent(intensityFeedback); target.addComponent(onButton); target.addComponent(offButton); setResponsePage(Lighting.class); } }); add(roomChoices.setRequired(true)); add(onButton); add(offButton); // add(form); }
public Lighting() { ((SolarDecathlonSession) getSession()).getHeaderSession().setActiveTab(3); Repository repository = new Repository(); livingState = repository.getLightingEnabled(IHaleRoom.LIVING).getValue(); diningState = repository.getLightingEnabled(IHaleRoom.DINING).getValue(); kitchenState = repository.getLightingEnabled(IHaleRoom.KITCHEN).getValue(); bathroomState = repository.getLightingEnabled(IHaleRoom.BATHROOM).getValue(); Form<String> form = new Form<String>("form"); // Add the control for the intensity slider setLivingIntensity = repository.getLightingLevel(IHaleRoom.LIVING).getValue(); setDiningIntensity = repository.getLightingLevel(IHaleRoom.DINING).getValue(); setKitchenIntensity = repository.getLightingLevel(IHaleRoom.KITCHEN).getValue(); setBathroomIntensity = repository.getLightingLevel(IHaleRoom.BATHROOM).getValue(); desiredLivingColor = repository.getLightingColor(IHaleRoom.LIVING).getValue(); desiredDiningColor = repository.getLightingColor(IHaleRoom.DINING).getValue(); desiredKitchenColor = repository.getLightingColor(IHaleRoom.KITCHEN).getValue(); desiredBathroomColor = repository.getLightingColor(IHaleRoom.BATHROOM).getValue(); // Messages // Add messages as a list view to each page // Get all messages applicable to this page List<SystemStatusMessage> msgs = SolarDecathlonApplication.getMessages().getMessages(IHaleSystem.LIGHTING); // Create wrapper container for pageable list view WebMarkupContainer systemLog = new WebMarkupContainer("LightingSystemLogContainer"); systemLog.setOutputMarkupId(true); // Create Listview PageableListView<SystemStatusMessage> listView = new PageableListView<SystemStatusMessage>("LightingStatusMessages", msgs, 10) { private static final long serialVersionUID = 1L; @Override protected void populateItem(ListItem<SystemStatusMessage> item) { SystemStatusMessage msg = item.getModelObject(); // If only the empty message is in the list, then // display "No Messages" if (msg.getType() == null) { item.add(new Label("LightingMessageType", "-")); item.add(new Label("LightingTimestamp", "-")); item.add(new Label("LightingMessageContent", "No Messages")); } // Populate data else { item.add(new Label("LightingTimestamp", new Date(msg.getTimestamp()).toString())); item.add(new Label("LightingMessageType", msg.getType().toString())); item.add(new Label("LightingMessageContent", msg.getMessage())); } } }; systemLog.add(listView); systemLog.add(new AjaxPagingNavigator("paginatorLighting", listView)); // Update log every 5 seconds. systemLog.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)) { private static final long serialVersionUID = 1L; }); systemLog.setVersioned(false); add(systemLog); // End messages section if (LIVING_ROOM.equals(currentRoom)) { setColor = desiredLivingColor; intensity = new TextField<String>(brightID, new Model<String>(setLivingIntensity + "%")); } else if (DINING_ROOM.equals(currentRoom)) { setColor = desiredDiningColor; intensity = new TextField<String>(brightID, new Model<String>(setDiningIntensity + "%")); } else if (KITCHEN.equals(currentRoom)) { setColor = desiredKitchenColor; intensity = new TextField<String>(brightID, new Model<String>(setKitchenIntensity + "%")); } else { setColor = desiredBathroomColor; intensity = new TextField<String>(brightID, new Model<String>(setBathroomIntensity + "%")); } // Added for jquery control. intensity.setMarkupId(intensity.getId()); intensity.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * Updates the model when the value is changed on screen. */ @Override protected void onUpdate(AjaxRequestTarget target) { if (LIVING_ROOM.equals(currentRoom)) { setLivingIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setLivingIntensity: " + setLivingIntensity); } } else if (DINING_ROOM.equals(currentRoom)) { setDiningIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setDiningIntensity: " + setDiningIntensity); } } else if (KITCHEN.equals(currentRoom)) { setKitchenIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setKitchenIntensity: " + setKitchenIntensity); } } else if (BATHROOM.equals(currentRoom)) { setBathroomIntensity = Integer.valueOf(intensity.getValue().substring(0, intensity.getValue().length() - 1)); if (DEBUG) { System.out.println("onUpdate setBathroomIntensity: " + setBathroomIntensity); } } } }); // airTemp.setOutputMarkupId(true); form.add(intensity); form.add(new AjaxButton("SubmitIntensity") { // support serializable private static final long serialVersionUID = 1L; /** Provide user feeback after they set a new desired temperature */ @Override protected void onSubmit(AjaxRequestTarget target, Form<?> form) { IHaleSystem system = IHaleSystem.HVAC; IHaleCommandType command = IHaleCommandType.SET_LIGHTING_LEVEL; IHaleRoom room; if (LIVING_ROOM.equals(currentRoom)) { if (setLivingIntensity == desiredLivingIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredLivingIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredLivingIntensity = setLivingIntensity; room = IHaleRoom.LIVING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredLivingIntensity); if (DEBUG) { System.out.println("do command sent for living " + "room lights intensity with level: " + desiredLivingIntensity + "%"); } intensityFeedback .setDefaultModelObject(greenTag + desiredLivingIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (DINING_ROOM.equals(currentRoom)) { if (setDiningIntensity == desiredDiningIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredDiningIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredDiningIntensity = setDiningIntensity; room = IHaleRoom.DINING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredDiningIntensity); if (DEBUG) { System.out.println("do command sent for dining " + "room lights intensity with level: " + desiredDiningIntensity + "%"); } intensityFeedback .setDefaultModelObject(greenTag + desiredDiningIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (KITCHEN.equals(currentRoom)) { if (setKitchenIntensity == desiredKitchenIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredKitchenIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredKitchenIntensity = setKitchenIntensity; room = IHaleRoom.KITCHEN; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredKitchenIntensity); if (DEBUG) { System.out.println("do command sent for kitchen room lights intensity with level: " + desiredKitchenIntensity + "%"); } intensityFeedback.setDefaultModelObject(greenTag + desiredKitchenIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } else if (BATHROOM.equals(currentRoom)) { if (setBathroomIntensity == desiredBathroomIntensity) { intensityFeedback.setDefaultModelObject(yellowTag + desiredBathroomIntensity + yellowTagEnd); target.addComponent(intensityFeedback); return; } else { desiredBathroomIntensity = setBathroomIntensity; room = IHaleRoom.BATHROOM; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredBathroomIntensity); if (DEBUG) { System.out.println("do command sent for bathroom " + "room lights intensity with level: " + desiredBathroomIntensity + "%"); } intensityFeedback.setDefaultModelObject(greenTag + desiredBathroomIntensity + greenTagEnd); target.addComponent(intensityFeedback); return; } } } }); form.setOutputMarkupId(true); // the on button onButton = new Link<String>("OnButton") { private static final long serialVersionUID = 1L; @Override /** * Turn on the light in this room. */ public void onClick() { handleRoomState(currentRoom, true); } }; // set markup id to true for ajax update onButton.setOutputMarkupId(true); // the off button offButton = new Link<String>("OffButton") { private static final long serialVersionUID = 1L; @Override /** * Turn off the light in this room. */ public void onClick() { handleRoomState(currentRoom, false); } }; // set markup id to true for ajax update offButton.setOutputMarkupId(true); // set the buttons according to user's current dropdownchoice if (LIVING_ROOM.equals(currentRoom)) { setButtons(livingState); } if (DINING_ROOM.equals(currentRoom)) { setButtons(diningState); } if (KITCHEN.equals(currentRoom)) { setButtons(kitchenState); } if (BATHROOM.equals(currentRoom)) { setButtons(bathroomState); } // create feedback for intensity intensityFeedback = new Label("intensityfeedback", "<font color=\"white\">&nbsp;</font>"); intensityFeedback.setEscapeModelStrings(false); intensityFeedback.setOutputMarkupId(true); colorChange = new HiddenField<String>("colorchange", new Model<String>(setColor)); // Added for jquery control. colorChange.setMarkupId(colorChange.getId()); colorChange.add(new AjaxFormComponentUpdatingBehavior("onchange") { /** * Serial ID. */ private static final long serialVersionUID = 1L; /** * Updates the model when the value is changed on screen. */ @Override protected void onUpdate(AjaxRequestTarget target) { setColor = colorChange.getValue(); IHaleSystem system = IHaleSystem.LIGHTING; IHaleCommandType command = IHaleCommandType.SET_LIGHTING_COLOR; IHaleRoom room; if (LIVING_ROOM.equals(currentRoom)) { if (desiredLivingColor.equals(setColor)) { return; } else { desiredLivingColor = setColor; room = IHaleRoom.LIVING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredLivingColor); if (DEBUG) { System.out.println("do command sent for living room lights color with color: " + desiredLivingColor); } return; } } else if (DINING_ROOM.equals(currentRoom)) { if (desiredDiningColor.equals(setColor)) { return; } else { desiredDiningColor = setColor; room = IHaleRoom.DINING; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredDiningColor); if (DEBUG) { System.out.println("do command sent for dining room lights color with color: " + desiredDiningColor); } return; } } else if (KITCHEN.equals(currentRoom)) { if (desiredKitchenColor.equals(setColor)) { return; } else { desiredKitchenColor = setColor; room = IHaleRoom.KITCHEN; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredKitchenColor); if (DEBUG) { System.out.println("do command sent for kitchen room lights color with color: " + desiredKitchenColor); } return; } } else if (BATHROOM.equals(currentRoom)) { if (desiredBathroomColor.equals(setColor)) { return; } else { desiredBathroomColor = setColor; room = IHaleRoom.BATHROOM; SolarDecathlonApplication.getBackend().doCommand(system, room, command, desiredBathroomColor); if (DEBUG) { System.out.println("do command sent for bathroom room lights color with color: " + desiredBathroomColor); } return; } } } }); add(colorChange); form.add(intensityFeedback); add(form); roomChoices = new DropDownChoice<String>("room", new PropertyModel<String>(this, "currentRoom"), rooms); roomChoices.add(new AjaxFormComponentUpdatingBehavior("onchange") { private static final long serialVersionUID = 1L; /** * For when user chooses new room. */ @Override protected void onUpdate(AjaxRequestTarget target) { Repository repository = new Repository(); String newSelection = roomChoices.getDefaultModelObjectAsString(); currentRoom = newSelection; System.out.println("new room selection: " + newSelection); if (LIVING_ROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(LIVING_ROOM); // set button to living state livingState = repository.getLightingEnabled(IHaleRoom.LIVING).getValue(); setButtons(livingState); // set intensity to living state } else if (DINING_ROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(DINING_ROOM); // set button to dining state diningState = repository.getLightingEnabled(IHaleRoom.DINING).getValue(); setButtons(diningState); // set intensity to dining state } else if (KITCHEN.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(KITCHEN); // set button to kitchen state kitchenState = repository.getLightingEnabled(IHaleRoom.KITCHEN).getValue(); setButtons(kitchenState); // set intensity to kitchen state } else if (BATHROOM.equals(newSelection)) { ((SolarDecathlonSession) getSession()).getLightingSession().setRoom(BATHROOM); // set button to bathroom state bathroomState = repository.getLightingEnabled(IHaleRoom.BATHROOM).getValue(); setButtons(bathroomState); // set intensity to bathroom state } // reset feedback intensityFeedback.setDefaultModelObject(""); // add components in the page we want to update to the target. target.addComponent(intensityFeedback); target.addComponent(onButton); target.addComponent(offButton); setResponsePage(Lighting.class); } }); add(roomChoices.setRequired(true)); add(onButton); add(offButton); // add(form); }
diff --git a/src/com/sunshine/SearchActivity.java b/src/com/sunshine/SearchActivity.java index 69db1ad..663bc5b 100644 --- a/src/com/sunshine/SearchActivity.java +++ b/src/com/sunshine/SearchActivity.java @@ -1,182 +1,182 @@ package com.sunshine; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.sunshine.Record.Header; import com.sunshine.Record.Question; import com.sunshine.Record.Section; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; //Activity to search for text //in the QnAs. public class SearchActivity extends Activity { private final static int MAX_RESULTS = 15; private final static String RESERVED = "b,i,a,ul,ol,li,br"; private CheckBox checkBoxQuestions, checkBoxAnswers; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_activity); ((LinearLayout)findViewById(R.id.linearLayoutMain)).setBackgroundColor( MenuActivity.BACKGROUND_DARK); ((Button)findViewById(R.id.buttonSearch)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { search(); } }); checkBoxQuestions = (CheckBox)findViewById(R.id.checkBoxQuestions); checkBoxAnswers = (CheckBox)findViewById(R.id.checkBoxAnswers); } private void search() { //Do we search through the question text? The answer text? boolean searchQs = checkBoxQuestions.isChecked(); boolean searchAs = checkBoxAnswers.isChecked(); if (!searchQs && !searchAs) { return; } String originalQuery = ((EditText)findViewById(R.id.editTextSearch)).getText().toString(); //Lowercase for consistency and HTML encoded for safety String query = originalQuery.toLowerCase(Locale.US); query = TextUtils.htmlEncode(query); if (query.length() == 0) return; try { String[] records = RecordCache.RECORDS; //Let's build a new header (QnA) out of the resuts String title = "Search: '" + originalQuery + "'"; Header h = new Header(title); //Split the query into words String[] words = query.split(" "); if (words.length < 1) return; String patternS = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; //Don't add "reserved" words, like html elements if (RESERVED.indexOf(word) == -1) { + //search for any of the words + if (patternS.length() > 0) patternS += "|"; //The word should be by itself patternS += "\\b" + Pattern.quote(word) + "\\b"; - //search for any of the words - if (i < words.length - 1) patternS += "|"; } } if (patternS.isEmpty()) return; //make sure we're searching case insensitive Pattern pattern = Pattern.compile(patternS, Pattern.CASE_INSENSITIVE); //Keep track of how good a result each one is final HashMap<Question, Integer> map = new HashMap<Record.Question, Integer>(); //For every question we have... for (String recordS : records) { Record record = RecordCache.parseRector(recordS, getAssets()); for (Section section : record) { for (Header header : section) { for (Question question : header) { //give it a weight int count = 0; if (searchQs) { //finding the text in the question itself it weighted x3 count += searchWeight(pattern, question.question, query) * 3; } if (searchAs) { count += searchWeight(pattern, question.answer, query); } //If we found anything, add it if (count > 0) { h.add(question); map.put(question, count); } } } } } //Sort the headers Collections.sort(h.questions, new Comparator<Question>() { @Override public int compare(Question lhs, Question rhs) { return map.get(rhs) - map.get(lhs); } }); //Remove any more results than the max number while (h.size() > MAX_RESULTS) { h.questions.removeLast(); } //If we had any results, show a new QnA with the results if (h.size() > 0) { Intent intent = new Intent(this, QnAActivity.class); intent.putExtra("header", h); intent.putExtra("pattern", patternS); startActivity(intent); return; } } catch (Exception e) { e.printStackTrace(); } //Otherwise, we have no results new AlertDialog.Builder(this) .setTitle("No Results") .setMessage("No results were found for '" + originalQuery + "'.") .setPositiveButton("Ok", null) .show(); } //tells how closely text matches a patter/query public int searchWeight(Pattern pattern, String text, String query) { int count = 0; Matcher matcherAs = pattern.matcher(text); while (matcherAs.find()) { //add one for every match to the pattern (any of the words) count++; } //If we had multiple words... if (query.indexOf(" ") > -1) { String qLower = text.toLowerCase(Locale.US); int index = qLower.indexOf(query); while (index >= 0) { //add 10 for every exact match of the query count += 10; index += query.length(); index = qLower.indexOf(query, index); } } return count; } }
false
true
private void search() { //Do we search through the question text? The answer text? boolean searchQs = checkBoxQuestions.isChecked(); boolean searchAs = checkBoxAnswers.isChecked(); if (!searchQs && !searchAs) { return; } String originalQuery = ((EditText)findViewById(R.id.editTextSearch)).getText().toString(); //Lowercase for consistency and HTML encoded for safety String query = originalQuery.toLowerCase(Locale.US); query = TextUtils.htmlEncode(query); if (query.length() == 0) return; try { String[] records = RecordCache.RECORDS; //Let's build a new header (QnA) out of the resuts String title = "Search: '" + originalQuery + "'"; Header h = new Header(title); //Split the query into words String[] words = query.split(" "); if (words.length < 1) return; String patternS = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; //Don't add "reserved" words, like html elements if (RESERVED.indexOf(word) == -1) { //The word should be by itself patternS += "\\b" + Pattern.quote(word) + "\\b"; //search for any of the words if (i < words.length - 1) patternS += "|"; } } if (patternS.isEmpty()) return; //make sure we're searching case insensitive Pattern pattern = Pattern.compile(patternS, Pattern.CASE_INSENSITIVE); //Keep track of how good a result each one is final HashMap<Question, Integer> map = new HashMap<Record.Question, Integer>(); //For every question we have... for (String recordS : records) { Record record = RecordCache.parseRector(recordS, getAssets()); for (Section section : record) { for (Header header : section) { for (Question question : header) { //give it a weight int count = 0; if (searchQs) { //finding the text in the question itself it weighted x3 count += searchWeight(pattern, question.question, query) * 3; } if (searchAs) { count += searchWeight(pattern, question.answer, query); } //If we found anything, add it if (count > 0) { h.add(question); map.put(question, count); } } } } } //Sort the headers Collections.sort(h.questions, new Comparator<Question>() { @Override public int compare(Question lhs, Question rhs) { return map.get(rhs) - map.get(lhs); } }); //Remove any more results than the max number while (h.size() > MAX_RESULTS) { h.questions.removeLast(); } //If we had any results, show a new QnA with the results if (h.size() > 0) { Intent intent = new Intent(this, QnAActivity.class); intent.putExtra("header", h); intent.putExtra("pattern", patternS); startActivity(intent); return; } } catch (Exception e) { e.printStackTrace(); } //Otherwise, we have no results new AlertDialog.Builder(this) .setTitle("No Results") .setMessage("No results were found for '" + originalQuery + "'.") .setPositiveButton("Ok", null) .show(); }
private void search() { //Do we search through the question text? The answer text? boolean searchQs = checkBoxQuestions.isChecked(); boolean searchAs = checkBoxAnswers.isChecked(); if (!searchQs && !searchAs) { return; } String originalQuery = ((EditText)findViewById(R.id.editTextSearch)).getText().toString(); //Lowercase for consistency and HTML encoded for safety String query = originalQuery.toLowerCase(Locale.US); query = TextUtils.htmlEncode(query); if (query.length() == 0) return; try { String[] records = RecordCache.RECORDS; //Let's build a new header (QnA) out of the resuts String title = "Search: '" + originalQuery + "'"; Header h = new Header(title); //Split the query into words String[] words = query.split(" "); if (words.length < 1) return; String patternS = ""; for (int i = 0; i < words.length; i++) { String word = words[i]; //Don't add "reserved" words, like html elements if (RESERVED.indexOf(word) == -1) { //search for any of the words if (patternS.length() > 0) patternS += "|"; //The word should be by itself patternS += "\\b" + Pattern.quote(word) + "\\b"; } } if (patternS.isEmpty()) return; //make sure we're searching case insensitive Pattern pattern = Pattern.compile(patternS, Pattern.CASE_INSENSITIVE); //Keep track of how good a result each one is final HashMap<Question, Integer> map = new HashMap<Record.Question, Integer>(); //For every question we have... for (String recordS : records) { Record record = RecordCache.parseRector(recordS, getAssets()); for (Section section : record) { for (Header header : section) { for (Question question : header) { //give it a weight int count = 0; if (searchQs) { //finding the text in the question itself it weighted x3 count += searchWeight(pattern, question.question, query) * 3; } if (searchAs) { count += searchWeight(pattern, question.answer, query); } //If we found anything, add it if (count > 0) { h.add(question); map.put(question, count); } } } } } //Sort the headers Collections.sort(h.questions, new Comparator<Question>() { @Override public int compare(Question lhs, Question rhs) { return map.get(rhs) - map.get(lhs); } }); //Remove any more results than the max number while (h.size() > MAX_RESULTS) { h.questions.removeLast(); } //If we had any results, show a new QnA with the results if (h.size() > 0) { Intent intent = new Intent(this, QnAActivity.class); intent.putExtra("header", h); intent.putExtra("pattern", patternS); startActivity(intent); return; } } catch (Exception e) { e.printStackTrace(); } //Otherwise, we have no results new AlertDialog.Builder(this) .setTitle("No Results") .setMessage("No results were found for '" + originalQuery + "'.") .setPositiveButton("Ok", null) .show(); }
diff --git a/src/com/btmura/android/reddit/app/ThingListFragment.java b/src/com/btmura/android/reddit/app/ThingListFragment.java index 19c551b1..736e65cb 100644 --- a/src/com/btmura/android/reddit/app/ThingListFragment.java +++ b/src/com/btmura/android/reddit/app/ThingListFragment.java @@ -1,530 +1,531 @@ /* * Copyright (C) 2012 Brian Muramatsu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.btmura.android.reddit.app; import android.app.Activity; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.text.TextUtils; import android.util.SparseBooleanArray; import android.view.ActionMode; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.MultiChoiceModeListener; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; import com.btmura.android.reddit.R; import com.btmura.android.reddit.accounts.AccountUtils; import com.btmura.android.reddit.database.Kinds; import com.btmura.android.reddit.database.Subreddits; import com.btmura.android.reddit.provider.Provider; import com.btmura.android.reddit.util.Flag; import com.btmura.android.reddit.util.Objects; import com.btmura.android.reddit.widget.OnVoteListener; import com.btmura.android.reddit.widget.ThingAdapter; public class ThingListFragment extends ThingProviderListFragment implements OnScrollListener, OnVoteListener, MultiChoiceModeListener { public static final String TAG = "ThingListFragment"; /** String argument specifying the account being used. */ private static final String ARG_ACCOUNT_NAME = "accountName"; /** String argument specifying the subreddit to load. */ private static final String ARG_SUBREDDIT = "subreddit"; /** String argument specifying the search query to use. */ private static final String ARG_QUERY = "query"; /** String argument specifying the profileUser profile to load. */ private static final String ARG_PROFILE_USER = "profileUser"; /** String argument specifying whose messages to load. */ private static final String ARG_MESSAGE_USER = "messageUser"; /** Integer argument to filter things, profile, or messages. */ private static final String ARG_FILTER = "filter"; /** String argument that is used to paginate things. */ private static final String ARG_MORE = "more"; /** Optional bit mask for controlling fragment appearance. */ private static final String ARG_FLAGS = "flags"; public static final int FLAG_SINGLE_CHOICE = 0x1; private static final String STATE_ACCOUNT_NAME = ARG_ACCOUNT_NAME; private static final String STATE_PARENT_SUBREDDIT = "parentSubreddit"; private static final String STATE_SUBREDDIT = ARG_SUBREDDIT; /** String argument specifying session ID of the data. */ private static final String STATE_SESSION_ID = "sessionId"; private static final String STATE_SELECTED_THING_ID = "selectedThingId"; private static final String STATE_SELECTED_LINK_ID = "selectedLinkId"; private static final String STATE_EMPTY_TEXT = "emptyText"; public interface OnThingSelectedListener { void onThingSelected(Bundle thingBundle, int pageType); int onMeasureThingBody(); } private OnThingSelectedListener listener; private OnSubredditEventListener eventListener; private ThingBundleHolder thingBundleHolder; private ThingAdapter adapter; private int emptyText; private boolean scrollLoading; public static ThingListFragment newSubredditInstance(String accountName, String subreddit, int filter, int flags) { Bundle args = new Bundle(4); args.putString(ARG_ACCOUNT_NAME, accountName); args.putString(ARG_SUBREDDIT, subreddit); args.putInt(ARG_FILTER, filter); args.putInt(ARG_FLAGS, flags); return newFragment(args); } public static ThingListFragment newQueryInstance(String accountName, String subreddit, String query, int flags) { Bundle args = new Bundle(4); args.putString(ARG_ACCOUNT_NAME, accountName); args.putString(ARG_SUBREDDIT, subreddit); args.putString(ARG_QUERY, query); args.putInt(ARG_FLAGS, flags); return newFragment(args); } public static ThingListFragment newInstance(String accountName, String subreddit, String query, String profileUser, String messageUser, int filter, int flags) { Bundle args = new Bundle(7); args.putString(ARG_ACCOUNT_NAME, accountName); args.putString(ARG_SUBREDDIT, subreddit); args.putString(ARG_QUERY, query); args.putString(ARG_PROFILE_USER, profileUser); args.putString(ARG_MESSAGE_USER, messageUser); args.putInt(ARG_FILTER, filter); args.putInt(ARG_FLAGS, flags); return newFragment(args); } private static ThingListFragment newFragment(Bundle args) { ThingListFragment frag = new ThingListFragment(); frag.setArguments(args); return frag; } @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof OnThingSelectedListener) { listener = (OnThingSelectedListener) activity; } if (activity instanceof OnSubredditEventListener) { eventListener = (OnSubredditEventListener) activity; } if (activity instanceof ThingBundleHolder) { thingBundleHolder = (ThingBundleHolder) activity; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int flags = getArguments().getInt(ARG_FLAGS); boolean singleChoice = Flag.isEnabled(flags, FLAG_SINGLE_CHOICE); adapter = new ThingAdapter(getActivity(), getArguments().getString(ARG_SUBREDDIT), getArguments().getString(ARG_QUERY), getArguments().getString(ARG_PROFILE_USER), getArguments().getString(ARG_MESSAGE_USER), getArguments().getInt(ARG_FILTER), this, singleChoice); adapter.setAccountName(getArguments().getString(ARG_ACCOUNT_NAME)); adapter.setParentSubreddit(getArguments().getString(ARG_SUBREDDIT)); if (savedInstanceState != null) { adapter.setSessionId(savedInstanceState.getLong(STATE_SESSION_ID)); adapter.setAccountName(savedInstanceState.getString(STATE_ACCOUNT_NAME)); adapter.setParentSubreddit(savedInstanceState.getString(STATE_PARENT_SUBREDDIT)); adapter.setSubreddit(savedInstanceState.getString(STATE_SUBREDDIT)); String thingId = savedInstanceState.getString(STATE_SELECTED_THING_ID); String linkId = savedInstanceState.getString(STATE_SELECTED_LINK_ID); adapter.setSelectedThing(thingId, linkId); emptyText = savedInstanceState.getInt(STATE_EMPTY_TEXT); } setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = super.onCreateView(inflater, container, savedInstanceState); ListView l = (ListView) v.findViewById(android.R.id.list); l.setVerticalScrollBarEnabled(false); l.setOnScrollListener(this); l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); l.setMultiChoiceModeListener(this); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); adapter.setThingBodyWidth(getThingBodyWidth()); setListAdapter(adapter); setListShown(false); if (emptyText == 0) { loadIfPossible(); } else { showEmpty(); } } public void loadIfPossible() { if (adapter.isLoadable()) { getLoaderManager().initLoader(0, null, this); } } public void setEmpty(boolean error) { this.emptyText = error ? R.string.error : R.string.empty_list; showEmpty(); } private void showEmpty() { setEmptyText(getString(emptyText)); setListShown(true); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { if (args != null) { adapter.setMore(args.getString(ARG_MORE)); } return adapter.getLoader(getActivity()); } public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Process ThingProvider results. super.onLoadFinished(loader, cursor); scrollLoading = false; adapter.setMore(null); adapter.updateLoaderUri(getActivity(), loader); adapter.swapCursor(cursor); setEmptyText(getString(cursor != null ? R.string.empty_list : R.string.error)); setListShown(true); getActivity().invalidateOptionsMenu(); } public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } @Override protected void onSessionIdLoaded(long sessionId) { adapter.setSessionId(sessionId); } @Override protected void onSubredditLoaded(String subreddit) { adapter.setParentSubreddit(subreddit); adapter.setSubreddit(subreddit); if (eventListener != null) { eventListener.onSubredditDiscovery(subreddit); } } public void onScrollStateChanged(AbsListView view, int scrollState) { } public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (visibleItemCount <= 0 || scrollLoading) { return; } if (firstVisibleItem + visibleItemCount * 2 >= totalItemCount) { if (getLoaderManager().getLoader(0) != null) { if (!adapter.isEmpty()) { String more = adapter.getNextMore(); if (!TextUtils.isEmpty(more)) { scrollLoading = true; Bundle b = new Bundle(1); b.putString(ARG_MORE, more); getLoaderManager().restartLoader(0, b, this); } } } } } @Override public void onListItemClick(ListView l, View v, int position, long id) { selectThing(position, ThingPagerAdapter.TYPE_LINK); } private void selectThing(int position, int pageType) { adapter.setSelectedPosition(position); if (listener != null) { listener.onThingSelected(adapter.getThingBundle(getActivity(), position), pageType); } if (adapter.isNew(position)) { Provider.readMessageAsync(getActivity(), adapter.getAccountName(), adapter.getThingId(position), true); } } public void onVote(View v, int action) { if (!TextUtils.isEmpty(adapter.getAccountName())) { int position = getListView().getPositionForView(v); adapter.vote(getActivity(), position, action); } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.thing_list_menu, menu); } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); String subreddit = getSubreddit(); boolean hasAccount = AccountUtils.isAccount(getAccountName()); boolean hasSubreddit = subreddit != null; boolean hasThing = thingBundleHolder != null && thingBundleHolder.getThingBundle() != null; boolean showNewPost = hasAccount && hasSubreddit && !hasThing; boolean showAddSubreddit = hasSubreddit && !hasThing; boolean showSubreddit = hasSubreddit && !hasThing && Subreddits.hasSidebar(subreddit); menu.findItem(R.id.menu_new_post).setVisible(showNewPost); menu.findItem(R.id.menu_add_subreddit).setVisible(showAddSubreddit); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(showSubreddit); if (showSubreddit) { subredditItem.setTitle(MenuHelper.getSubredditTitle(getActivity(), subreddit)); } } public boolean onCreateActionMode(ActionMode mode, Menu menu) { if (adapter.getCursor() == null) { getListView().clearChoices(); return false; } MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.thing_action_menu, menu); return true; } public boolean onPrepareActionMode(ActionMode mode, Menu menu) { int position = getFirstCheckedPosition(); int count = getListView().getCheckedItemCount(); mode.setTitle(getResources().getQuantityString(R.plurals.things, count, count)); menu.findItem(R.id.menu_copy_url).setVisible(count == 1); MenuItem authorItem = menu.findItem(R.id.menu_author); String author = adapter.getAuthor(position); authorItem.setVisible(count == 1 && MenuHelper.isUserItemVisible(author)); if (authorItem.isVisible()) { authorItem.setTitle(MenuHelper.getUserTitle(getActivity(), author)); } String subreddit = adapter.getSubreddit(position); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(count == 1 && Subreddits.hasSidebar(subreddit)); if (subredditItem.isVisible()) { subredditItem.setTitle(MenuHelper.getSubredditTitle(getActivity(), subreddit)); } MenuItem shareItem = menu.findItem(R.id.menu_share_thing); shareItem.setVisible(count == 1); if (shareItem.isVisible()) { String label = adapter.getTitle(position); CharSequence text = adapter.getUrl(position); MenuHelper.setShareProvider(menu.findItem(R.id.menu_share_thing), label, text); } + boolean isLink = adapter.getKind(position) == Kinds.KIND_LINK; MenuItem commentsItem = menu.findItem(R.id.menu_comments); - commentsItem.setVisible(count == 1); + commentsItem.setVisible(count == 1 && isLink); boolean saveable = false; boolean saved = false; boolean hasAccount = count == 1 && AccountUtils.isAccount(adapter.getAccountName()); if (hasAccount) { - saveable = adapter.getKind(position) == Kinds.KIND_LINK; + saveable = isLink; saved = adapter.isSaved(position); } menu.findItem(R.id.menu_saved).setVisible(saveable && saved); menu.findItem(R.id.menu_unsaved).setVisible(saveable && !saved); return true; } public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { mode.invalidate(); } public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.menu_saved: handleSaved(); mode.finish(); return true; case R.id.menu_unsaved: handleUnsaved(); mode.finish(); return true; case R.id.menu_comments: handleComments(); mode.finish(); return true; case R.id.menu_copy_url: handleCopyUrl(); mode.finish(); return true; case R.id.menu_author: handleAuthor(); mode.finish(); return true; case R.id.menu_subreddit: handleSubreddit(); mode.finish(); return true; default: return false; } } private void handleSaved() { adapter.unsave(getActivity(), getFirstCheckedPosition()); } private void handleUnsaved() { adapter.save(getActivity(), getFirstCheckedPosition()); } private void handleComments() { selectThing(getFirstCheckedPosition(), ThingPagerAdapter.TYPE_COMMENTS); } private void handleCopyUrl() { int position = getFirstCheckedPosition(); String title = adapter.getTitle(position); CharSequence url = adapter.getUrl(position); MenuHelper.setClipAndToast(getActivity(), title, url); } private void handleAuthor() { String user = adapter.getAuthor(getFirstCheckedPosition()); MenuHelper.startProfileActivity(getActivity(), user, -1); } private void handleSubreddit() { String subreddit = adapter.getSubreddit(getFirstCheckedPosition()); MenuHelper.startSidebarActivity(getActivity(), subreddit); } public void onDestroyActionMode(ActionMode mode) { } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(STATE_SESSION_ID, adapter.getSessionId()); outState.putString(STATE_ACCOUNT_NAME, adapter.getAccountName()); outState.putString(STATE_PARENT_SUBREDDIT, adapter.getParentSubreddit()); outState.putString(STATE_SUBREDDIT, adapter.getSubreddit()); outState.putString(STATE_SELECTED_THING_ID, adapter.getSelectedThingId()); outState.putString(STATE_SELECTED_LINK_ID, adapter.getSelectedLinkId()); outState.putInt(STATE_EMPTY_TEXT, emptyText); } private int getThingBodyWidth() { return listener != null ? listener.onMeasureThingBody() : 0; } public void setAccountName(String accountName) { adapter.setAccountName(accountName); } public void setSelectedThing(String thingId, String linkId) { adapter.setSelectedThing(thingId, linkId); } public String getAccountName() { return adapter.getAccountName(); } public String getSubreddit() { return adapter.getSubreddit(); } public void setSubreddit(String subreddit) { if (!Objects.equalsIgnoreCase(subreddit, adapter.getSubreddit())) { adapter.setSubreddit(subreddit); } } public String getQuery() { return adapter.getQuery(); } public int getFilter() { return adapter.getFilterValue(); } private int getFirstCheckedPosition() { SparseBooleanArray checked = getListView().getCheckedItemPositions(); int size = adapter.getCount(); for (int i = 0; i < size; i++) { if (checked.get(i)) { return i; } } return -1; } }
false
true
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { int position = getFirstCheckedPosition(); int count = getListView().getCheckedItemCount(); mode.setTitle(getResources().getQuantityString(R.plurals.things, count, count)); menu.findItem(R.id.menu_copy_url).setVisible(count == 1); MenuItem authorItem = menu.findItem(R.id.menu_author); String author = adapter.getAuthor(position); authorItem.setVisible(count == 1 && MenuHelper.isUserItemVisible(author)); if (authorItem.isVisible()) { authorItem.setTitle(MenuHelper.getUserTitle(getActivity(), author)); } String subreddit = adapter.getSubreddit(position); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(count == 1 && Subreddits.hasSidebar(subreddit)); if (subredditItem.isVisible()) { subredditItem.setTitle(MenuHelper.getSubredditTitle(getActivity(), subreddit)); } MenuItem shareItem = menu.findItem(R.id.menu_share_thing); shareItem.setVisible(count == 1); if (shareItem.isVisible()) { String label = adapter.getTitle(position); CharSequence text = adapter.getUrl(position); MenuHelper.setShareProvider(menu.findItem(R.id.menu_share_thing), label, text); } MenuItem commentsItem = menu.findItem(R.id.menu_comments); commentsItem.setVisible(count == 1); boolean saveable = false; boolean saved = false; boolean hasAccount = count == 1 && AccountUtils.isAccount(adapter.getAccountName()); if (hasAccount) { saveable = adapter.getKind(position) == Kinds.KIND_LINK; saved = adapter.isSaved(position); } menu.findItem(R.id.menu_saved).setVisible(saveable && saved); menu.findItem(R.id.menu_unsaved).setVisible(saveable && !saved); return true; }
public boolean onPrepareActionMode(ActionMode mode, Menu menu) { int position = getFirstCheckedPosition(); int count = getListView().getCheckedItemCount(); mode.setTitle(getResources().getQuantityString(R.plurals.things, count, count)); menu.findItem(R.id.menu_copy_url).setVisible(count == 1); MenuItem authorItem = menu.findItem(R.id.menu_author); String author = adapter.getAuthor(position); authorItem.setVisible(count == 1 && MenuHelper.isUserItemVisible(author)); if (authorItem.isVisible()) { authorItem.setTitle(MenuHelper.getUserTitle(getActivity(), author)); } String subreddit = adapter.getSubreddit(position); MenuItem subredditItem = menu.findItem(R.id.menu_subreddit); subredditItem.setVisible(count == 1 && Subreddits.hasSidebar(subreddit)); if (subredditItem.isVisible()) { subredditItem.setTitle(MenuHelper.getSubredditTitle(getActivity(), subreddit)); } MenuItem shareItem = menu.findItem(R.id.menu_share_thing); shareItem.setVisible(count == 1); if (shareItem.isVisible()) { String label = adapter.getTitle(position); CharSequence text = adapter.getUrl(position); MenuHelper.setShareProvider(menu.findItem(R.id.menu_share_thing), label, text); } boolean isLink = adapter.getKind(position) == Kinds.KIND_LINK; MenuItem commentsItem = menu.findItem(R.id.menu_comments); commentsItem.setVisible(count == 1 && isLink); boolean saveable = false; boolean saved = false; boolean hasAccount = count == 1 && AccountUtils.isAccount(adapter.getAccountName()); if (hasAccount) { saveable = isLink; saved = adapter.isSaved(position); } menu.findItem(R.id.menu_saved).setVisible(saveable && saved); menu.findItem(R.id.menu_unsaved).setVisible(saveable && !saved); return true; }
diff --git a/trunk/uim/orchestration/basic/src/main/java/eu/europeana/uim/orchestration/UIMWorkflowProcessor.java b/trunk/uim/orchestration/basic/src/main/java/eu/europeana/uim/orchestration/UIMWorkflowProcessor.java index fc9d1301..ae757174 100644 --- a/trunk/uim/orchestration/basic/src/main/java/eu/europeana/uim/orchestration/UIMWorkflowProcessor.java +++ b/trunk/uim/orchestration/basic/src/main/java/eu/europeana/uim/orchestration/UIMWorkflowProcessor.java @@ -1,216 +1,216 @@ package eu.europeana.uim.orchestration; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; import eu.europeana.uim.api.ActiveExecution; import eu.europeana.uim.api.Registry; import eu.europeana.uim.api.StorageEngineException; import eu.europeana.uim.orchestration.processing.TaskExecutorRegistry; import eu.europeana.uim.orchestration.processing.TaskExecutorThread; import eu.europeana.uim.orchestration.processing.TaskExecutorThreadFactory; import eu.europeana.uim.util.BatchWorkflowStart; import eu.europeana.uim.workflow.Task; import eu.europeana.uim.workflow.TaskStatus; import eu.europeana.uim.workflow.WorkflowStart; import eu.europeana.uim.workflow.WorkflowStep; public class UIMWorkflowProcessor implements Runnable { private static Logger log = Logger.getLogger(UIMWorkflowProcessor.class.getName()); private TaskExecutorThreadFactory factory = new TaskExecutorThreadFactory("processor"); private TaskExecutorThread dispatcherThread; private final Registry registry; private boolean running = false; private List<ActiveExecution<Task>> executions = new ArrayList<ActiveExecution<Task>>(); public UIMWorkflowProcessor(Registry registry) { this.registry = registry; } public void run() { running = true; while (running) { int total = 0; try { Iterator<ActiveExecution<Task>> iterator = executions.iterator(); while (iterator.hasNext()) { ActiveExecution<Task> execution = iterator.next(); total += execution.getProgressSize(); // well we skip this execution if it is paused, // FIXME: if only paused executions are around then // we do somehow busy waiting - total count is > 0 if (execution.isPaused()) continue; try { // we ask the workflow start if we have more to do if (execution.getProgressSize() == 0) { WorkflowStart start = execution.getWorkflow().getStart(); int tasks = start.createWorkflowTasks(execution); if (tasks == 0) { if (start.isFinished(execution)) { if (execution.isFinished()) { Thread.sleep(100); if (execution.isFinished()) { execution.setActive(false); execution.setEndTime(new Date()); start.finalize(execution); for (WorkflowStep step : execution.getWorkflow().getSteps()) { step.finalize(execution); } execution.getStorageEngine().updateExecution( execution.getExecution()); iterator.remove(); } } } else { Runnable loader = start.createLoader(execution); if (loader != null) { start.getThreadPoolExecutor().execute(loader); } } } else { - if (start.getScheduledSize() == -1) { + if (start.getScheduledSize() > -1) { execution.incrementScheduled(tasks); } } } Queue<Task> success = execution.getSuccess(execution.getWorkflow().getStart().getIdentifier()); List<WorkflowStep> steps = execution.getWorkflow().getSteps(); for (WorkflowStep step : steps) { Queue<Task> thisSuccess = execution.getSuccess(step.getIdentifier()); Queue<Task> thisFailure = execution.getFailure(step.getIdentifier()); // get successful tasks from previouse step // and schedule them into the step executor. Task task = null; synchronized (success) { task = success.poll(); } while (task != null) { task.setStep(step); task.setOnSuccess(thisSuccess); task.setOnFailure(thisFailure); task.setStatus(TaskStatus.QUEUED); step.getThreadPoolExecutor().execute(task); synchronized (success) { task = success.poll(); } } // make the current success list the "next" input list success = thisSuccess; } // save and clean final Task task; synchronized (success) { task = success.poll(); } while (task != null) { task.save(); execution.done(1); execution.getMonitor().worked(1); synchronized (success) { task = success.poll(); } } } catch (Throwable exc) { log.log(Level.WARNING, "Exception in workflow execution", exc); // execution.setActive(false); // execution.setThrowable(exc); // iterator.remove(); } } if (total == 0) { Thread.sleep(25); } } catch (Throwable exc) { log.log(Level.SEVERE, "Exception in workflow executor", exc); } } } public synchronized void schedule(ActiveExecution<Task> execution) throws StorageEngineException { if (execution.getWorkflow().getSteps().isEmpty()) throw new IllegalStateException("Empty workflow not allowed: " + execution.getWorkflow().getClass().getName()); WorkflowStart start = execution.getWorkflow().getStart(); if (start == null) { execution.getWorkflow().setStart(new BatchWorkflowStart()); } start.initialize(execution); TaskExecutorRegistry.getInstance().initialize(start, start.getMaximumThreadCount()); for (WorkflowStep step : execution.getWorkflow().getSteps()) { step.initialize(execution); TaskExecutorRegistry.getInstance().initialize(step, step.getMaximumThreadCount()); } // initialize the scheduled number of records for this execution if (start.getScheduledSize() != -1) { execution.setScheduled(start.getScheduledSize()); } // start/execute the first loader task so that we do preload data start.getThreadPoolExecutor().execute(start.createLoader(execution)); executions.add(execution); } public synchronized List<ActiveExecution<Task>> getExecutions() { return Collections.unmodifiableList(executions); } public void initialize() { running = false; } public void startup() { dispatcherThread = (TaskExecutorThread)factory.newThread(this); dispatcherThread.start(); } public void shutdown() { running = false; dispatcherThread = null; } public void pause() { running = false; dispatcherThread = null; } public void resume() { running = true; dispatcherThread = (TaskExecutorThread)factory.newThread(this); dispatcherThread.start(); } }
true
true
public void run() { running = true; while (running) { int total = 0; try { Iterator<ActiveExecution<Task>> iterator = executions.iterator(); while (iterator.hasNext()) { ActiveExecution<Task> execution = iterator.next(); total += execution.getProgressSize(); // well we skip this execution if it is paused, // FIXME: if only paused executions are around then // we do somehow busy waiting - total count is > 0 if (execution.isPaused()) continue; try { // we ask the workflow start if we have more to do if (execution.getProgressSize() == 0) { WorkflowStart start = execution.getWorkflow().getStart(); int tasks = start.createWorkflowTasks(execution); if (tasks == 0) { if (start.isFinished(execution)) { if (execution.isFinished()) { Thread.sleep(100); if (execution.isFinished()) { execution.setActive(false); execution.setEndTime(new Date()); start.finalize(execution); for (WorkflowStep step : execution.getWorkflow().getSteps()) { step.finalize(execution); } execution.getStorageEngine().updateExecution( execution.getExecution()); iterator.remove(); } } } else { Runnable loader = start.createLoader(execution); if (loader != null) { start.getThreadPoolExecutor().execute(loader); } } } else { if (start.getScheduledSize() == -1) { execution.incrementScheduled(tasks); } } } Queue<Task> success = execution.getSuccess(execution.getWorkflow().getStart().getIdentifier()); List<WorkflowStep> steps = execution.getWorkflow().getSteps(); for (WorkflowStep step : steps) { Queue<Task> thisSuccess = execution.getSuccess(step.getIdentifier()); Queue<Task> thisFailure = execution.getFailure(step.getIdentifier()); // get successful tasks from previouse step // and schedule them into the step executor. Task task = null; synchronized (success) { task = success.poll(); } while (task != null) { task.setStep(step); task.setOnSuccess(thisSuccess); task.setOnFailure(thisFailure); task.setStatus(TaskStatus.QUEUED); step.getThreadPoolExecutor().execute(task); synchronized (success) { task = success.poll(); } } // make the current success list the "next" input list success = thisSuccess; } // save and clean final Task task; synchronized (success) { task = success.poll(); } while (task != null) { task.save(); execution.done(1); execution.getMonitor().worked(1); synchronized (success) { task = success.poll(); } } } catch (Throwable exc) { log.log(Level.WARNING, "Exception in workflow execution", exc); // execution.setActive(false); // execution.setThrowable(exc); // iterator.remove(); } } if (total == 0) { Thread.sleep(25); } } catch (Throwable exc) { log.log(Level.SEVERE, "Exception in workflow executor", exc); } } }
public void run() { running = true; while (running) { int total = 0; try { Iterator<ActiveExecution<Task>> iterator = executions.iterator(); while (iterator.hasNext()) { ActiveExecution<Task> execution = iterator.next(); total += execution.getProgressSize(); // well we skip this execution if it is paused, // FIXME: if only paused executions are around then // we do somehow busy waiting - total count is > 0 if (execution.isPaused()) continue; try { // we ask the workflow start if we have more to do if (execution.getProgressSize() == 0) { WorkflowStart start = execution.getWorkflow().getStart(); int tasks = start.createWorkflowTasks(execution); if (tasks == 0) { if (start.isFinished(execution)) { if (execution.isFinished()) { Thread.sleep(100); if (execution.isFinished()) { execution.setActive(false); execution.setEndTime(new Date()); start.finalize(execution); for (WorkflowStep step : execution.getWorkflow().getSteps()) { step.finalize(execution); } execution.getStorageEngine().updateExecution( execution.getExecution()); iterator.remove(); } } } else { Runnable loader = start.createLoader(execution); if (loader != null) { start.getThreadPoolExecutor().execute(loader); } } } else { if (start.getScheduledSize() > -1) { execution.incrementScheduled(tasks); } } } Queue<Task> success = execution.getSuccess(execution.getWorkflow().getStart().getIdentifier()); List<WorkflowStep> steps = execution.getWorkflow().getSteps(); for (WorkflowStep step : steps) { Queue<Task> thisSuccess = execution.getSuccess(step.getIdentifier()); Queue<Task> thisFailure = execution.getFailure(step.getIdentifier()); // get successful tasks from previouse step // and schedule them into the step executor. Task task = null; synchronized (success) { task = success.poll(); } while (task != null) { task.setStep(step); task.setOnSuccess(thisSuccess); task.setOnFailure(thisFailure); task.setStatus(TaskStatus.QUEUED); step.getThreadPoolExecutor().execute(task); synchronized (success) { task = success.poll(); } } // make the current success list the "next" input list success = thisSuccess; } // save and clean final Task task; synchronized (success) { task = success.poll(); } while (task != null) { task.save(); execution.done(1); execution.getMonitor().worked(1); synchronized (success) { task = success.poll(); } } } catch (Throwable exc) { log.log(Level.WARNING, "Exception in workflow execution", exc); // execution.setActive(false); // execution.setThrowable(exc); // iterator.remove(); } } if (total == 0) { Thread.sleep(25); } } catch (Throwable exc) { log.log(Level.SEVERE, "Exception in workflow executor", exc); } } }
diff --git a/javasrc/src/org/ccnx/ccn/utils/CommonArguments.java b/javasrc/src/org/ccnx/ccn/utils/CommonArguments.java index 4531941d1..01d56327d 100644 --- a/javasrc/src/org/ccnx/ccn/utils/CommonArguments.java +++ b/javasrc/src/org/ccnx/ccn/utils/CommonArguments.java @@ -1,68 +1,68 @@ /* * A CCNx command line utility. * * Copyright (C) 2011 Palo Alto Research Center, Inc. * * This work is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License version 2 as published by the * Free Software Foundation. * This work is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ package org.ccnx.ccn.utils; import java.util.logging.Level; import org.ccnx.ccn.impl.support.Log; /** * Parse arguments that are used in all the I/O utilities */ public abstract class CommonArguments { public static boolean parseArguments(String[] args, int i, Usage u) { boolean ret = true; if (args[i].equals("-unversioned")) { CommonParameters.unversioned = true; } else if (args[i].equals("-timeout")) { if (args.length < (i + 2)) { u.usage(); } try { - CommonParameters.timeout = Integer.parseInt(args[i++]); + CommonParameters.timeout = Integer.parseInt(args[++i]); } catch (NumberFormatException nfe) { u.usage(); } } else if (args[i].equals("-log")) { Level level = null; if (args.length < (i + 2)) { u.usage(); } try { level = Level.parse(args[++i]); } catch (NumberFormatException nfe) { u.usage(); } Log.setLevel(Log.FAC_ALL, level); } else if (args[i].equals("-v")) { CommonParameters.verbose = true; } else if (args[i].equals("-as")) { if (args.length < (i + 2)) { u.usage(); } CommonSecurity.setUser(args[++i]); } else if (args[i].equals("-ac")) { CommonSecurity.setAccessControl(); } else { ret = false; } if (CommonParameters.startArg < i + 1) CommonParameters.startArg = i + 1; return ret; } }
true
true
public static boolean parseArguments(String[] args, int i, Usage u) { boolean ret = true; if (args[i].equals("-unversioned")) { CommonParameters.unversioned = true; } else if (args[i].equals("-timeout")) { if (args.length < (i + 2)) { u.usage(); } try { CommonParameters.timeout = Integer.parseInt(args[i++]); } catch (NumberFormatException nfe) { u.usage(); } } else if (args[i].equals("-log")) { Level level = null; if (args.length < (i + 2)) { u.usage(); } try { level = Level.parse(args[++i]); } catch (NumberFormatException nfe) { u.usage(); } Log.setLevel(Log.FAC_ALL, level); } else if (args[i].equals("-v")) { CommonParameters.verbose = true; } else if (args[i].equals("-as")) { if (args.length < (i + 2)) { u.usage(); } CommonSecurity.setUser(args[++i]); } else if (args[i].equals("-ac")) { CommonSecurity.setAccessControl(); } else { ret = false; } if (CommonParameters.startArg < i + 1) CommonParameters.startArg = i + 1; return ret; }
public static boolean parseArguments(String[] args, int i, Usage u) { boolean ret = true; if (args[i].equals("-unversioned")) { CommonParameters.unversioned = true; } else if (args[i].equals("-timeout")) { if (args.length < (i + 2)) { u.usage(); } try { CommonParameters.timeout = Integer.parseInt(args[++i]); } catch (NumberFormatException nfe) { u.usage(); } } else if (args[i].equals("-log")) { Level level = null; if (args.length < (i + 2)) { u.usage(); } try { level = Level.parse(args[++i]); } catch (NumberFormatException nfe) { u.usage(); } Log.setLevel(Log.FAC_ALL, level); } else if (args[i].equals("-v")) { CommonParameters.verbose = true; } else if (args[i].equals("-as")) { if (args.length < (i + 2)) { u.usage(); } CommonSecurity.setUser(args[++i]); } else if (args[i].equals("-ac")) { CommonSecurity.setAccessControl(); } else { ret = false; } if (CommonParameters.startArg < i + 1) CommonParameters.startArg = i + 1; return ret; }
diff --git a/framework/src/com/phonegap/ContactManager.java b/framework/src/com/phonegap/ContactManager.java index 5a79c37a..7ef70c18 100755 --- a/framework/src/com/phonegap/ContactManager.java +++ b/framework/src/com/phonegap/ContactManager.java @@ -1,67 +1,74 @@ /* * PhoneGap is available under *either* the terms of the modified BSD license *or* the * MIT License (2008). See http://opensource.org/licenses/alphabetical for full text. * * Copyright (c) 2005-2010, Nitobi Software Inc. * Copyright (c) 2010, IBM Corporation */ package com.phonegap; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.phonegap.api.Plugin; import com.phonegap.api.PluginResult; import android.util.Log; public class ContactManager extends Plugin { private static ContactAccessor contactAccessor; private static final String LOG_TAG = "Contact Query"; /** * Constructor. */ public ContactManager() { } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArry of arguments for the plugin. * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. */ public PluginResult execute(String action, JSONArray args, String callbackId) { if (contactAccessor == null) { contactAccessor = ContactAccessor.getInstance(webView, ctx); } PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("search")) { JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1)); return new PluginResult(status, res, "navigator.service.contacts.cast"); } else if (action.equals("save")) { - return new PluginResult(status, contactAccessor.save(args.getJSONObject(0))); + if (contactAccessor.save(args.getJSONObject(0))) { + return new PluginResult(status, result); + } + else { + JSONObject r = new JSONObject(); + r.put("code", 0); + return new PluginResult(PluginResult.Status.ERROR, r); + } } else if (action.equals("remove")) { if (contactAccessor.remove(args.getString(0))) { return new PluginResult(status, result); } else { JSONObject r = new JSONObject(); r.put("code", 2); return new PluginResult(PluginResult.Status.ERROR, r); } } return new PluginResult(status, result); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } } }
true
true
public PluginResult execute(String action, JSONArray args, String callbackId) { if (contactAccessor == null) { contactAccessor = ContactAccessor.getInstance(webView, ctx); } PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("search")) { JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1)); return new PluginResult(status, res, "navigator.service.contacts.cast"); } else if (action.equals("save")) { return new PluginResult(status, contactAccessor.save(args.getJSONObject(0))); } else if (action.equals("remove")) { if (contactAccessor.remove(args.getString(0))) { return new PluginResult(status, result); } else { JSONObject r = new JSONObject(); r.put("code", 2); return new PluginResult(PluginResult.Status.ERROR, r); } } return new PluginResult(status, result); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
public PluginResult execute(String action, JSONArray args, String callbackId) { if (contactAccessor == null) { contactAccessor = ContactAccessor.getInstance(webView, ctx); } PluginResult.Status status = PluginResult.Status.OK; String result = ""; try { if (action.equals("search")) { JSONArray res = contactAccessor.search(args.getJSONArray(0), args.optJSONObject(1)); return new PluginResult(status, res, "navigator.service.contacts.cast"); } else if (action.equals("save")) { if (contactAccessor.save(args.getJSONObject(0))) { return new PluginResult(status, result); } else { JSONObject r = new JSONObject(); r.put("code", 0); return new PluginResult(PluginResult.Status.ERROR, r); } } else if (action.equals("remove")) { if (contactAccessor.remove(args.getString(0))) { return new PluginResult(status, result); } else { JSONObject r = new JSONObject(); r.put("code", 2); return new PluginResult(PluginResult.Status.ERROR, r); } } return new PluginResult(status, result); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } }
diff --git a/DataDroid/src/com/foxykeep/datadroid/internal/network/NetworkConnectionImpl.java b/DataDroid/src/com/foxykeep/datadroid/internal/network/NetworkConnectionImpl.java index 9ca7a15..4f1080f 100644 --- a/DataDroid/src/com/foxykeep/datadroid/internal/network/NetworkConnectionImpl.java +++ b/DataDroid/src/com/foxykeep/datadroid/internal/network/NetworkConnectionImpl.java @@ -1,338 +1,337 @@ /** * 2011 Foxykeep (http://datadroid.foxykeep.com) * <p> * Licensed under the Beerware License : <br /> * As long as you retain this notice you can do whatever you want with this stuff. If we meet some * day, and you think this stuff is worth it, you can buy me a beer in return */ package com.foxykeep.datadroid.internal.network; import android.content.Context; import android.support.util.Base64; import android.util.Log; import com.foxykeep.datadroid.exception.ConnectionException; import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult; import com.foxykeep.datadroid.network.NetworkConnection.Method; import com.foxykeep.datadroid.network.UserAgentUtils; import com.foxykeep.datadroid.util.DataDroidLog; import org.apache.http.HttpStatus; import org.apache.http.auth.UsernamePasswordCredentials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate; import java.util.HashMap; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; /** * Implementation of the network connection. * * @author Foxykeep */ public final class NetworkConnectionImpl { private static final String TAG = NetworkConnectionImpl.class.getSimpleName(); private static final String ACCEPT_CHARSET_HEADER = "Accept-Charset"; private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; private static final String AUTHORIZATION_HEADER = "Authorization"; private static final String CONTENT_ENCODING_HEADER = "Content-Encoding"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String LOCATION_HEADER = "Location"; private static final String USER_AGENT_HEADER = "User-Agent"; private static final String UTF8_CHARSET = "UTF-8"; // Default connection and socket timeout of 60 seconds. Tweak to taste. private static final int OPERATION_TIMEOUT = 60 * 1000; private NetworkConnectionImpl() { // No public constructor } /** * Call the webservice using the given parameters to construct the request and return the * result. * * @param context The context to use for this operation. Used to generate the user agent if * needed. * @param url The webservice URL. * @param method The request method to use. * @param parameterMap The parameters to add to the request. * @param headerMap The headers to add to the request. * @param isGzipEnabled Whether the request will use gzip compression if available on the * server. * @param userAgent The user agent to set in the request. If null, a default Android one will be * created. * @param postText The POSTDATA text to add in the request. * @param credentials The credentials to use for authentication. * @param isSslValidationEnabled Whether the request will validate the SSL certificates. * @return The result of the webservice call. */ public static ConnectionResult execute(Context context, String urlValue, Method method, HashMap<String, String> parameterMap, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled) throws ConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(USER_AGENT_HEADER, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterMap != null && !parameterMap.isEmpty()) { for (Entry<String, String> parameter : parameterMap.entrySet()) { paramBuilder.append(URLEncoder.encode(parameter.getKey(), UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(parameter.getValue(), UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (DataDroidLog.canLog(Log.DEBUG)) { DataDroidLog.d(TAG, "Request url: " + urlValue); DataDroidLog.d(TAG, "Method: " + method.toString()); if (parameterMap != null && !parameterMap.isEmpty()) { DataDroidLog.d(TAG, "Parameters:"); for (Entry<String, String> parameter : parameterMap.entrySet()) { String message = "- " + parameter.getKey() + " = " + parameter.getValue(); DataDroidLog.d(TAG, message); } } if (postText != null) { DataDroidLog.d(TAG, "Post body: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { DataDroidLog.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: case PUT: url = new URL(urlValue + "?" + paramBuilder.toString()); connection = (HttpURLConnection) url.openConnection(); break; case POST: url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(CONTENT_TYPE_HEADER, "application/x-www-form-urlencoded"); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(OPERATION_TIMEOUT); // Set the outputStream content for POST requests if (method == Method.POST && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(CONTENT_ENCODING_HEADER); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); DataDroidLog.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { - String error = convertStreamToString(connection.getInputStream(), - isGzip); + String error = convertStreamToString(errorStream, isGzip); throw new ConnectionException(error, responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip); if (DataDroidLog.canLog(Log.VERBOSE)) { DataDroidLog.v(TAG, "Response body: "); int pos = 0; int bodyLength = body.length(); while (pos < bodyLength) { DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200))); pos = pos + 200; } } return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { DataDroidLog.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { DataDroidLog.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { DataDroidLog.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } } private static String createAuthenticationHeader(UsernamePasswordCredentials credentials) { StringBuilder sb = new StringBuilder(); sb.append(credentials.getUserName()).append(":").append(credentials.getPassword()); return "Basic " + Base64.encodeToString(sb.toString().getBytes(), Base64.NO_WRAP); } private static SSLSocketFactory sAllHostsValidSocketFactory; private static SSLSocketFactory getAllHostsValidSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { if (sAllHostsValidSocketFactory == null) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) {} public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); sAllHostsValidSocketFactory = sc.getSocketFactory(); } return sAllHostsValidSocketFactory; } private static HostnameVerifier sAllHostsValidVerifier; private static HostnameVerifier getAllHostsValidVerifier() { if (sAllHostsValidVerifier == null) { sAllHostsValidVerifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; } return sAllHostsValidVerifier; } private static String convertStreamToString(InputStream is, boolean isGzipEnabled) throws IOException { InputStream cleanedIs = is; if (isGzipEnabled) { cleanedIs = new GZIPInputStream(is); } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(cleanedIs, UTF8_CHARSET)); StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null;) { sb.append(line); sb.append("\n"); } return sb.toString(); } finally { if (reader != null) { reader.close(); } cleanedIs.close(); if (isGzipEnabled) { is.close(); } } } }
true
true
public static ConnectionResult execute(Context context, String urlValue, Method method, HashMap<String, String> parameterMap, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled) throws ConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(USER_AGENT_HEADER, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterMap != null && !parameterMap.isEmpty()) { for (Entry<String, String> parameter : parameterMap.entrySet()) { paramBuilder.append(URLEncoder.encode(parameter.getKey(), UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(parameter.getValue(), UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (DataDroidLog.canLog(Log.DEBUG)) { DataDroidLog.d(TAG, "Request url: " + urlValue); DataDroidLog.d(TAG, "Method: " + method.toString()); if (parameterMap != null && !parameterMap.isEmpty()) { DataDroidLog.d(TAG, "Parameters:"); for (Entry<String, String> parameter : parameterMap.entrySet()) { String message = "- " + parameter.getKey() + " = " + parameter.getValue(); DataDroidLog.d(TAG, message); } } if (postText != null) { DataDroidLog.d(TAG, "Post body: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { DataDroidLog.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: case PUT: url = new URL(urlValue + "?" + paramBuilder.toString()); connection = (HttpURLConnection) url.openConnection(); break; case POST: url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(CONTENT_TYPE_HEADER, "application/x-www-form-urlencoded"); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(OPERATION_TIMEOUT); // Set the outputStream content for POST requests if (method == Method.POST && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(CONTENT_ENCODING_HEADER); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); DataDroidLog.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { String error = convertStreamToString(connection.getInputStream(), isGzip); throw new ConnectionException(error, responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip); if (DataDroidLog.canLog(Log.VERBOSE)) { DataDroidLog.v(TAG, "Response body: "); int pos = 0; int bodyLength = body.length(); while (pos < bodyLength) { DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200))); pos = pos + 200; } } return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { DataDroidLog.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { DataDroidLog.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { DataDroidLog.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
public static ConnectionResult execute(Context context, String urlValue, Method method, HashMap<String, String> parameterMap, HashMap<String, String> headerMap, boolean isGzipEnabled, String userAgent, String postText, UsernamePasswordCredentials credentials, boolean isSslValidationEnabled) throws ConnectionException { HttpURLConnection connection = null; try { // Prepare the request information if (userAgent == null) { userAgent = UserAgentUtils.get(context); } if (headerMap == null) { headerMap = new HashMap<String, String>(); } headerMap.put(USER_AGENT_HEADER, userAgent); if (isGzipEnabled) { headerMap.put(ACCEPT_ENCODING_HEADER, "gzip"); } headerMap.put(ACCEPT_CHARSET_HEADER, UTF8_CHARSET); if (credentials != null) { headerMap.put(AUTHORIZATION_HEADER, createAuthenticationHeader(credentials)); } StringBuilder paramBuilder = new StringBuilder(); if (parameterMap != null && !parameterMap.isEmpty()) { for (Entry<String, String> parameter : parameterMap.entrySet()) { paramBuilder.append(URLEncoder.encode(parameter.getKey(), UTF8_CHARSET)); paramBuilder.append("="); paramBuilder.append(URLEncoder.encode(parameter.getValue(), UTF8_CHARSET)); paramBuilder.append("&"); } } // Log the request if (DataDroidLog.canLog(Log.DEBUG)) { DataDroidLog.d(TAG, "Request url: " + urlValue); DataDroidLog.d(TAG, "Method: " + method.toString()); if (parameterMap != null && !parameterMap.isEmpty()) { DataDroidLog.d(TAG, "Parameters:"); for (Entry<String, String> parameter : parameterMap.entrySet()) { String message = "- " + parameter.getKey() + " = " + parameter.getValue(); DataDroidLog.d(TAG, message); } } if (postText != null) { DataDroidLog.d(TAG, "Post body: " + postText); } if (headerMap != null && !headerMap.isEmpty()) { DataDroidLog.d(TAG, "Headers:"); for (Entry<String, String> header : headerMap.entrySet()) { DataDroidLog.d(TAG, "- " + header.getKey() + " = " + header.getValue()); } } } // Create the connection object URL url = null; String outputText = null; switch (method) { case GET: case DELETE: case PUT: url = new URL(urlValue + "?" + paramBuilder.toString()); connection = (HttpURLConnection) url.openConnection(); break; case POST: url = new URL(urlValue); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); if (paramBuilder.length() > 0) { outputText = paramBuilder.toString(); headerMap.put(CONTENT_TYPE_HEADER, "application/x-www-form-urlencoded"); } else if (postText != null) { outputText = postText; } break; } // Set the request method connection.setRequestMethod(method.toString()); // If it's an HTTPS request and the SSL Validation is disabled if (url.getProtocol().equals("https") && !isSslValidationEnabled) { HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; httpsConnection.setSSLSocketFactory(getAllHostsValidSocketFactory()); httpsConnection.setHostnameVerifier(getAllHostsValidVerifier()); } // Add the headers if (!headerMap.isEmpty()) { for (Entry<String, String> header : headerMap.entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } } // Set the connection and read timeout connection.setConnectTimeout(OPERATION_TIMEOUT); connection.setReadTimeout(OPERATION_TIMEOUT); // Set the outputStream content for POST requests if (method == Method.POST && outputText != null) { OutputStream output = null; try { output = connection.getOutputStream(); output.write(outputText.getBytes()); } finally { if (output != null) { try { output.close(); } catch (IOException e) { // Already catching the first IOException so nothing to do here. } } } } String contentEncoding = connection.getHeaderField(CONTENT_ENCODING_HEADER); int responseCode = connection.getResponseCode(); boolean isGzip = contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip"); DataDroidLog.d(TAG, "Response code: " + responseCode); if (responseCode == HttpStatus.SC_MOVED_PERMANENTLY) { String redirectionUrl = connection.getHeaderField(LOCATION_HEADER); throw new ConnectionException("New location : " + redirectionUrl, redirectionUrl); } InputStream errorStream = connection.getErrorStream(); if (errorStream != null) { String error = convertStreamToString(errorStream, isGzip); throw new ConnectionException(error, responseCode); } String body = convertStreamToString(connection.getInputStream(), isGzip); if (DataDroidLog.canLog(Log.VERBOSE)) { DataDroidLog.v(TAG, "Response body: "); int pos = 0; int bodyLength = body.length(); while (pos < bodyLength) { DataDroidLog.v(TAG, body.substring(pos, Math.min(bodyLength - 1, pos + 200))); pos = pos + 200; } } return new ConnectionResult(connection.getHeaderFields(), body); } catch (IOException e) { DataDroidLog.e(TAG, "IOException", e); throw new ConnectionException(e); } catch (KeyManagementException e) { DataDroidLog.e(TAG, "KeyManagementException", e); throw new ConnectionException(e); } catch (NoSuchAlgorithmException e) { DataDroidLog.e(TAG, "NoSuchAlgorithmException", e); throw new ConnectionException(e); } finally { if (connection != null) { connection.disconnect(); } } }
diff --git a/modules/org.restlet/src/org/restlet/data/Conditions.java b/modules/org.restlet/src/org/restlet/data/Conditions.java index b09b323b9..6951c8510 100644 --- a/modules/org.restlet/src/org/restlet/data/Conditions.java +++ b/modules/org.restlet/src/org/restlet/data/Conditions.java @@ -1,255 +1,259 @@ /* * Copyright 2005-2007 Noelios Consulting. * * The contents of this file are subject to the terms of the Common Development * and Distribution License (the "License"). You may not use this file except in * compliance with the License. * * You can obtain a copy of the license at * http://www.opensource.org/licenses/cddl1.txt See the License for the specific * language governing permissions and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each file and * include the License file at http://www.opensource.org/licenses/cddl1.txt If * applicable, add the following below this CDDL HEADER, with the fields * enclosed by brackets "[]" replaced with your own identifying information: * Portions Copyright [yyyy] [name of copyright owner] */ package org.restlet.data; import java.util.Date; import java.util.Iterator; import java.util.List; import org.restlet.resource.Variant; import org.restlet.util.DateUtils; /** * Set of conditions applying to a request. This is equivalent to the HTTP * conditional headers. * * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24">If-Match</a> * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25">If-Modified-Since</a> * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26">If-None-Match</a> * @see <a * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.28">If-Unmodified-Since</a> * * @author Jerome Louvel ([email protected]) */ public final class Conditions { /** The "if-modified-since" condition */ private Date modifiedSince; /** The "if-unmodified-since" condition */ private Date unmodifiedSince; /** The "if-match" condition */ private List<Tag> match; /** The "if-none-match" condition */ private List<Tag> noneMatch; /** * Constructor. */ public Conditions() { } /** * Returns the "if-match" condition. * * @return The "if-match" condition. */ public List<Tag> getMatch() { return this.match; } /** * Returns the "if-modified-since" condition. * * @return The "if-modified-since" condition. */ public Date getModifiedSince() { return this.modifiedSince; } /** * Returns the "if-none-match" condition. * * @return The "if-none-match" condition. */ public List<Tag> getNoneMatch() { return this.noneMatch; } /** * Returns the conditional status of a variant using a given method. * * @param method * The request method. * @param variant * The representation whose entity tag or date of modification * will be tested * @return Null if the requested method can be performed, the status of the * response otherwise. */ public Status getStatus(Method method, Variant variant) { Status result = null; // Is the "if-Match" rule followed or not? if (getMatch() != null && getMatch().size() != 0) { boolean matched = false; boolean failed = false; if (variant != null) { // If a tag exists if (variant.getTag() != null) { // Check if it matches one of the representations already // cached by the client Tag tag; for (Iterator<Tag> iter = getMatch().iterator(); !matched && iter.hasNext();) { tag = iter.next(); matched = tag.equals(variant.getTag(), false); } } } else { // see // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 // If none of the entity tags match, or if "*" is given and no // current entity exists, the server MUST NOT perform the // requested method failed = getMatch().get(0).equals(Tag.ALL); } failed = failed || !matched; if (failed) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } // Is the "if-None-Match" rule followed or not? if (result == null && getNoneMatch() != null && getNoneMatch().size() != 0) { boolean matched = false; if (variant != null) { // If a tag exists if (variant.getTag() != null) { // Check if it matches one of the representations // already cached by the client Tag tag; for (Iterator<Tag> iter = getNoneMatch().iterator(); !matched && iter.hasNext();) { tag = iter.next(); matched = tag.equals(variant.getTag(), (Method.GET .equals(method) || Method.HEAD.equals(method))); } if (!matched) { Date modifiedSince = getModifiedSince(); matched = ((modifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(modifiedSince, variant .getModificationDate())); } } } else { matched = getNoneMatch().get(0).equals(Tag.ALL); } if (matched) { if (Method.GET.equals(method) || Method.HEAD.equals(method)) { result = Status.REDIRECTION_NOT_MODIFIED; } else { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } } // Is the "if-Modified-Since" rule followed or not? if (result == null && getModifiedSince() != null) { - Date modifiedSince = getModifiedSince(); - boolean isModifiedSince = ((modifiedSince == null) - || (variant.getModificationDate() == null) || DateUtils - .after(modifiedSince, variant.getModificationDate())); - if (!isModifiedSince) { - result = Status.REDIRECTION_NOT_MODIFIED; + if (variant != null) { + Date modifiedSince = getModifiedSince(); + boolean isModifiedSince = ((modifiedSince == null) + || (variant.getModificationDate() == null) || DateUtils + .after(modifiedSince, variant.getModificationDate())); + if (!isModifiedSince) { + result = Status.REDIRECTION_NOT_MODIFIED; + } } } // Is the "if-Unmodified-Since" rule followed or not? if (result == null && getUnmodifiedSince() != null) { - Date unModifiedSince = getUnmodifiedSince(); - boolean isUnModifiedSince = ((unModifiedSince == null) - || (variant.getModificationDate() == null) || DateUtils - .after(variant.getModificationDate(), unModifiedSince)); - if (!isUnModifiedSince) { - result = Status.CLIENT_ERROR_PRECONDITION_FAILED; + if (variant != null) { + Date unModifiedSince = getUnmodifiedSince(); + boolean isUnModifiedSince = ((unModifiedSince == null) + || (variant.getModificationDate() == null) || DateUtils + .after(variant.getModificationDate(), unModifiedSince)); + if (!isUnModifiedSince) { + result = Status.CLIENT_ERROR_PRECONDITION_FAILED; + } } } return result; } /** * Returns the "if-unmodified-since" condition. * * @return The "if-unmodified-since" condition. */ public Date getUnmodifiedSince() { return this.unmodifiedSince; } /** * Indicates if there are some conditions set. * * @return True if there are some conditions set. */ public boolean hasSome() { return ((getMatch() != null && !getMatch().isEmpty()) || (getNoneMatch() != null && !getNoneMatch().isEmpty()) || (getModifiedSince() != null) || (getUnmodifiedSince() != null)); } /** * Sets the "if-match" condition. * * @param tags * The "if-match" condition. */ public void setMatch(List<Tag> tags) { this.match = tags; } /** * Sets the "if-modified-since" condition. * * @param date * The "if-modified-since" condition. */ public void setModifiedSince(Date date) { this.modifiedSince = DateUtils.unmodifiable(date); } /** * Sets the "if-none-match" condition. * * @param tags * The "if-none-match" condition. */ public void setNoneMatch(List<Tag> tags) { this.noneMatch = tags; } /** * Sets the "if-unmodified-since" condition. * * @param date * The "if-unmodified-since" condition. */ public void setUnmodifiedSince(Date date) { this.unmodifiedSince = DateUtils.unmodifiable(date); } }
false
true
public Status getStatus(Method method, Variant variant) { Status result = null; // Is the "if-Match" rule followed or not? if (getMatch() != null && getMatch().size() != 0) { boolean matched = false; boolean failed = false; if (variant != null) { // If a tag exists if (variant.getTag() != null) { // Check if it matches one of the representations already // cached by the client Tag tag; for (Iterator<Tag> iter = getMatch().iterator(); !matched && iter.hasNext();) { tag = iter.next(); matched = tag.equals(variant.getTag(), false); } } } else { // see // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 // If none of the entity tags match, or if "*" is given and no // current entity exists, the server MUST NOT perform the // requested method failed = getMatch().get(0).equals(Tag.ALL); } failed = failed || !matched; if (failed) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } // Is the "if-None-Match" rule followed or not? if (result == null && getNoneMatch() != null && getNoneMatch().size() != 0) { boolean matched = false; if (variant != null) { // If a tag exists if (variant.getTag() != null) { // Check if it matches one of the representations // already cached by the client Tag tag; for (Iterator<Tag> iter = getNoneMatch().iterator(); !matched && iter.hasNext();) { tag = iter.next(); matched = tag.equals(variant.getTag(), (Method.GET .equals(method) || Method.HEAD.equals(method))); } if (!matched) { Date modifiedSince = getModifiedSince(); matched = ((modifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(modifiedSince, variant .getModificationDate())); } } } else { matched = getNoneMatch().get(0).equals(Tag.ALL); } if (matched) { if (Method.GET.equals(method) || Method.HEAD.equals(method)) { result = Status.REDIRECTION_NOT_MODIFIED; } else { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } } // Is the "if-Modified-Since" rule followed or not? if (result == null && getModifiedSince() != null) { Date modifiedSince = getModifiedSince(); boolean isModifiedSince = ((modifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(modifiedSince, variant.getModificationDate())); if (!isModifiedSince) { result = Status.REDIRECTION_NOT_MODIFIED; } } // Is the "if-Unmodified-Since" rule followed or not? if (result == null && getUnmodifiedSince() != null) { Date unModifiedSince = getUnmodifiedSince(); boolean isUnModifiedSince = ((unModifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(variant.getModificationDate(), unModifiedSince)); if (!isUnModifiedSince) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } return result; }
public Status getStatus(Method method, Variant variant) { Status result = null; // Is the "if-Match" rule followed or not? if (getMatch() != null && getMatch().size() != 0) { boolean matched = false; boolean failed = false; if (variant != null) { // If a tag exists if (variant.getTag() != null) { // Check if it matches one of the representations already // cached by the client Tag tag; for (Iterator<Tag> iter = getMatch().iterator(); !matched && iter.hasNext();) { tag = iter.next(); matched = tag.equals(variant.getTag(), false); } } } else { // see // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.24 // If none of the entity tags match, or if "*" is given and no // current entity exists, the server MUST NOT perform the // requested method failed = getMatch().get(0).equals(Tag.ALL); } failed = failed || !matched; if (failed) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } // Is the "if-None-Match" rule followed or not? if (result == null && getNoneMatch() != null && getNoneMatch().size() != 0) { boolean matched = false; if (variant != null) { // If a tag exists if (variant.getTag() != null) { // Check if it matches one of the representations // already cached by the client Tag tag; for (Iterator<Tag> iter = getNoneMatch().iterator(); !matched && iter.hasNext();) { tag = iter.next(); matched = tag.equals(variant.getTag(), (Method.GET .equals(method) || Method.HEAD.equals(method))); } if (!matched) { Date modifiedSince = getModifiedSince(); matched = ((modifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(modifiedSince, variant .getModificationDate())); } } } else { matched = getNoneMatch().get(0).equals(Tag.ALL); } if (matched) { if (Method.GET.equals(method) || Method.HEAD.equals(method)) { result = Status.REDIRECTION_NOT_MODIFIED; } else { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } } // Is the "if-Modified-Since" rule followed or not? if (result == null && getModifiedSince() != null) { if (variant != null) { Date modifiedSince = getModifiedSince(); boolean isModifiedSince = ((modifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(modifiedSince, variant.getModificationDate())); if (!isModifiedSince) { result = Status.REDIRECTION_NOT_MODIFIED; } } } // Is the "if-Unmodified-Since" rule followed or not? if (result == null && getUnmodifiedSince() != null) { if (variant != null) { Date unModifiedSince = getUnmodifiedSince(); boolean isUnModifiedSince = ((unModifiedSince == null) || (variant.getModificationDate() == null) || DateUtils .after(variant.getModificationDate(), unModifiedSince)); if (!isUnModifiedSince) { result = Status.CLIENT_ERROR_PRECONDITION_FAILED; } } } return result; }
diff --git a/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java b/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java index 2bd5f0faf..b9f3dcee8 100644 --- a/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java +++ b/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/backup/AbstractBackupUseCasesTest.java @@ -1,1348 +1,1348 @@ /* * Copyright (C) 2003-2010 eXo Platform SAS. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.services.jcr.ext.backup; import org.apache.commons.collections.map.HashedMap; import org.exoplatform.commons.utils.PrivilegedFileHelper; import org.exoplatform.commons.utils.PrivilegedSystemHelper; import org.exoplatform.services.jcr.config.RepositoryEntry; import org.exoplatform.services.jcr.config.WorkspaceEntry; import org.exoplatform.services.jcr.core.ManageableRepository; import org.exoplatform.services.jcr.ext.backup.impl.JobRepositoryRestore; import org.exoplatform.services.jcr.ext.backup.impl.JobWorkspaceRestore; import org.exoplatform.services.jcr.impl.Constants; import org.exoplatform.services.jcr.util.IdGenerator; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; /** * Created by The eXo Platform SAS. * * <br/>Date: 2010 * * @author <a href="mailto:[email protected]">Alex Reshetnyak</a> * @version $Id$ */ public abstract class AbstractBackupUseCasesTest extends AbstractBackupTestCase { public void testFullBackupRestore() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore WorkspaceEntry newWS = helper.createWorkspaceEntry(true, null); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, config.getRepository(), newWS, false); checkConent(repository, newWS.getName()); } public void testIncrementalBackupRestore() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); addIncrementalConent(repository, wsEntry.getName()); backup.stopBackup(bch); // restore WorkspaceEntry newWS = helper.createWorkspaceEntry(true, null); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, config.getRepository(), newWS, false); checkConent(repository, newWS.getName()); checkIncrementalConent(repository, newWS.getName()); } public void testFullBackupRestoreAsync() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore WorkspaceEntry newWS = helper.createWorkspaceEntry(true, null); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, config.getRepository(), newWS, true); waitEndOfRestore(config.getRepository(), newWS.getName()); assertEquals(backup.getLastRestore(config.getRepository(), newWS.getName()).getStateRestore(), JobWorkspaceRestore.RESTORE_SUCCESSFUL); checkConent(repository, newWS.getName()); } public void testAutoStopBackupFull() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); Thread.sleep(30000); try { assertEquals(backup.getCurrentBackups().size(), 0); } finally { backup.stopBackup(bch); } } public void testAutoStopBackupIncr() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setIncrementalJobPeriod(3); config.setIncrementalJobNumber(0); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); Thread.sleep(10000); try { assertEquals(backup.getCurrentBackups().size(), 1); } finally { backup.stopBackup(bch); } } public void _testAutoStopBackupIncrRepetion() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setIncrementalJobPeriod(4); config.setIncrementalJobNumber(2); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); Thread.sleep(60000); try { assertEquals(backup.getCurrentBackups().size(), 0); } finally { backup.stopBackup(bch); } } public void testNegativeIncremetalJobPeriod() throws Exception { // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository("fake"); config.setWorkspace("fake"); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setIncrementalJobPeriod(-1000); config.setBackupDir(backDir); try { backup.startBackup(config); fail("The backup can not be started."); } catch (BackupConfigurationException e) { } } public void testNegativeIncremetalJobNumber() throws Exception { // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository("fake"); config.setWorkspace("fake"); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setIncrementalJobNumber(-5); config.setBackupDir(backDir); try { backup.startBackup(config); fail("The backup can not be started."); } catch (BackupConfigurationException e) { } } public void testRestoreAfterFailureRestore() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore WorkspaceEntry newWS = helper.createWorkspaceEntry(true, "NOT_EXISTED_DS"); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); try { backup.restore(bchLog, config.getRepository(), newWS, false); fail("Exception should be thrown"); } catch (Exception e) { } newWS = helper.createWorkspaceEntry(true, null); backup.restore(bchLog, config.getRepository(), newWS, false); checkConent(repository, newWS.getName()); } public void testRepositoryFullBackupRestore() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, repository.getConfiguration().getSystemWorkspaceName(), null); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, newRE, false); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testRepositoryFullAndIncrementalBackupRestore() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); addIncrementalConent(repository, repository.getConfiguration().getSystemWorkspaceName()); backup.stopBackup(bch); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, repository.getConfiguration().getSystemWorkspaceName(), null); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, newRE, false); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); checkIncrementalConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testRepositoryFullBackupAsynchronusRestore() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, repository.getConfiguration().getSystemWorkspaceName(), null); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, newRE, true); waitEndOfRestore(newRE.getName()); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testRepositoryFullBackupAsynchronusRestoreWorkspaceMapping() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, null, null); // create workspace mappingS Map<String, String> workspaceMapping = new HashedMap(); workspaceMapping.put(repository.getConfiguration().getSystemWorkspaceName(), newRE.getSystemWorkspaceName()); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, newRE, workspaceMapping, true); waitEndOfRestore(newRE.getName()); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void _testAutoStopRepositoryBackupIncrRepetion() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_AND_INCREMENTAL); config.setIncrementalJobPeriod(4); config.setIncrementalJobNumber(2); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, null, null); // create workspace mappingS Map<String, String> workspaceMapping = new HashedMap(); workspaceMapping.put(repository.getConfiguration().getSystemWorkspaceName(), newRE.getSystemWorkspaceName()); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, newRE, workspaceMapping, true); waitEndOfRestore(newRE.getName()); Thread.sleep(60000); assertEquals(backup.getCurrentRepositoryBackups().size(), 0); } public void testRepositoryRestoreFail() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, null, null); newRE.getWorkspaceEntries().get(0).getQueryHandler().setType("gg"); // create workspace mappingS Map<String, String> workspaceMapping = new HashedMap(); workspaceMapping.put(repository.getConfiguration().getSystemWorkspaceName(), newRE.getSystemWorkspaceName()); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); try { backup.restore(bchLog, newRE, workspaceMapping, false); fail("Exception should be thrown"); } catch (RepositoryRestoreExeption e) { } } public void testExistedWorkspaceRestoreMultiDB() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreExistingWorkspace(bchLog, repository.getConfiguration().getName(), repository.getConfiguration() .getWorkspaceEntries().get(1), false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testExistedWorkspaceRestoreSingleDB() throws Exception { // prepare String dsName = helper.createDatasource(); ManageableRepository repository = helper.createRepository(container, false, dsName); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(false, dsName); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreExistingWorkspace(bchLog, repository.getConfiguration().getName(), repository.getConfiguration() .getWorkspaceEntries().get(1), false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testExistedWorkspaceRestoreAsync() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreExistingWorkspace(bchLog, repository.getConfiguration().getName(), repository.getConfiguration() .getWorkspaceEntries().get(1), true); waitEndOfRestore(repository.getConfiguration().getName(), repository.getConfiguration().getWorkspaceEntries() .get(1).getName()); assertEquals( backup.getLastRestore(repository.getConfiguration().getName(), repository.getConfiguration().getWorkspaceEntries().get(1).getName()).getStateRestore(), JobWorkspaceRestore.RESTORE_SUCCESSFUL); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testExistedRepositoryRestoreMultiDB() throws Exception { // prepare String dsName = helper.createDatasource(); ManageableRepository repository = helper.createRepository(container, true, dsName); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, repository.getConfiguration().getSystemWorkspaceName(), dsName); newRE.setName(repository.getConfiguration().getName()); backup.restoreExistingRepository(bchLog, newRE, false); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testExistedRepositoryRestoreSingelDB() throws Exception { // prepare String dsName = helper.createDatasource(); ManageableRepository repository = helper.createRepository(container, false, dsName); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); // restore RepositoryEntry newRE = helper.createRepositoryEntry(false, repository.getConfiguration().getSystemWorkspaceName(), dsName); newRE.setName(repository.getConfiguration().getName()); backup.restoreExistingRepository(bchLog, newRE, false); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testExistedRepositoryRestoreAsync() throws Exception { // prepare String dsName = helper.createDatasource(); ManageableRepository repository = helper.createRepository(container, false, dsName); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); // restore RepositoryEntry newRE = helper.createRepositoryEntry(false, repository.getConfiguration().getSystemWorkspaceName(), dsName); newRE.setName(repository.getConfiguration().getName()); backup.restoreExistingRepository(bchLog, newRE, true); waitEndOfRestore(repository.getConfiguration().getName()); assertEquals(JobRepositoryRestore.REPOSITORY_RESTORE_SUCCESSFUL, backup.getLastRepositoryRestore(repository.getConfiguration().getName()).getStateRestore()); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testExistedWorkspaceRestoreWithConfig() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreExistingWorkspace(bchLog.getBackupId(), false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testExistedRepositoryRestoreWithConfig() throws Exception { // prepare String dsName = helper.createDatasource(); ManageableRepository repository = helper.createRepository(container, true, dsName); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); // restore RepositoryEntry newRE = helper.createRepositoryEntry(true, repository.getConfiguration().getSystemWorkspaceName(), dsName); newRE.setName(repository.getConfiguration().getName()); backup.restoreExistingRepository(bchLog.getBackupId(), false); checkConent(repositoryService.getRepository(newRE.getName()), newRE.getSystemWorkspaceName()); } public void testWorkspaceRestoreWithConfig() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); removeWorkspaceFully(repository.getConfiguration().getName(), wsEntry.getName()); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreWorkspace(bchLog.getBackupId(), false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testRepositoryRestoreWithConfig() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore removeRepositoryFully(repository.getConfiguration().getName()); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreRepository(bchLog.getBackupId(), false); checkConent(repositoryService.getRepository(config.getRepository()), repositoryService.getRepository(config.getRepository()).getConfiguration().getSystemWorkspaceName()); } public void testRepositoryRestoreWithNullConfig() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore removeRepositoryFully(repository.getConfiguration().getName()); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restore(bchLog, null, false); checkConent(repositoryService.getRepository(config.getRepository()), repositoryService.getRepository(config.getRepository()).getConfiguration().getSystemWorkspaceName()); } public void testWorkspaceRestoreWithNullConfig() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); removeWorkspaceFully(repository.getConfiguration().getName(), wsEntry.getName()); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); try { backup.restore(bchLog, repository.getConfiguration().getName() + "not_exists", null, false); fail("Exception should be thrown"); } catch (Exception e) { } backup.restore(bchLog, repository.getConfiguration().getName(), null, false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testExistedWorkspaceRestoreWithConfigBackupSetDir() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreExistingWorkspace(bchLog.getBackupConfig().getBackupDir(), false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testExistedRepositoryRestoreWithConfigBackupSetDir() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreExistingRepository(bchLog.getBackupConfig().getBackupDir(), false); checkConent(repositoryService.getRepository(config.getRepository()), repositoryService.getRepository(config.getRepository()).getConfiguration().getSystemWorkspaceName()); } public void testWorkspaceRestoreWithConfigBackupSetDir() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); WorkspaceEntry wsEntry = helper.createWorkspaceEntry(true, null); helper.addWorkspace(repository, wsEntry); addConent(repository, wsEntry.getName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); BackupConfig config = new BackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setWorkspace(wsEntry.getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); BackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); removeWorkspaceFully(repository.getConfiguration().getName(), wsEntry.getName()); // restore File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); BackupChainLog bchLog = new BackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreWorkspace(bchLog.getBackupConfig().getBackupDir(), false); checkConent(repository, repository.getConfiguration().getWorkspaceEntries().get(1).getName()); } public void testRepositoryRestoreWithConfigBackupSetDir() throws Exception { // prepare ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target/backup/" + IdGenerator.generate()); backDir.mkdirs(); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // restore removeRepositoryFully(repository.getConfiguration().getName()); File backLog = new File(bch.getLogFilePath()); assertTrue(backLog.exists()); RepositoryBackupChainLog bchLog = new RepositoryBackupChainLog(backLog); assertNotNull(bchLog.getStartedTime()); assertNotNull(bchLog.getFinishedTime()); backup.restoreRepository(bchLog.getBackupConfig().getBackupDir(), false); checkConent(repositoryService.getRepository(config.getRepository()), repositoryService.getRepository(config.getRepository()).getConfiguration().getSystemWorkspaceName()); } public void testEnvironmentVariablesToBackupDir() throws Exception { // prepare stage #1 ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); String tempDir = PrivilegedSystemHelper.getProperty("java.io.tmpdir"); // backup File backDir = new File(tempDir); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // prepare stage #2 String repositoryBackupChainLogPath = bch.getLogFilePath(); String backupDitEnv = backDir.getCanonicalPath(); String newBackupDir = "\\${java.io.tmpdir}" + bch.getBackupConfig().getBackupDir().getCanonicalPath() - .replaceAll(backupDitEnv, ""); + .replace(backupDitEnv, ""); File dest = new File(repositoryBackupChainLogPath + ".xml"); dest.createNewFile(); RepositoryBackupChainLog newRepositoryBackupChainLog = null; try { String sConfig = setNewBackupDirInRepositoryBackupChainLog(new File(repositoryBackupChainLogPath), dest, newBackupDir); assertTrue(sConfig.contains(newBackupDir.subSequence(1, newBackupDir.length()))); // check newRepositoryBackupChainLog = new RepositoryBackupChainLog(dest); assertEquals(bch.getBackupConfig().getBackupDir().getCanonicalPath(), newRepositoryBackupChainLog.getBackupConfig().getBackupDir().getCanonicalPath()); } finally { newRepositoryBackupChainLog = null; dest.delete(); deleteFolder(bch.getBackupConfig().getBackupDir()); } } public void testRelativeBackupDir() throws Exception { // prepare stage #1 ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); // backup File backDir = new File("target"); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // prepare stage #2 String repositoryBackupChainLogPath = bch.getLogFilePath(); String relativePrefixBackupDir = backDir.getCanonicalFile().getParent() + File.separator; String newBackupDir = bch.getBackupConfig().getBackupDir().getCanonicalPath().replaceAll(relativePrefixBackupDir, ""); File dest = new File(repositoryBackupChainLogPath + ".xml"); dest.createNewFile(); RepositoryBackupChainLog newRepositoryBackupChainLog = null; String sConfig = setNewBackupDirInRepositoryBackupChainLog(new File(repositoryBackupChainLogPath), dest, newBackupDir); assertTrue(sConfig.contains(newBackupDir)); // check newRepositoryBackupChainLog = new RepositoryBackupChainLog(dest); assertEquals(bch.getBackupConfig().getBackupDir().getCanonicalPath(), newRepositoryBackupChainLog .getBackupConfig().getBackupDir().getCanonicalPath()); } /** * Set new backup directory in RepositoryBackupChainLog * * @param src * source file of RepositoryBackupChainLog * @param dest * destination file of RepositoryBackupChainLog * @param newBackupDir * @return String * the content of file destination * @throws IOException */ protected String setNewBackupDirInRepositoryBackupChainLog(File src, File dest, String newBackupDir) throws IOException { InputStream in = PrivilegedFileHelper.fileInputStream(src); OutputStream out = PrivilegedFileHelper.fileOutputStream(dest); byte[] buf = new byte[(int) (PrivilegedFileHelper.length(src))]; in.read(buf); String sConfig = new String(buf, Constants.DEFAULT_ENCODING); sConfig = sConfig.replaceAll("<backup-dir>.+</backup-dir>", "<backup-dir>" + newBackupDir + "</backup-dir>"); out.write(sConfig.getBytes(Constants.DEFAULT_ENCODING)); in.close(); out.close(); return sConfig; } protected void deleteFolder(File f) { if (f.isDirectory()) { for (File file : f.listFiles()) { deleteFolder(file); } f.delete(); } else { f.delete(); } } }
true
true
public void testEnvironmentVariablesToBackupDir() throws Exception { // prepare stage #1 ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); String tempDir = PrivilegedSystemHelper.getProperty("java.io.tmpdir"); // backup File backDir = new File(tempDir); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // prepare stage #2 String repositoryBackupChainLogPath = bch.getLogFilePath(); String backupDitEnv = backDir.getCanonicalPath(); String newBackupDir = "\\${java.io.tmpdir}" + bch.getBackupConfig().getBackupDir().getCanonicalPath() .replaceAll(backupDitEnv, ""); File dest = new File(repositoryBackupChainLogPath + ".xml"); dest.createNewFile(); RepositoryBackupChainLog newRepositoryBackupChainLog = null; try { String sConfig = setNewBackupDirInRepositoryBackupChainLog(new File(repositoryBackupChainLogPath), dest, newBackupDir); assertTrue(sConfig.contains(newBackupDir.subSequence(1, newBackupDir.length()))); // check newRepositoryBackupChainLog = new RepositoryBackupChainLog(dest); assertEquals(bch.getBackupConfig().getBackupDir().getCanonicalPath(), newRepositoryBackupChainLog.getBackupConfig().getBackupDir().getCanonicalPath()); } finally { newRepositoryBackupChainLog = null; dest.delete(); deleteFolder(bch.getBackupConfig().getBackupDir()); } }
public void testEnvironmentVariablesToBackupDir() throws Exception { // prepare stage #1 ManageableRepository repository = helper.createRepository(container, true, null); addConent(repository, repository.getConfiguration().getSystemWorkspaceName()); String tempDir = PrivilegedSystemHelper.getProperty("java.io.tmpdir"); // backup File backDir = new File(tempDir); RepositoryBackupConfig config = new RepositoryBackupConfig(); config.setRepository(repository.getConfiguration().getName()); config.setBackupType(BackupManager.FULL_BACKUP_ONLY); config.setBackupDir(backDir); RepositoryBackupChain bch = backup.startBackup(config); waitEndOfBackup(bch); backup.stopBackup(bch); // prepare stage #2 String repositoryBackupChainLogPath = bch.getLogFilePath(); String backupDitEnv = backDir.getCanonicalPath(); String newBackupDir = "\\${java.io.tmpdir}" + bch.getBackupConfig().getBackupDir().getCanonicalPath() .replace(backupDitEnv, ""); File dest = new File(repositoryBackupChainLogPath + ".xml"); dest.createNewFile(); RepositoryBackupChainLog newRepositoryBackupChainLog = null; try { String sConfig = setNewBackupDirInRepositoryBackupChainLog(new File(repositoryBackupChainLogPath), dest, newBackupDir); assertTrue(sConfig.contains(newBackupDir.subSequence(1, newBackupDir.length()))); // check newRepositoryBackupChainLog = new RepositoryBackupChainLog(dest); assertEquals(bch.getBackupConfig().getBackupDir().getCanonicalPath(), newRepositoryBackupChainLog.getBackupConfig().getBackupDir().getCanonicalPath()); } finally { newRepositoryBackupChainLog = null; dest.delete(); deleteFolder(bch.getBackupConfig().getBackupDir()); } }
diff --git a/src/com/suxsem/liquidnextparts/activities/Webview.java b/src/com/suxsem/liquidnextparts/activities/Webview.java index ff557ad..11b8651 100644 --- a/src/com/suxsem/liquidnextparts/activities/Webview.java +++ b/src/com/suxsem/liquidnextparts/activities/Webview.java @@ -1,125 +1,130 @@ package com.suxsem.liquidnextparts.activities; import java.util.Timer; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.os.Bundle; import android.os.CountDownTimer; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import android.widget.Toast; import com.suxsem.liquidnextparts.R; import com.suxsem.liquidnextparts.components.NotificationHelper; public class Webview extends Activity { Context myactivity = null; Webview webviewclass = this; Timer timer; WebView mWebView; boolean firstloading = false; TextView waittextview; ProgressDialog waitdialog; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webviewlayout); waitdialog = ProgressDialog.show(this, "", "Processing click...", true); waittextview = (TextView) findViewById(R.id.textView1); waittextview.setText("Loading ADS..."); final CountDownTimer timer2 = new CountDownTimer(6000, 6000) { @Override public void onFinish() { // TODO Auto-generated method stub Toast.makeText(myactivity, "Thanks", 4000).show(); this.cancel(); - waitdialog.dismiss(); + try { + waitdialog.dismiss(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } NotificationHelper.adsfinish = true; if(NotificationHelper.waitflash){ NotificationHelper.flashrom(); } webviewclass.finish(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }; final CountDownTimer timer1 = new CountDownTimer(20000, 1000) { @Override public void onFinish() { // TODO Auto-generated method stub waittextview.setText("Storing click..."); mWebView.loadUrl("javascript:skipButton()"); timer2.start(); this.cancel(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub waittextview.setText(Long.toString(millisUntilFinished/1000)+" seconds..."); } }; final CountDownTimer timer_timeout = new CountDownTimer(40000, 40000) { @Override public void onFinish() { Toast.makeText(myactivity, "Network error", 4000).show(); webviewclass.finish(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }; myactivity = this.getBaseContext(); mWebView = (WebView) findViewById(R.id.webView1); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); mWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { //timer = new Timer(); //timer.schedule(new UpdateTimeTask(), 0, 1000); runOnUiThread(new Runnable() { public void run() { if(!firstloading){ try { timer_timeout.cancel(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } timer1.start(); firstloading = true; } } }); } }); mWebView.loadUrl(getString(R.string.adsurl)); // mWebView.loadUrl("http://www.google.it"); timer_timeout.start(); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webviewlayout); waitdialog = ProgressDialog.show(this, "", "Processing click...", true); waittextview = (TextView) findViewById(R.id.textView1); waittextview.setText("Loading ADS..."); final CountDownTimer timer2 = new CountDownTimer(6000, 6000) { @Override public void onFinish() { // TODO Auto-generated method stub Toast.makeText(myactivity, "Thanks", 4000).show(); this.cancel(); waitdialog.dismiss(); NotificationHelper.adsfinish = true; if(NotificationHelper.waitflash){ NotificationHelper.flashrom(); } webviewclass.finish(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }; final CountDownTimer timer1 = new CountDownTimer(20000, 1000) { @Override public void onFinish() { // TODO Auto-generated method stub waittextview.setText("Storing click..."); mWebView.loadUrl("javascript:skipButton()"); timer2.start(); this.cancel(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub waittextview.setText(Long.toString(millisUntilFinished/1000)+" seconds..."); } }; final CountDownTimer timer_timeout = new CountDownTimer(40000, 40000) { @Override public void onFinish() { Toast.makeText(myactivity, "Network error", 4000).show(); webviewclass.finish(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }; myactivity = this.getBaseContext(); mWebView = (WebView) findViewById(R.id.webView1); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); mWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { //timer = new Timer(); //timer.schedule(new UpdateTimeTask(), 0, 1000); runOnUiThread(new Runnable() { public void run() { if(!firstloading){ try { timer_timeout.cancel(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } timer1.start(); firstloading = true; } } }); } }); mWebView.loadUrl(getString(R.string.adsurl)); // mWebView.loadUrl("http://www.google.it"); timer_timeout.start(); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webviewlayout); waitdialog = ProgressDialog.show(this, "", "Processing click...", true); waittextview = (TextView) findViewById(R.id.textView1); waittextview.setText("Loading ADS..."); final CountDownTimer timer2 = new CountDownTimer(6000, 6000) { @Override public void onFinish() { // TODO Auto-generated method stub Toast.makeText(myactivity, "Thanks", 4000).show(); this.cancel(); try { waitdialog.dismiss(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } NotificationHelper.adsfinish = true; if(NotificationHelper.waitflash){ NotificationHelper.flashrom(); } webviewclass.finish(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }; final CountDownTimer timer1 = new CountDownTimer(20000, 1000) { @Override public void onFinish() { // TODO Auto-generated method stub waittextview.setText("Storing click..."); mWebView.loadUrl("javascript:skipButton()"); timer2.start(); this.cancel(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub waittextview.setText(Long.toString(millisUntilFinished/1000)+" seconds..."); } }; final CountDownTimer timer_timeout = new CountDownTimer(40000, 40000) { @Override public void onFinish() { Toast.makeText(myactivity, "Network error", 4000).show(); webviewclass.finish(); } @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } }; myactivity = this.getBaseContext(); mWebView = (WebView) findViewById(R.id.webView1); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); mWebView.setWebViewClient(new WebViewClient() { public void onPageFinished(WebView view, String url) { //timer = new Timer(); //timer.schedule(new UpdateTimeTask(), 0, 1000); runOnUiThread(new Runnable() { public void run() { if(!firstloading){ try { timer_timeout.cancel(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } timer1.start(); firstloading = true; } } }); } }); mWebView.loadUrl(getString(R.string.adsurl)); // mWebView.loadUrl("http://www.google.it"); timer_timeout.start(); }
diff --git a/src/main/java/com/hrktsoft/portfowardutility/ConfigurationLoader.java b/src/main/java/com/hrktsoft/portfowardutility/ConfigurationLoader.java index e8905b7..d743e27 100644 --- a/src/main/java/com/hrktsoft/portfowardutility/ConfigurationLoader.java +++ b/src/main/java/com/hrktsoft/portfowardutility/ConfigurationLoader.java @@ -1,133 +1,135 @@ package com.hrktsoft.portfowardutility; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.hrktsoft.portfowardutility.entry.ForwardEntryL; /** * A configuration loader class * * @author hrkt * */ public class ConfigurationLoader { /** * file path */ private String filePath = null; /** * @param filePath */ public ConfigurationLoader(String filePath) { super(); this.filePath = filePath; } public Configuration getConfiguration() throws FileNotFoundException, IllegalConfigurationException, IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filePath)); Configuration configuration = new Configuration(); List<ForwardEntryL> entriesL = new ArrayList<ForwardEntryL>(); String line = null; while (null != (line = br.readLine())) { if (line.startsWith("USER:")) { // parse USER:XXXX if (null != configuration.getUser()) { throw new IllegalConfigurationException( "duplicate user line:" + line); } String[] user = line.split(":"); if (user.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setUser(user[1]); } else if (line.startsWith("HOST:")) { // parse HOST:XXX.YYY.ZZZ if (null != configuration.getHost()) { throw new IllegalConfigurationException( "duplicate host line:" + line); } String[] host = line.split(":"); if (host.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setHost(host[1]); } else if (line.startsWith("PORT:")) { // parse PORT:XX String[] portLine = line.split(":"); if (portLine.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } int port = 0; try{ port = Integer.parseInt(portLine[1]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setPort(port); } else if (line.startsWith("L:")) { // parse String[] host = line.split(":"); if (host.length != 4) { throw new IllegalConfigurationException("invalid line:" + line); } int localPort = 0; int destPort = 0; try{ localPort = Integer.parseInt(host[1]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } String destHost = host[2]; if("".equals(destHost)) { throw new IllegalConfigurationException("invalid line:" + line); } try{ destPort = Integer.parseInt(host[3]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } ForwardEntryL l = new ForwardEntryL(localPort, destHost, destPort); entriesL.add(l); } else if (line.startsWith("#")) { // comment line } else { // ignore } } configuration.setForwardEntriesL(entriesL); return configuration; } catch (IOException e) { System.err.println("An error occured in reading file."); throw e; } finally { try { - br.close(); + if(null != br){ + br.close(); + } } catch (IOException e) { System.err.println("An error occured in closing file."); } } } }
true
true
public Configuration getConfiguration() throws FileNotFoundException, IllegalConfigurationException, IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filePath)); Configuration configuration = new Configuration(); List<ForwardEntryL> entriesL = new ArrayList<ForwardEntryL>(); String line = null; while (null != (line = br.readLine())) { if (line.startsWith("USER:")) { // parse USER:XXXX if (null != configuration.getUser()) { throw new IllegalConfigurationException( "duplicate user line:" + line); } String[] user = line.split(":"); if (user.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setUser(user[1]); } else if (line.startsWith("HOST:")) { // parse HOST:XXX.YYY.ZZZ if (null != configuration.getHost()) { throw new IllegalConfigurationException( "duplicate host line:" + line); } String[] host = line.split(":"); if (host.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setHost(host[1]); } else if (line.startsWith("PORT:")) { // parse PORT:XX String[] portLine = line.split(":"); if (portLine.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } int port = 0; try{ port = Integer.parseInt(portLine[1]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setPort(port); } else if (line.startsWith("L:")) { // parse String[] host = line.split(":"); if (host.length != 4) { throw new IllegalConfigurationException("invalid line:" + line); } int localPort = 0; int destPort = 0; try{ localPort = Integer.parseInt(host[1]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } String destHost = host[2]; if("".equals(destHost)) { throw new IllegalConfigurationException("invalid line:" + line); } try{ destPort = Integer.parseInt(host[3]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } ForwardEntryL l = new ForwardEntryL(localPort, destHost, destPort); entriesL.add(l); } else if (line.startsWith("#")) { // comment line } else { // ignore } } configuration.setForwardEntriesL(entriesL); return configuration; } catch (IOException e) { System.err.println("An error occured in reading file."); throw e; } finally { try { br.close(); } catch (IOException e) { System.err.println("An error occured in closing file."); } } }
public Configuration getConfiguration() throws FileNotFoundException, IllegalConfigurationException, IOException { BufferedReader br = null; try { br = new BufferedReader(new FileReader(filePath)); Configuration configuration = new Configuration(); List<ForwardEntryL> entriesL = new ArrayList<ForwardEntryL>(); String line = null; while (null != (line = br.readLine())) { if (line.startsWith("USER:")) { // parse USER:XXXX if (null != configuration.getUser()) { throw new IllegalConfigurationException( "duplicate user line:" + line); } String[] user = line.split(":"); if (user.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setUser(user[1]); } else if (line.startsWith("HOST:")) { // parse HOST:XXX.YYY.ZZZ if (null != configuration.getHost()) { throw new IllegalConfigurationException( "duplicate host line:" + line); } String[] host = line.split(":"); if (host.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setHost(host[1]); } else if (line.startsWith("PORT:")) { // parse PORT:XX String[] portLine = line.split(":"); if (portLine.length != 2) { throw new IllegalConfigurationException("invalid line:" + line); } int port = 0; try{ port = Integer.parseInt(portLine[1]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } configuration.setPort(port); } else if (line.startsWith("L:")) { // parse String[] host = line.split(":"); if (host.length != 4) { throw new IllegalConfigurationException("invalid line:" + line); } int localPort = 0; int destPort = 0; try{ localPort = Integer.parseInt(host[1]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } String destHost = host[2]; if("".equals(destHost)) { throw new IllegalConfigurationException("invalid line:" + line); } try{ destPort = Integer.parseInt(host[3]); } catch (NumberFormatException nfe) { throw new IllegalConfigurationException("invalid line:" + line); } ForwardEntryL l = new ForwardEntryL(localPort, destHost, destPort); entriesL.add(l); } else if (line.startsWith("#")) { // comment line } else { // ignore } } configuration.setForwardEntriesL(entriesL); return configuration; } catch (IOException e) { System.err.println("An error occured in reading file."); throw e; } finally { try { if(null != br){ br.close(); } } catch (IOException e) { System.err.println("An error occured in closing file."); } } }
diff --git a/src/com/minecarts/verrier/lockdown/Lockdown.java b/src/com/minecarts/verrier/lockdown/Lockdown.java index 415e5b3..a526136 100644 --- a/src/com/minecarts/verrier/lockdown/Lockdown.java +++ b/src/com/minecarts/verrier/lockdown/Lockdown.java @@ -1,207 +1,206 @@ package com.minecarts.verrier.lockdown; import java.util.logging.Logger; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.event.Event; import org.bukkit.event.Event.Type; import org.bukkit.util.config.Configuration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import com.minecarts.verrier.lockdown.listener.*; public class Lockdown extends JavaPlugin { public final Logger log = Logger.getLogger("Minecraft.Lockdown"); private PluginManager pluginManager; public Configuration config; private List<String> requiredPlugins; private boolean debug = false; private boolean locked = false; private HashMap<String, Boolean> disabledPlugins = new HashMap<String, Boolean>(); private HashMap<String, Boolean> lockedPlugins = new HashMap<String, Boolean>(); private EntityListener entityListener; private BlockListener blockListener; private PlayerListener playerListener; public void onEnable(){ PluginDescriptionFile pdf = getDescription(); log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled."); pluginManager = getServer().getPluginManager(); loadConfig(); // Start the world in lockdown mode? if(config.getBoolean("locked", false)) { lock("Starting in lockdown mode."); } //Create our listeners entityListener = new EntityListener(this); blockListener = new BlockListener(this); playerListener = new PlayerListener(this); //Register our events //Player //TODO - pluginManager.registerEvent(Type.PLAYER_ITEM, playerListener, Event.Priority.Normal, this); - pluginManager.registerEvent(Type.ENTITY_DAMAGED, entityListener, Event.Priority.Normal, this); + pluginManager.registerEvent(Type.PLAYER_INTERACT, playerListener, Event.Priority.Normal, this); + pluginManager.registerEvent(Type.ENTITY_DAMAGE, entityListener, Event.Priority.Normal, this); //Painting pluginManager.registerEvent(Type.PAINTING_CREATE, entityListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.PAINTING_REMOVE, entityListener, Event.Priority.Normal, this); //Explosions - pluginManager.registerEvent(Type.EXPLOSION_PRIMED, entityListener, Event.Priority.Normal, this); + pluginManager.registerEvent(Type.EXPLOSION_PRIME, entityListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.ENTITY_EXPLODE, entityListener, Event.Priority.Normal, this); //Blocks pluginManager.registerEvent(Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); - pluginManager.registerEvent(Type.BLOCK_PLACED, blockListener, Event.Priority.Normal, this); - pluginManager.registerEvent(Type.BLOCK_INTERACT, blockListener, Event.Priority.Normal, this); + pluginManager.registerEvent(Type.BLOCK_PLACE, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_IGNITE, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_BURN, blockListener, Event.Priority.Normal, this); - pluginManager.registerEvent(Type.BLOCK_FLOW, blockListener, Event.Priority.Normal, this); + pluginManager.registerEvent(Type.BLOCK_FROMTO, blockListener, Event.Priority.Normal, this); //Start the timer to monitor our required plugins Runnable checkLoadedPlugins = new checkLoadedPlugins(); getServer().getScheduler().scheduleSyncRepeatingTask(this, checkLoadedPlugins, 20, 300); //Check after one second, then every 15 seconds (300 ticks) } public void onDisable(){ } public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String[] args){ if(cmdLabel.equals("lockdown") && sender.isOp()){ String msg = "Console command"; if(sender instanceof Player) msg = "Command issued by " + ((Player) sender).getName(); if(args.length > 0) { if(args[0].equals("lock")){ lock(msg); sender.sendMessage("LOCKDOWN ENFORCED!"); return true; } else if (args[0].equals("unlock")){ unlock(msg); sender.sendMessage("Lockdown lifted!"); return true; } else if (args[0].equals("reload")) { loadConfig(); sender.sendMessage("Lockdown config reloaded."); log("Config reloaded.", false); return true; } } else { msg = "Lockdown status: " + (isLocked() ? "LOCKED" : "UNLOCKED"); if(!lockedPlugins.isEmpty()) msg += "\n Locked plugins: " + lockedPlugins.keySet(); if(!disabledPlugins.isEmpty()) msg += "\n Disabled plugins: " + disabledPlugins.keySet(); sender.sendMessage(msg); return true; } } return false; } private void loadConfig() { if(config == null) config = getConfiguration(); else config.load(); requiredPlugins = config.getStringList("required_plugins", new ArrayList<String>()); debug = config.getBoolean("debug", false); } //Repeating plugin loaded checker public class checkLoadedPlugins implements Runnable { public void run() { if(disabledPlugins.isEmpty()) { log("All required plugins enabled."); return; } // clear disabled plugins list in case the required plugins list changes on a config reload disabledPlugins.clear(); for(String p : Lockdown.this.requiredPlugins) { if(!Lockdown.this.pluginManager.isPluginEnabled(p)) { disabledPlugins.put(p, true); log("Required plugin " + p + " is not loaded or disabled."); } } } } // Internal lock/unlock private void lock(String reason){ locked = true; log("LOCKDOWN ENFORCED: " + reason, false); } private void unlock(String reason){ locked = false; log("Lockdown lifted: " + reason, false); } //External API public boolean isLocked(){ return locked || !disabledPlugins.isEmpty() || !lockedPlugins.isEmpty(); } public boolean isLocked(Plugin p) { return isLocked(p.getDescription().getName()); } public boolean isLocked(String pluginName) { return lockedPlugins.containsKey(pluginName); } public void lock(Plugin p, String reason) { lock(p.getDescription().getName(), reason); } public void lock(String pluginName, String reason) { lockedPlugins.put(pluginName, true); log(pluginName + " PLUGIN LOCK: " + reason, false); } public void unlock(Plugin p, String reason) { unlock(p.getDescription().getName(), reason); } public void unlock(String pluginName, String reason) { lockedPlugins.remove(pluginName); log(pluginName + " plugin lock lifted: " + reason, false); } //Internal logging and messaging public void log(String msg){ log(msg, true); } public void log(String msg, boolean debug){ if(debug && !this.debug) return; log.info("Lockdown> " + msg); } public void informPlayer(org.bukkit.entity.Player player){ player.sendMessage(ChatColor.GRAY + "The world is in " + ChatColor.YELLOW + "temporary lockdown mode" + ChatColor.GRAY + " while all plugins are"); player.sendMessage(ChatColor.GRAY + " properly loaded. Please try again in a few seconds."); } }
false
true
public void onEnable(){ PluginDescriptionFile pdf = getDescription(); log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled."); pluginManager = getServer().getPluginManager(); loadConfig(); // Start the world in lockdown mode? if(config.getBoolean("locked", false)) { lock("Starting in lockdown mode."); } //Create our listeners entityListener = new EntityListener(this); blockListener = new BlockListener(this); playerListener = new PlayerListener(this); //Register our events //Player //TODO pluginManager.registerEvent(Type.PLAYER_ITEM, playerListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.ENTITY_DAMAGED, entityListener, Event.Priority.Normal, this); //Painting pluginManager.registerEvent(Type.PAINTING_CREATE, entityListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.PAINTING_REMOVE, entityListener, Event.Priority.Normal, this); //Explosions pluginManager.registerEvent(Type.EXPLOSION_PRIMED, entityListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.ENTITY_EXPLODE, entityListener, Event.Priority.Normal, this); //Blocks pluginManager.registerEvent(Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_PLACED, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_INTERACT, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_IGNITE, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_BURN, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_FLOW, blockListener, Event.Priority.Normal, this); //Start the timer to monitor our required plugins Runnable checkLoadedPlugins = new checkLoadedPlugins(); getServer().getScheduler().scheduleSyncRepeatingTask(this, checkLoadedPlugins, 20, 300); //Check after one second, then every 15 seconds (300 ticks) }
public void onEnable(){ PluginDescriptionFile pdf = getDescription(); log.info("[" + pdf.getName() + "] version " + pdf.getVersion() + " enabled."); pluginManager = getServer().getPluginManager(); loadConfig(); // Start the world in lockdown mode? if(config.getBoolean("locked", false)) { lock("Starting in lockdown mode."); } //Create our listeners entityListener = new EntityListener(this); blockListener = new BlockListener(this); playerListener = new PlayerListener(this); //Register our events //Player //TODO pluginManager.registerEvent(Type.PLAYER_INTERACT, playerListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.ENTITY_DAMAGE, entityListener, Event.Priority.Normal, this); //Painting pluginManager.registerEvent(Type.PAINTING_CREATE, entityListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.PAINTING_REMOVE, entityListener, Event.Priority.Normal, this); //Explosions pluginManager.registerEvent(Type.EXPLOSION_PRIME, entityListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.ENTITY_EXPLODE, entityListener, Event.Priority.Normal, this); //Blocks pluginManager.registerEvent(Type.BLOCK_BREAK, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_PLACE, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_IGNITE, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_BURN, blockListener, Event.Priority.Normal, this); pluginManager.registerEvent(Type.BLOCK_FROMTO, blockListener, Event.Priority.Normal, this); //Start the timer to monitor our required plugins Runnable checkLoadedPlugins = new checkLoadedPlugins(); getServer().getScheduler().scheduleSyncRepeatingTask(this, checkLoadedPlugins, 20, 300); //Check after one second, then every 15 seconds (300 ticks) }
diff --git a/src/com/github/LeoVerto/Fact/Fact.java b/src/com/github/LeoVerto/Fact/Fact.java index 6c03383..6d7693e 100644 --- a/src/com/github/LeoVerto/Fact/Fact.java +++ b/src/com/github/LeoVerto/Fact/Fact.java @@ -1,170 +1,172 @@ package com.github.LeoVerto.Fact; import java.util.Arrays; import java.util.HashSet; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; public class Fact extends JavaPlugin { HashSet<Player> playersIgnoring = new HashSet<Player>(); @Override public void onEnable() { loadConfiguration(); autoFacts(); } @Override public void onDisable() { getServer().getScheduler().cancelTasks(this); playersIgnoring.clear(); } public void loadConfiguration() { reloadConfig(); getConfig().addDefault("Colors.PlayerFact.Fact", "'&7'"); getConfig().addDefault("Colors.PlayerFact.Text", "'&f'"); getConfig().addDefault("Colors.ConsoleFact.Fact", "'&6'"); getConfig().addDefault("Colors.ConsoleFact.Text", "'&f'"); getConfig().addDefault("Colors.AutoFact.Fact", "'&3'"); getConfig().addDefault("Colors.AutoFact.Text", "'&f'"); getConfig().addDefault("Messages.AutoFact.Delay", 5); getConfig().addDefault("Messages.AutoFact.Facts", Arrays.asList("This is a default autofact.", "You can change autofacts in /plugins/Fact/config.yml", "Default stuff is usually bad, so please change this!")); getConfig().addDefault("Text.Fact", "Fact>"); getConfig().addDefault("Text.AutoFact", "AutoFact>"); getConfig().addDefault("Messages.Ignore.Ignoring", ("No longer displaying Fact messages!")); getConfig().addDefault("Messages.Ignore.NotIgnoring", ("Now displaying Fact messages!")); getConfig().addDefault("Messages.Reload", ("Reload complete!")); getConfig().options().copyDefaults(true); //Currently no header //getConfig().options().copyHeader(true); saveConfig(); } public void autoFacts() { final long autoFactDelay = (getConfig().getLong("Messages.AutoFact.Delay") * 1200); final List<?> messages = getConfig().getList("Messages.AutoFact.Facts"); final int messageCount = messages.size(); getServer().getScheduler().scheduleSyncRepeatingTask(this, new Runnable() { private int messageNumber = 0; @Override public void run() { if (messageNumber < (messageCount)) { sendFact((String) messages.get(messageNumber), "auto"); messageNumber++; } else { messageNumber = 0; sendFact((String) messages.get(messageNumber), "auto"); messageNumber++; } } }, 1200L, autoFactDelay); } public <player> void sendFact(final String message, final String type) { final String FactColor = ChatColor.translateAlternateColorCodes('&', getConfig().getString("Colors.PlayerFact.Fact").replace("'", "")); final String TextColor = ChatColor.translateAlternateColorCodes('&', getConfig().getString("Colors.PlayerFact.Text").replace("'", "")); final String ConsoleFactColor = ChatColor.translateAlternateColorCodes('&', getConfig().getString("Colors.ConsoleFact.Fact").replace("'", "")); final String ConsoleTextColor = ChatColor.translateAlternateColorCodes('&', getConfig().getString("Colors.ConsoleFact.Text").replace("'", "")); final String AutoFactColor = ChatColor.translateAlternateColorCodes('&', getConfig().getString("Colors.AutoFact.Fact").replace("'", "")); final String AutoTextColor = ChatColor.translateAlternateColorCodes('&', getConfig().getString("Colors.AutoFact.Text").replace("'", "")); final String FactText = getConfig().getString("Text.Fact"); final String AutoFactText = getConfig().getString("Text.AutoFact"); final Player[] onlinePlayers = Bukkit.getServer().getOnlinePlayers(); for (int i = 0; i < onlinePlayers.length; i++) { if (playersIgnoring.contains(Bukkit.getOnlinePlayers()[i]) == false) { final Player player = onlinePlayers[i]; if (player.hasPermission("fact.receive")) { if (type.equals("player")) { onlinePlayers[i].sendMessage(FactColor + FactText + " " + TextColor + message); } else if (type.equals("auto")) { onlinePlayers[i].sendMessage(AutoFactColor + AutoFactText + " " + AutoTextColor + message); } else { onlinePlayers[i].sendMessage(ConsoleFactColor + FactText + " " + ConsoleTextColor + message); } } } } if (!type.equals("auto")) { getLogger().info(FactText + " " + message); } } @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { if (cmd.getName().equalsIgnoreCase("fact")) { //Reload command if (args[0].equalsIgnoreCase("reload")) { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.reload")) { loadConfiguration(); + getServer().getScheduler().cancelTasks(this); + autoFacts(); player.sendMessage(getConfig().getString("Messages.Reload")); getLogger().info(getConfig().getString("Messages.Reload")); return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { loadConfiguration(); getLogger().info(getConfig().getString("Messages.Reload")); return true; } //Ignore command } else if (args[0].equalsIgnoreCase("ignore")) { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.ignore")) { if (playersIgnoring.contains(player) == false) { playersIgnoring.add(player); player.sendMessage(getConfig().getString("Messages.Ignore.Ignoring")); } else { playersIgnoring.remove(player); player.sendMessage(getConfig().getString("Messages.Ignore.NotIgnoring")); } return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { sender.sendMessage("You can only execute this command as a player!"); return true; } //Normal facts } else { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.fact")) { String message = ""; for (int i = 0; i < args.length; i++) { message = (message + " " + args[i]); } sendFact(message, "player"); return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { String message = ""; for (int i = 0; i < args.length; i++) { message = (message + " " + args[i]); } sendFact(message, "nonplayer"); return true; } } } return false; } }
true
true
public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { if (cmd.getName().equalsIgnoreCase("fact")) { //Reload command if (args[0].equalsIgnoreCase("reload")) { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.reload")) { loadConfiguration(); player.sendMessage(getConfig().getString("Messages.Reload")); getLogger().info(getConfig().getString("Messages.Reload")); return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { loadConfiguration(); getLogger().info(getConfig().getString("Messages.Reload")); return true; } //Ignore command } else if (args[0].equalsIgnoreCase("ignore")) { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.ignore")) { if (playersIgnoring.contains(player) == false) { playersIgnoring.add(player); player.sendMessage(getConfig().getString("Messages.Ignore.Ignoring")); } else { playersIgnoring.remove(player); player.sendMessage(getConfig().getString("Messages.Ignore.NotIgnoring")); } return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { sender.sendMessage("You can only execute this command as a player!"); return true; } //Normal facts } else { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.fact")) { String message = ""; for (int i = 0; i < args.length; i++) { message = (message + " " + args[i]); } sendFact(message, "player"); return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { String message = ""; for (int i = 0; i < args.length; i++) { message = (message + " " + args[i]); } sendFact(message, "nonplayer"); return true; } } } return false; }
public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) { if (cmd.getName().equalsIgnoreCase("fact")) { //Reload command if (args[0].equalsIgnoreCase("reload")) { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.reload")) { loadConfiguration(); getServer().getScheduler().cancelTasks(this); autoFacts(); player.sendMessage(getConfig().getString("Messages.Reload")); getLogger().info(getConfig().getString("Messages.Reload")); return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { loadConfiguration(); getLogger().info(getConfig().getString("Messages.Reload")); return true; } //Ignore command } else if (args[0].equalsIgnoreCase("ignore")) { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.ignore")) { if (playersIgnoring.contains(player) == false) { playersIgnoring.add(player); player.sendMessage(getConfig().getString("Messages.Ignore.Ignoring")); } else { playersIgnoring.remove(player); player.sendMessage(getConfig().getString("Messages.Ignore.NotIgnoring")); } return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { sender.sendMessage("You can only execute this command as a player!"); return true; } //Normal facts } else { if ((sender instanceof Player)) { final Player player = (Player) sender; if (player.hasPermission("fact.fact")) { String message = ""; for (int i = 0; i < args.length; i++) { message = (message + " " + args[i]); } sendFact(message, "player"); return true; } else { player.sendMessage(this.getCommand("fact").getPermissionMessage()); return false; } } else { String message = ""; for (int i = 0; i < args.length; i++) { message = (message + " " + args[i]); } sendFact(message, "nonplayer"); return true; } } } return false; }
diff --git a/src/org/mozilla/javascript/DefaultErrorReporter.java b/src/org/mozilla/javascript/DefaultErrorReporter.java index 17ad79ac..c7d93d48 100644 --- a/src/org/mozilla/javascript/DefaultErrorReporter.java +++ b/src/org/mozilla/javascript/DefaultErrorReporter.java @@ -1,102 +1,113 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; /** * This is the default error reporter for JavaScript. * * @author Norris Boyd */ class DefaultErrorReporter implements ErrorReporter { static final DefaultErrorReporter instance = new DefaultErrorReporter(); private boolean forEval; private ErrorReporter chainedReporter; private DefaultErrorReporter() { } static ErrorReporter forEval(ErrorReporter reporter) { DefaultErrorReporter r = new DefaultErrorReporter(); r.forEval = true; r.chainedReporter = reporter; return r; } public void warning(String message, String sourceURI, int line, String lineText, int lineOffset) { if (chainedReporter != null) { chainedReporter.warning( message, sourceURI, line, lineText, lineOffset); } else { // Do nothing } } public void error(String message, String sourceURI, int line, String lineText, int lineOffset) { if (forEval) { - throw ScriptRuntime.constructError( - "SyntaxError", message, sourceURI, line, lineText, lineOffset); + // Assume error message strings that start with "TypeError: " + // should become TypeError exceptions. A bit of a hack, but we + // don't want to change the ErrorReporter interface. + String error = "SyntaxError"; + final String TYPE_ERROR_NAME = "TypeError"; + final String DELIMETER = ": "; + final String prefix = TYPE_ERROR_NAME + DELIMETER; + if (message.startsWith(prefix)) { + error = TYPE_ERROR_NAME; + message = message.substring(prefix.length()); + } + throw ScriptRuntime.constructError(error, message, sourceURI, + line, lineText, lineOffset); } if (chainedReporter != null) { chainedReporter.error( message, sourceURI, line, lineText, lineOffset); } else { throw runtimeError( message, sourceURI, line, lineText, lineOffset); } } public EvaluatorException runtimeError(String message, String sourceURI, int line, String lineText, int lineOffset) { if (chainedReporter != null) { return chainedReporter.runtimeError( message, sourceURI, line, lineText, lineOffset); } else { return new EvaluatorException( message, sourceURI, line, lineText, lineOffset); } } }
true
true
public void error(String message, String sourceURI, int line, String lineText, int lineOffset) { if (forEval) { throw ScriptRuntime.constructError( "SyntaxError", message, sourceURI, line, lineText, lineOffset); } if (chainedReporter != null) { chainedReporter.error( message, sourceURI, line, lineText, lineOffset); } else { throw runtimeError( message, sourceURI, line, lineText, lineOffset); } }
public void error(String message, String sourceURI, int line, String lineText, int lineOffset) { if (forEval) { // Assume error message strings that start with "TypeError: " // should become TypeError exceptions. A bit of a hack, but we // don't want to change the ErrorReporter interface. String error = "SyntaxError"; final String TYPE_ERROR_NAME = "TypeError"; final String DELIMETER = ": "; final String prefix = TYPE_ERROR_NAME + DELIMETER; if (message.startsWith(prefix)) { error = TYPE_ERROR_NAME; message = message.substring(prefix.length()); } throw ScriptRuntime.constructError(error, message, sourceURI, line, lineText, lineOffset); } if (chainedReporter != null) { chainedReporter.error( message, sourceURI, line, lineText, lineOffset); } else { throw runtimeError( message, sourceURI, line, lineText, lineOffset); } }
diff --git a/apt/src/main/java/com/bloatit/framework/webprocessor/annotations/MessageFormater.java b/apt/src/main/java/com/bloatit/framework/webprocessor/annotations/MessageFormater.java index 5f13ab415..a528faeb9 100644 --- a/apt/src/main/java/com/bloatit/framework/webprocessor/annotations/MessageFormater.java +++ b/apt/src/main/java/com/bloatit/framework/webprocessor/annotations/MessageFormater.java @@ -1,32 +1,32 @@ package com.bloatit.framework.webprocessor.annotations; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; public class MessageFormater { private Map<String, String> params = new HashMap<String, String>(); public MessageFormater(final String name, final String value) { params.put("%paramName%", name); params.put("%value%", value); } public void addParameter(final String name, final String value) { params.put(name, value); } public String format(final String message) { String errorMsg = message; for (final Entry<String, String> formatter : params.entrySet()) { if (!formatter.getValue().isEmpty()) { - errorMsg = message.replaceAll(formatter.getKey(), Matcher.quoteReplacement(formatter.getValue())); + errorMsg = errorMsg.replaceAll(formatter.getKey(), Matcher.quoteReplacement(formatter.getValue())); } else { - errorMsg = message.replaceAll(formatter.getKey(), "null"); + errorMsg = errorMsg.replaceAll(formatter.getKey(), "null"); } } return errorMsg; } }
false
true
public String format(final String message) { String errorMsg = message; for (final Entry<String, String> formatter : params.entrySet()) { if (!formatter.getValue().isEmpty()) { errorMsg = message.replaceAll(formatter.getKey(), Matcher.quoteReplacement(formatter.getValue())); } else { errorMsg = message.replaceAll(formatter.getKey(), "null"); } } return errorMsg; }
public String format(final String message) { String errorMsg = message; for (final Entry<String, String> formatter : params.entrySet()) { if (!formatter.getValue().isEmpty()) { errorMsg = errorMsg.replaceAll(formatter.getKey(), Matcher.quoteReplacement(formatter.getValue())); } else { errorMsg = errorMsg.replaceAll(formatter.getKey(), "null"); } } return errorMsg; }
diff --git a/src/gwt/src/org/rstudio/studio/client/pdfviewer/pdfjs/PDFView.java b/src/gwt/src/org/rstudio/studio/client/pdfviewer/pdfjs/PDFView.java index 468210a15a..b31ddf2e8a 100644 --- a/src/gwt/src/org/rstudio/studio/client/pdfviewer/pdfjs/PDFView.java +++ b/src/gwt/src/org/rstudio/studio/client/pdfviewer/pdfjs/PDFView.java @@ -1,157 +1,157 @@ /* * PDFView.java * * Copyright (C) 2009-12 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.pdfviewer.pdfjs; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import org.rstudio.studio.client.pdfviewer.pdfjs.events.PDFLoadEvent; import org.rstudio.studio.client.pdfviewer.pdfjs.events.PageChangeEvent; import org.rstudio.studio.client.pdfviewer.pdfjs.events.ScaleChangeEvent; public class PDFView extends JavaScriptObject { protected PDFView() { } public static native void nextPage() /*-{ $wnd.PDFView.page++; }-*/; public static native void previousPage() /*-{ $wnd.PDFView.page-- ; }-*/; public static native int currentPage() /*-{ return $wnd.PDFView.page; }-*/; public static native int pageCount() /*-{ return $wnd.PDFView.pages.length; }-*/; public static native void goToPage(int page) /*-{ $wnd.PDFView.page = page; }-*/; public static native double currentScale() /*-{ return $wnd.PDFView.currentScale; }-*/; public static native void zoomIn() /*-{ $wnd.PDFView.zoomIn() ; }-*/; public static native void zoomOut() /*-{ $wnd.PDFView.zoomOut() ; }-*/; public native static void parseScale(String value) /*-{ $wnd.PDFView.parseScale(value); }-*/; public static HandlerRegistration addPageChangeHandler(PageChangeEvent.Handler handler) { return handlers_.addHandler(PageChangeEvent.TYPE, handler); } public static HandlerRegistration addScaleChangeHandler(ScaleChangeEvent.Handler handler) { return handlers_.addHandler(ScaleChangeEvent.TYPE, handler); } public static HandlerRegistration addPDFLoadHandler(PDFLoadEvent.Handler handler) { return handlers_.addHandler(PDFLoadEvent.TYPE, handler); } public static native void toggleSidebar() /*-{ $wnd.PDFView.toggleSidebar(); }-*/; public native static void initializeEvents() /*-{ - var _load = $wnd.PDFView.load; - $wnd.PDFView.load = $entry(function(data, scale) { - _load.call($wnd.PDFView, data, scale); + var _setInitialView = $wnd.PDFView.setInitialView; + $wnd.PDFView.setInitialView = $entry(function(storedHash, scale) { + _setInitialView.call($wnd.PDFView, storedHash, scale); @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::firePDFLoadEvent()(); }); $wnd.addEventListener( "pagechange", $entry(function(evt) { @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::firePageChangeEvent()(); }), true); $wnd.addEventListener( "scalechange", $entry(function(evt) { @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::fireScaleChangeEvent()(); }), true); }-*/; private static void firePageChangeEvent() { handlers_.fireEvent(new PageChangeEvent()); } private static void fireScaleChangeEvent() { handlers_.fireEvent(new ScaleChangeEvent()); } private static void firePDFLoadEvent() { handlers_.fireEvent(new PDFLoadEvent()); } public static void setLoadingVisible(boolean visible) { Element el = Document.get().getElementById("loading"); if (visible) el.removeAttribute("hidden"); else el.setAttribute("hidden", "hidden"); } public static native void navigateTo(JavaScriptObject dest) /*-{ if (dest == null) return; $wnd.PDFView.parseScale(dest.scale); $wnd.scrollTo(dest.x, dest.y); }-*/; public static native JavaScriptObject getNavigateDest() /*-{ if ($wnd.PDFView.pages.length == 0) return null; return { scale: $wnd.PDFView.currentScaleValue, x: $wnd.scrollX, y: $wnd.scrollY }; }-*/; public static native void scrollToTop() /*-{ $wnd.scrollTo($wnd.scrollX, 32); // a little padding on top }-*/; private static final HandlerManager handlers_ = new HandlerManager(PDFView.class); }
true
true
public native static void initializeEvents() /*-{ var _load = $wnd.PDFView.load; $wnd.PDFView.load = $entry(function(data, scale) { _load.call($wnd.PDFView, data, scale); @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::firePDFLoadEvent()(); }); $wnd.addEventListener( "pagechange", $entry(function(evt) { @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::firePageChangeEvent()(); }), true); $wnd.addEventListener( "scalechange", $entry(function(evt) { @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::fireScaleChangeEvent()(); }), true); }-*/;
public native static void initializeEvents() /*-{ var _setInitialView = $wnd.PDFView.setInitialView; $wnd.PDFView.setInitialView = $entry(function(storedHash, scale) { _setInitialView.call($wnd.PDFView, storedHash, scale); @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::firePDFLoadEvent()(); }); $wnd.addEventListener( "pagechange", $entry(function(evt) { @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::firePageChangeEvent()(); }), true); $wnd.addEventListener( "scalechange", $entry(function(evt) { @org.rstudio.studio.client.pdfviewer.pdfjs.PDFView::fireScaleChangeEvent()(); }), true); }-*/;
diff --git a/app/domainservices/RandomHorsesBreeder.java b/app/domainservices/RandomHorsesBreeder.java index 64b0074..9f25b8a 100644 --- a/app/domainservices/RandomHorsesBreeder.java +++ b/app/domainservices/RandomHorsesBreeder.java @@ -1,42 +1,42 @@ package domainservices; import models.Horse; import models.HorseNamePrefix; import models.HorseNameSuffix; import java.util.Date; import java.util.List; import java.util.Random; public class RandomHorsesBreeder { public Horse createRandomHorse() { if (allRandomHorsesAreExhausted()) { throw new RuntimeException("All horses exhausted. Couldn't breed new horse!"); } List<HorseNamePrefix> horsePrefixes = HorseNamePrefix.findAll(); List<HorseNameSuffix> horseSuffixes = HorseNameSuffix.findAll(); Random random = new Random(new Date().getTime()); int randomPrefix = random.nextInt(horsePrefixes.size()); int randomSuffix = random.nextInt(horseSuffixes.size()); Horse horse = new Horse(horsePrefixes.get(randomPrefix).prefix + " " + horseSuffixes.get(randomSuffix).suffix, random.nextInt(2000)); - horse.setMoneyForTrainer(20); + horse.moneyForTrainer = 20; long horseCount = Horse.count("byName", horse.getName()); if (horseCount > 0) { return createRandomHorse(); } return horse; } private static boolean allRandomHorsesAreExhausted() { long totalAmountOfPossibleRandomHorses = HorseNamePrefix.count() * HorseNameSuffix.count(); long amountOfHorsesInDatabase = Horse.count(); return totalAmountOfPossibleRandomHorses == amountOfHorsesInDatabase; } }
true
true
public Horse createRandomHorse() { if (allRandomHorsesAreExhausted()) { throw new RuntimeException("All horses exhausted. Couldn't breed new horse!"); } List<HorseNamePrefix> horsePrefixes = HorseNamePrefix.findAll(); List<HorseNameSuffix> horseSuffixes = HorseNameSuffix.findAll(); Random random = new Random(new Date().getTime()); int randomPrefix = random.nextInt(horsePrefixes.size()); int randomSuffix = random.nextInt(horseSuffixes.size()); Horse horse = new Horse(horsePrefixes.get(randomPrefix).prefix + " " + horseSuffixes.get(randomSuffix).suffix, random.nextInt(2000)); horse.setMoneyForTrainer(20); long horseCount = Horse.count("byName", horse.getName()); if (horseCount > 0) { return createRandomHorse(); } return horse; }
public Horse createRandomHorse() { if (allRandomHorsesAreExhausted()) { throw new RuntimeException("All horses exhausted. Couldn't breed new horse!"); } List<HorseNamePrefix> horsePrefixes = HorseNamePrefix.findAll(); List<HorseNameSuffix> horseSuffixes = HorseNameSuffix.findAll(); Random random = new Random(new Date().getTime()); int randomPrefix = random.nextInt(horsePrefixes.size()); int randomSuffix = random.nextInt(horseSuffixes.size()); Horse horse = new Horse(horsePrefixes.get(randomPrefix).prefix + " " + horseSuffixes.get(randomSuffix).suffix, random.nextInt(2000)); horse.moneyForTrainer = 20; long horseCount = Horse.count("byName", horse.getName()); if (horseCount > 0) { return createRandomHorse(); } return horse; }
diff --git a/code/src/presenter/ui/editor/EditDialog.java b/code/src/presenter/ui/editor/EditDialog.java index 9b8b3e3..a4bfc8d 100644 --- a/code/src/presenter/ui/editor/EditDialog.java +++ b/code/src/presenter/ui/editor/EditDialog.java @@ -1,203 +1,204 @@ package presenter.ui.editor; import java.io.File; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.window.ApplicationWindow; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.RowLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import presenter.Settings; import presenter.model.Presentation; import presenter.model.Slide; import presenter.ui.OpenDialog; import presenter.ui.presentation.PresenterControl; public class EditDialog extends ApplicationWindow { private Composite slidesComposite; private int size = 500; public EditDialog(Shell parentShell) { super(null); addToolBar(SWT.FLAT); } @Override protected Control createContents(Composite parent) { getShell().setSize(1050, 700); Composite container = (Composite) super.createContents(parent); container.setLayoutData(new GridData(GridData.FILL_BOTH)); container.setLayout(new FillLayout()); ScrolledComposite scrolledSlideComposite = new ScrolledComposite( container, SWT.V_SCROLL); scrolledSlideComposite.setLayout(new FillLayout()); scrolledSlideComposite.setExpandHorizontal(true); scrolledSlideComposite.setExpandVertical(true); slidesComposite = new Composite(scrolledSlideComposite, SWT.NONE); scrolledSlideComposite.setContent(slidesComposite); slidesComposite.setLayout(new RowLayout(SWT.HORIZONTAL)); slidesComposite.setBackground(parent.getDisplay().getSystemColor( SWT.COLOR_GRAY)); slidesComposite.addPaintListener(new PaintListener() { @Override public void paintControl(PaintEvent e) { Rectangle r = slidesComposite.getParent().getClientArea(); ((ScrolledComposite) slidesComposite.getParent()) .setMinSize(slidesComposite.computeSize(r.width, SWT.DEFAULT)); } }); update(); return slidesComposite; } @Override protected Control createToolBarControl(Composite parent) { ToolBar toolbar = (ToolBar) super.createToolBarControl(parent); ToolItem addButton = new ToolItem(toolbar, SWT.PUSH); addButton.setText("add"); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog fileDialog = new FileDialog(getShell(), SWT.MULTI | SWT.OPEN); // fileDialog.setFilterExtensions(new String[] { "*.jpg" }); fileDialog.open(); for (String current : fileDialog.getFileNames()) { File currentFile = new File(fileDialog.getFilterPath() + System.getProperty("file.separator") + current); if (currentFile.getName().endsWith(".pdf")) { MessageBox dialog = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); dialog.setText("extract notes from pdf?"); dialog.setMessage("Do you want to use every second page of the pdf as notes for the previous one?"); Presentation.getEditor().loadFromPdf(currentFile, SWT.YES == dialog.open()); } else { Presentation.getEditor().add(currentFile); } } update(); } }); ToolItem zoomInButton = new ToolItem(toolbar, SWT.PUSH); zoomInButton.setText("+"); zoomInButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { size *= 1.11111f; update(); } }); ToolItem zoomOutButton = new ToolItem(toolbar, SWT.PUSH); zoomOutButton.setText("-"); zoomOutButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { size *= 0.9f; update(); } }); ToolItem startButton = new ToolItem(toolbar, SWT.PUSH); startButton.setText("Start"); startButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PresenterControl dialog = new PresenterControl(); dialog.open(); } }); ToolItem saveButton = new ToolItem(toolbar, SWT.PUSH); saveButton.setText("Save"); saveButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); dialog.setFilterExtensions(new String[] { "*.presentation" }); String result = dialog.open(); if (null == result) return; // cancelled if (!result.endsWith(".presentation")) result += ".presentation"; Presentation.save(new File(result)); Settings.setRecent(result); } }); ToolItem openButton = new ToolItem(toolbar, SWT.PUSH); openButton.setText("Open"); openButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { Dialog dialog = new OpenDialog(getShell()); dialog.open(); + update(); } }); ToolItem exitButton = new ToolItem(toolbar, SWT.PUSH); exitButton.setText("Exit"); exitButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { close(); } }); return toolbar; } public void update() { for (Control current : slidesComposite.getChildren()) current.dispose(); for (Slide current : Presentation.getSlides()) new SlideItem(slidesComposite, SWT.None, current, this); slidesComposite.redraw(); slidesComposite.layout(); } public int getTileWidth() { return size; } }
true
true
protected Control createToolBarControl(Composite parent) { ToolBar toolbar = (ToolBar) super.createToolBarControl(parent); ToolItem addButton = new ToolItem(toolbar, SWT.PUSH); addButton.setText("add"); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog fileDialog = new FileDialog(getShell(), SWT.MULTI | SWT.OPEN); // fileDialog.setFilterExtensions(new String[] { "*.jpg" }); fileDialog.open(); for (String current : fileDialog.getFileNames()) { File currentFile = new File(fileDialog.getFilterPath() + System.getProperty("file.separator") + current); if (currentFile.getName().endsWith(".pdf")) { MessageBox dialog = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); dialog.setText("extract notes from pdf?"); dialog.setMessage("Do you want to use every second page of the pdf as notes for the previous one?"); Presentation.getEditor().loadFromPdf(currentFile, SWT.YES == dialog.open()); } else { Presentation.getEditor().add(currentFile); } } update(); } }); ToolItem zoomInButton = new ToolItem(toolbar, SWT.PUSH); zoomInButton.setText("+"); zoomInButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { size *= 1.11111f; update(); } }); ToolItem zoomOutButton = new ToolItem(toolbar, SWT.PUSH); zoomOutButton.setText("-"); zoomOutButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { size *= 0.9f; update(); } }); ToolItem startButton = new ToolItem(toolbar, SWT.PUSH); startButton.setText("Start"); startButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PresenterControl dialog = new PresenterControl(); dialog.open(); } }); ToolItem saveButton = new ToolItem(toolbar, SWT.PUSH); saveButton.setText("Save"); saveButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); dialog.setFilterExtensions(new String[] { "*.presentation" }); String result = dialog.open(); if (null == result) return; // cancelled if (!result.endsWith(".presentation")) result += ".presentation"; Presentation.save(new File(result)); Settings.setRecent(result); } }); ToolItem openButton = new ToolItem(toolbar, SWT.PUSH); openButton.setText("Open"); openButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { Dialog dialog = new OpenDialog(getShell()); dialog.open(); } }); ToolItem exitButton = new ToolItem(toolbar, SWT.PUSH); exitButton.setText("Exit"); exitButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { close(); } }); return toolbar; }
protected Control createToolBarControl(Composite parent) { ToolBar toolbar = (ToolBar) super.createToolBarControl(parent); ToolItem addButton = new ToolItem(toolbar, SWT.PUSH); addButton.setText("add"); addButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog fileDialog = new FileDialog(getShell(), SWT.MULTI | SWT.OPEN); // fileDialog.setFilterExtensions(new String[] { "*.jpg" }); fileDialog.open(); for (String current : fileDialog.getFileNames()) { File currentFile = new File(fileDialog.getFilterPath() + System.getProperty("file.separator") + current); if (currentFile.getName().endsWith(".pdf")) { MessageBox dialog = new MessageBox(getShell(), SWT.ICON_QUESTION | SWT.YES | SWT.NO); dialog.setText("extract notes from pdf?"); dialog.setMessage("Do you want to use every second page of the pdf as notes for the previous one?"); Presentation.getEditor().loadFromPdf(currentFile, SWT.YES == dialog.open()); } else { Presentation.getEditor().add(currentFile); } } update(); } }); ToolItem zoomInButton = new ToolItem(toolbar, SWT.PUSH); zoomInButton.setText("+"); zoomInButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { size *= 1.11111f; update(); } }); ToolItem zoomOutButton = new ToolItem(toolbar, SWT.PUSH); zoomOutButton.setText("-"); zoomOutButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { size *= 0.9f; update(); } }); ToolItem startButton = new ToolItem(toolbar, SWT.PUSH); startButton.setText("Start"); startButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { PresenterControl dialog = new PresenterControl(); dialog.open(); } }); ToolItem saveButton = new ToolItem(toolbar, SWT.PUSH); saveButton.setText("Save"); saveButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); dialog.setFilterExtensions(new String[] { "*.presentation" }); String result = dialog.open(); if (null == result) return; // cancelled if (!result.endsWith(".presentation")) result += ".presentation"; Presentation.save(new File(result)); Settings.setRecent(result); } }); ToolItem openButton = new ToolItem(toolbar, SWT.PUSH); openButton.setText("Open"); openButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { Dialog dialog = new OpenDialog(getShell()); dialog.open(); update(); } }); ToolItem exitButton = new ToolItem(toolbar, SWT.PUSH); exitButton.setText("Exit"); exitButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent arg0) { close(); } }); return toolbar; }
diff --git a/src/main/org/codehaus/groovy/transform/ImmutableASTTransformation.java b/src/main/org/codehaus/groovy/transform/ImmutableASTTransformation.java index 9cdc6ed9f..87e9a6a9b 100644 --- a/src/main/org/codehaus/groovy/transform/ImmutableASTTransformation.java +++ b/src/main/org/codehaus/groovy/transform/ImmutableASTTransformation.java @@ -1,583 +1,583 @@ /* * Copyright 2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.codehaus.groovy.transform; import groovy.lang.Immutable; import org.codehaus.groovy.ast.*; import org.codehaus.groovy.ast.expr.*; import org.codehaus.groovy.ast.stmt.*; import org.codehaus.groovy.control.CompilePhase; import org.codehaus.groovy.control.SourceUnit; import org.codehaus.groovy.runtime.DefaultGroovyMethods; import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import org.codehaus.groovy.util.HashCodeHelper; import org.objectweb.asm.Opcodes; import java.util.*; /** * Handles generation of code for the @Immutable annotation. * This is experimental, use at your own risk. * * @author Paul King */ @GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION) public class ImmutableASTTransformation implements ASTTransformation, Opcodes { /* currently leaving BigInteger and BigDecimal in list but see: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6348370 */ private static Class[] immutableList = { Boolean.class, Byte.class, Character.class, Double.class, Float.class, Integer.class, Long.class, Short.class, String.class, java.math.BigInteger.class, java.math.BigDecimal.class, java.awt.Color.class, }; private static final Class MY_CLASS = Immutable.class; private static final ClassNode MY_TYPE = new ClassNode(MY_CLASS); private static final String MY_TYPE_NAME = "@" + MY_TYPE.getNameWithoutPackage(); private static final ClassNode OBJECT_TYPE = new ClassNode(Object.class); private static final ClassNode HASHMAP_TYPE = new ClassNode(HashMap.class); private static final ClassNode MAP_TYPE = new ClassNode(Map.class); private static final ClassNode DATE_TYPE = new ClassNode(Date.class); private static final ClassNode CLONEABLE_TYPE = new ClassNode(Cloneable.class); private static final ClassNode COLLECTION_TYPE = new ClassNode(Collection.class); private static final ClassNode HASHUTIL_TYPE = new ClassNode(HashCodeHelper.class); private static final ClassNode STRINGBUFFER_TYPE = new ClassNode(StringBuffer.class); private static final ClassNode DGM_TYPE = new ClassNode(DefaultGroovyMethods.class); private static final ClassNode SELF_TYPE = new ClassNode(ImmutableASTTransformation.class); private static final Token COMPARE_EQUAL = Token.newSymbol(Types.COMPARE_EQUAL, -1, -1); private static final Token COMPARE_NOT_EQUAL = Token.newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1); private static final Token COMPARE_IDENTICAL = Token.newSymbol(Types.COMPARE_IDENTICAL, -1, -1); private static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1); public void visit(ASTNode[] nodes, SourceUnit source) { - if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { - throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class"); + if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { + throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedClass] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; List<PropertyNode> newNodes = new ArrayList<PropertyNode>(); if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; String cName = cNode.getName(); if (cNode.isInterface()) { throw new RuntimeException("Error processing interface '" + cName + "'. " + MY_TYPE_NAME + " not allowed for interfaces."); } if ((cNode.getModifiers() & ACC_FINAL) == 0) { throw new RuntimeException("Error processing class '" + cName + "'. " + MY_TYPE_NAME + " classes must be final."); } final List<PropertyNode> pList = cNode.getProperties(); for (PropertyNode pNode : pList) { adjustPropertyForImmutability(pNode, newNodes); } for (PropertyNode pNode : newNodes) { pList.remove(pNode); addProperty(cNode, pNode); } final List<FieldNode> fList = cNode.getFields(); for (FieldNode fNode : fList) { ensureNotPublic(cName, fNode); } createConstructor(cNode); createHashCode(cNode); createEquals(cNode); createToString(cNode); } } private void ensureNotPublic(String cNode, FieldNode fNode) { String fName = fNode.getName(); // TODO: do we need to lock down things like: $ownClass if (fNode.isPublic() && !fName.contains("$")) { throw new RuntimeException("Public field '" + fName + "' not allowed for " + MY_TYPE_NAME + " class '" + cNode + "'."); } } private void createHashCode(ClassNode cNode) { final FieldNode hashField = cNode.addField("$hash$code", ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.int_TYPE, null); final BlockStatement body = new BlockStatement(); final Expression hash = new FieldExpression(hashField); final List<PropertyNode> list = cNode.getProperties(); body.addStatement(new IfStatement( isZeroExpr(hash), calculateHashStatements(hash, list), new EmptyStatement() )); body.addStatement(new ReturnStatement(hash)); cNode.addMethod(new MethodNode("hashCode", ACC_PUBLIC, ClassHelper.int_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body)); } private void createToString(ClassNode cNode) { final BlockStatement body = new BlockStatement(); final List<PropertyNode> list = cNode.getProperties(); // def _result = new StringBuffer() final Expression result = new VariableExpression("_result"); final Expression init = new ConstructorCallExpression(STRINGBUFFER_TYPE, MethodCallExpression.NO_ARGUMENTS); body.addStatement(new ExpressionStatement(new DeclarationExpression(result, ASSIGN, init))); body.addStatement(append(result, new ConstantExpression(cNode.getName()))); body.addStatement(append(result, new ConstantExpression("("))); boolean first = true; for (PropertyNode pNode : list) { if (first) { first = false; } else { body.addStatement(append(result, new ConstantExpression(", "))); } body.addStatement(new IfStatement( new BooleanExpression(new FieldExpression(cNode.getField("$map$constructor"))), toStringPropertyName(result, pNode.getName()), new EmptyStatement() )); final FieldExpression fieldExpr = new FieldExpression(pNode.getField()); body.addStatement(append(result, new MethodCallExpression(fieldExpr, "toString", MethodCallExpression.NO_ARGUMENTS))); } body.addStatement(append(result, new ConstantExpression(")"))); body.addStatement(new ReturnStatement(new MethodCallExpression(result, "toString", MethodCallExpression.NO_ARGUMENTS))); cNode.addMethod(new MethodNode("toString", ACC_PUBLIC, ClassHelper.STRING_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, body)); } private Statement toStringPropertyName(Expression result, String fName) { final BlockStatement body = new BlockStatement(); body.addStatement(append(result, new ConstantExpression(fName))); body.addStatement(append(result, new ConstantExpression(":"))); return body; } private ExpressionStatement append(Expression result, Expression expr) { return new ExpressionStatement(new MethodCallExpression(result, "append", expr)); } private Statement calculateHashStatements(Expression hash, List<PropertyNode> list) { final BlockStatement body = new BlockStatement(); // def _result = HashCodeHelper.initHash() final Expression result = new VariableExpression("_result"); final Expression init = new StaticMethodCallExpression(HASHUTIL_TYPE, "initHash", MethodCallExpression.NO_ARGUMENTS); body.addStatement(new ExpressionStatement(new DeclarationExpression(result, ASSIGN, init))); // fields for (PropertyNode pNode : list) { // _result = HashCodeHelper.updateHash(_result, field) final Expression fieldExpr = new FieldExpression(pNode.getField()); final Expression args = new TupleExpression(result, fieldExpr); final Expression current = new StaticMethodCallExpression(HASHUTIL_TYPE, "updateHash", args); body.addStatement(assignStatement(result, current)); } // $hash$code = _result body.addStatement(assignStatement(hash, result)); return body; } private void createEquals(ClassNode cNode) { final BlockStatement body = new BlockStatement(); Expression other = new VariableExpression("other"); // some short circuit cases for efficiency body.addStatement(returnFalseIfNull(other)); body.addStatement(returnFalseIfWrongType(cNode, other)); body.addStatement(returnTrueIfIdentical(VariableExpression.THIS_EXPRESSION, other)); final List<PropertyNode> list = cNode.getProperties(); // fields for (PropertyNode pNode : list) { body.addStatement(returnFalseIfPropertyNotEqual(pNode, other)); } // default body.addStatement(new ReturnStatement(ConstantExpression.TRUE)); Parameter[] params = {new Parameter(OBJECT_TYPE, "other")}; cNode.addMethod(new MethodNode("equals", ACC_PUBLIC, ClassHelper.boolean_TYPE, params, ClassNode.EMPTY_ARRAY, body)); } private Statement returnFalseIfWrongType(ClassNode cNode, Expression other) { return new IfStatement( identicalExpr(new ClassExpression(cNode), new ClassExpression(other.getType())), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } private IfStatement returnFalseIfNull(Expression other) { return new IfStatement( equalsNullExpr(other), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } private IfStatement returnTrueIfIdentical(Expression self, Expression other) { return new IfStatement( identicalExpr(self, other), new ReturnStatement(ConstantExpression.TRUE), new EmptyStatement() ); } private Statement returnFalseIfPropertyNotEqual(PropertyNode pNode, Expression other) { return new IfStatement( notEqualsExpr(pNode, other), new ReturnStatement(ConstantExpression.FALSE), new EmptyStatement() ); } private void addProperty(ClassNode cNode, PropertyNode pNode) { final FieldNode fn = pNode.getField(); cNode.getFields().remove(fn); cNode.addProperty(pNode.getName(), pNode.getModifiers() | ACC_FINAL, pNode.getType(), pNode.getInitialExpression(), pNode.getGetterBlock(), pNode.getSetterBlock()); final FieldNode newfn = cNode.getField(fn.getName()); cNode.getFields().remove(newfn); cNode.addField(fn); } private void createConstructor(ClassNode cNode) { // pretty toString will remember how the user declared the params and print accordingly final FieldNode constructorField = cNode.addField("$map$constructor", ACC_PRIVATE | ACC_SYNTHETIC, ClassHelper.boolean_TYPE, null); final FieldExpression constructorStyle = new FieldExpression(constructorField); if (cNode.getDeclaredConstructors().size() != 0) { // TODO: allow constructors which call provided constructor? throw new RuntimeException("Explicit constructors not allowed for " + MY_TYPE_NAME + " class: " + cNode.getNameWithoutPackage()); } List<PropertyNode> list = cNode.getProperties(); boolean specialHashMapCase = list.size() == 1 && list.get(0).getField().getType().equals(HASHMAP_TYPE); if (specialHashMapCase) { createConstructorMapSpecial(cNode, constructorStyle, list); } else { createConstructorMap(cNode, constructorStyle, list); createConstructorOrdered(cNode, constructorStyle, list); } } private void createConstructorMapSpecial(ClassNode cNode, FieldExpression constructorStyle, List<PropertyNode> list) { final BlockStatement body = new BlockStatement(); body.addStatement(createConstructorStatementMapSpecial(list.get(0).getField())); createConstructorMapCommon(cNode, constructorStyle, body); } private void createConstructorMap(ClassNode cNode, FieldExpression constructorStyle, List<PropertyNode> list) { final BlockStatement body = new BlockStatement(); for (PropertyNode pNode : list) { body.addStatement(createConstructorStatement(pNode)); } createConstructorMapCommon(cNode, constructorStyle, body); } private void createConstructorMapCommon(ClassNode cNode, FieldExpression constructorStyle, BlockStatement body) { final List<FieldNode> fList = cNode.getFields(); for (FieldNode fNode : fList) { if (!fNode.isPublic() && !fNode.getName().contains("$") && (cNode.getProperty(fNode.getName()) == null)) { body.addStatement(createConstructorStatementDefault(fNode)); } } body.addStatement(assignStatement(constructorStyle, ConstantExpression.TRUE)); final Parameter[] params = new Parameter[]{new Parameter(HASHMAP_TYPE, "args")}; cNode.addConstructor(new ConstructorNode(ACC_PUBLIC, params, ClassNode.EMPTY_ARRAY, new IfStatement( equalsNullExpr(new VariableExpression("args")), new EmptyStatement(), body))); } private void createConstructorOrdered(ClassNode cNode, FieldExpression constructorStyle, List<PropertyNode> list) { final MapExpression argMap = new MapExpression(); final Parameter[] orderedParams = new Parameter[list.size()]; int index = 0; for (PropertyNode pNode : list) { orderedParams[index++] = new Parameter(pNode.getField().getType(), pNode.getField().getName()); argMap.addMapEntryExpression(new ConstantExpression(pNode.getName()), new VariableExpression(pNode.getName())); } final BlockStatement orderedBody = new BlockStatement(); orderedBody.addStatement(new ExpressionStatement( new ConstructorCallExpression(ClassNode.THIS, new ArgumentListExpression(new CastExpression(HASHMAP_TYPE, argMap))) )); orderedBody.addStatement(assignStatement(constructorStyle, ConstantExpression.FALSE)); cNode.addConstructor(new ConstructorNode(ACC_PUBLIC, orderedParams, ClassNode.EMPTY_ARRAY, orderedBody)); } private Statement createConstructorStatement(PropertyNode pNode) { FieldNode fNode = pNode.getField(); final ClassNode fieldType = fNode.getType(); final Statement statement; if (fieldType.isArray() || implementsInterface(fieldType, CLONEABLE_TYPE)) { statement = createConstructorStatementArrayOrCloneable(fNode); } else if (fieldType.isDerivedFrom(DATE_TYPE)) { statement = createConstructorStatementDate(fNode); } else if (fieldType.isDerivedFrom(COLLECTION_TYPE) || fieldType.isDerivedFrom(MAP_TYPE)) { statement = createConstructorStatementCollection(fNode); } else if (isKnownImmutable(fieldType)) { statement = createConstructorStatementDefault(fNode); } else if (fieldType.isResolved()) { throw new RuntimeException(createErrorMessage(fNode.getName(), fieldType.getName(), "compiling")); } else { statement = createConstructorStatementGuarded(fNode); } return statement; } private boolean implementsInterface(ClassNode fieldType, ClassNode interfaceType) { return Arrays.asList(fieldType.getInterfaces()).contains(interfaceType); } private Statement createConstructorStatementGuarded(FieldNode fNode) { final FieldExpression fieldExpr = new FieldExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression unknown = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(unknown), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, checkUnresolved(fNode, initExpr))), assignStatement(fieldExpr, checkUnresolved(fNode, unknown))); } private Expression checkUnresolved(FieldNode fNode, Expression value) { Expression args = new TupleExpression(new ConstantExpression(fNode.getName()), value); return new StaticMethodCallExpression(SELF_TYPE, "checkImmutable", args); } private Statement createConstructorStatementCollection(FieldNode fNode) { final FieldExpression fieldExpr = new FieldExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression collection = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(collection), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, cloneCollectionExpr(initExpr))), assignStatement(fieldExpr, cloneCollectionExpr(collection))); } private Statement createConstructorStatementMapSpecial(FieldNode fNode) { final FieldExpression fieldExpr = new FieldExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression namedArgs = findArg(fNode.getName()); Expression baseArgs = new VariableExpression("args"); return new IfStatement( equalsNullExpr(baseArgs), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, cloneCollectionExpr(initExpr))), new IfStatement( equalsNullExpr(namedArgs), new IfStatement( isTrueExpr(new MethodCallExpression(baseArgs, "containsKey", new ConstantExpression(fNode.getName()))), assignStatement(fieldExpr, namedArgs), assignStatement(fieldExpr, cloneCollectionExpr(baseArgs))), new IfStatement( isOneExpr(new MethodCallExpression(baseArgs, "size", MethodCallExpression.NO_ARGUMENTS)), assignStatement(fieldExpr, cloneCollectionExpr(namedArgs)), assignStatement(fieldExpr, cloneCollectionExpr(baseArgs))) ) ); } private boolean isKnownImmutable(ClassNode fieldType) { if (!fieldType.isResolved()) return false; Class typeClass = fieldType.getTypeClass(); return typeClass.isEnum() || typeClass.isPrimitive() || inImmutableList(typeClass); } private static boolean inImmutableList(Class typeClass) { return Arrays.asList(immutableList).contains(typeClass); } private Statement createConstructorStatementDefault(FieldNode fNode) { final FieldExpression fieldExpr = new FieldExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; Expression value = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(value), new IfStatement( equalsNullExpr(initExpr), new EmptyStatement(), assignStatement(fieldExpr, initExpr)), assignStatement(fieldExpr, value)); } private Statement createConstructorStatementArrayOrCloneable(FieldNode fNode) { final FieldExpression fieldExpr = new FieldExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; final Expression array = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(array), new IfStatement( equalsNullExpr(initExpr), assignStatement(fieldExpr, ConstantExpression.NULL), assignStatement(fieldExpr, cloneArrayOrCloneableExpr(initExpr))), assignStatement(fieldExpr, cloneArrayOrCloneableExpr(array))); } private Statement createConstructorStatementDate(FieldNode fNode) { final FieldExpression fieldExpr = new FieldExpression(fNode); Expression initExpr = fNode.getInitialValueExpression(); if (initExpr == null) initExpr = ConstantExpression.NULL; final Expression date = findArg(fNode.getName()); return new IfStatement( equalsNullExpr(date), new IfStatement( equalsNullExpr(initExpr), assignStatement(fieldExpr, ConstantExpression.NULL), assignStatement(fieldExpr, cloneDateExpr(initExpr))), assignStatement(fieldExpr, cloneDateExpr(date))); } private Expression cloneDateExpr(Expression origDate) { return new ConstructorCallExpression(DATE_TYPE, new MethodCallExpression(origDate, "getTime", MethodCallExpression.NO_ARGUMENTS)); } private Statement assignStatement(Expression fieldExpr, Expression value) { return new ExpressionStatement(assignExpr(fieldExpr, value)); } private Expression assignExpr(Expression fieldExpr, Expression value) { return new BinaryExpression(fieldExpr, ASSIGN, value); } private BooleanExpression equalsNullExpr(Expression argExpr) { return new BooleanExpression(new BinaryExpression(argExpr, COMPARE_EQUAL, ConstantExpression.NULL)); } private BooleanExpression isTrueExpr(Expression argExpr) { return new BooleanExpression(new BinaryExpression(argExpr, COMPARE_EQUAL, ConstantExpression.TRUE)); } private BooleanExpression isZeroExpr(Expression expr) { return new BooleanExpression(new BinaryExpression(expr, COMPARE_EQUAL, new ConstantExpression(Integer.valueOf(0)))); } private BooleanExpression isOneExpr(Expression expr) { return new BooleanExpression(new BinaryExpression(expr, COMPARE_EQUAL, new ConstantExpression(Integer.valueOf(1)))); } private BooleanExpression notEqualsExpr(PropertyNode pNode, Expression other) { final Expression fieldExpr = new FieldExpression(pNode.getField()); final Expression otherExpr = new PropertyExpression(other, pNode.getField().getName()); return new BooleanExpression(new BinaryExpression(fieldExpr, COMPARE_NOT_EQUAL, otherExpr)); } private BooleanExpression identicalExpr(Expression self, Expression other) { return new BooleanExpression(new BinaryExpression(self, COMPARE_IDENTICAL, other)); } private Expression findArg(String fName) { return new PropertyExpression(new VariableExpression("args"), fName); } private void adjustPropertyForImmutability(PropertyNode pNode, List<PropertyNode> newNodes) { final FieldNode fNode = pNode.getField(); fNode.setModifiers((pNode.getModifiers() & (~ACC_PUBLIC)) | ACC_FINAL | ACC_PRIVATE); adjustPropertyNode(pNode, createGetterBody(fNode)); newNodes.add(pNode); } private void adjustPropertyNode(PropertyNode pNode, Statement getterBody) { pNode.setSetterBlock(null); pNode.setGetterBlock(getterBody); } private Statement createGetterBody(FieldNode fNode) { BlockStatement body = new BlockStatement(); final ClassNode fieldType = fNode.getType(); final Statement statement; if (fieldType.isArray() || implementsInterface(fieldType, CLONEABLE_TYPE)) { statement = createGetterBodyArrayOrCloneable(fNode); } else if (fieldType.isDerivedFrom(DATE_TYPE)) { statement = createGetterBodyDate(fNode); } else { statement = createGetterBodyDefault(fNode); } body.addStatement(statement); return body; } private Statement createGetterBodyDefault(FieldNode fNode) { final Expression fieldExpr = new FieldExpression(fNode); return new ExpressionStatement(fieldExpr); } private static String createErrorMessage(String fieldName, String typeName, String mode) { return "Possible mutable field '" + fieldName + "' of type '" + typeName + "' found while " + mode + " " + MY_TYPE_NAME + " class."; } private Statement createGetterBodyArrayOrCloneable(FieldNode fNode) { final Expression fieldExpr = new FieldExpression(fNode); final Expression expression = cloneArrayOrCloneableExpr(fieldExpr); return safeExpression(fieldExpr, expression); } private Expression cloneArrayOrCloneableExpr(Expression fieldExpr) { return new MethodCallExpression(fieldExpr, "clone", MethodCallExpression.NO_ARGUMENTS); } private Expression cloneCollectionExpr(Expression fieldExpr) { return new StaticMethodCallExpression(DGM_TYPE, "asImmutable", fieldExpr); } private Statement createGetterBodyDate(FieldNode fNode) { final Expression fieldExpr = new FieldExpression(fNode); final Expression expression = cloneDateExpr(fieldExpr); return safeExpression(fieldExpr, expression); } private Statement safeExpression(Expression fieldExpr, Expression expression) { return new IfStatement( equalsNullExpr(fieldExpr), new ExpressionStatement(fieldExpr), new ExpressionStatement(expression)); } public static Object checkImmutable(String fieldName, Object field) { if (field == null || field instanceof Enum || inImmutableList(field.getClass())) return field; if (field instanceof Collection) return DefaultGroovyMethods.asImmutable((Collection) field); if (field.getClass().getAnnotation(MY_CLASS) != null) return field; final String typeName = field.getClass().getName(); throw new RuntimeException(createErrorMessage(fieldName, typeName, "constructing")); } }
true
true
public void visit(ASTNode[] nodes, SourceUnit source) { if (!(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: wrong types: $node.class / $parent.class"); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; List<PropertyNode> newNodes = new ArrayList<PropertyNode>(); if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; String cName = cNode.getName(); if (cNode.isInterface()) { throw new RuntimeException("Error processing interface '" + cName + "'. " + MY_TYPE_NAME + " not allowed for interfaces."); } if ((cNode.getModifiers() & ACC_FINAL) == 0) { throw new RuntimeException("Error processing class '" + cName + "'. " + MY_TYPE_NAME + " classes must be final."); } final List<PropertyNode> pList = cNode.getProperties(); for (PropertyNode pNode : pList) { adjustPropertyForImmutability(pNode, newNodes); } for (PropertyNode pNode : newNodes) { pList.remove(pNode); addProperty(cNode, pNode); } final List<FieldNode> fList = cNode.getFields(); for (FieldNode fNode : fList) { ensureNotPublic(cName, fNode); } createConstructor(cNode); createHashCode(cNode); createEquals(cNode); createToString(cNode); } }
public void visit(ASTNode[] nodes, SourceUnit source) { if (nodes.length != 2 || !(nodes[0] instanceof AnnotationNode) || !(nodes[1] instanceof AnnotatedNode)) { throw new RuntimeException("Internal error: expecting [AnnotationNode, AnnotatedClass] but got: " + Arrays.asList(nodes)); } AnnotatedNode parent = (AnnotatedNode) nodes[1]; AnnotationNode node = (AnnotationNode) nodes[0]; if (!MY_TYPE.equals(node.getClassNode())) return; List<PropertyNode> newNodes = new ArrayList<PropertyNode>(); if (parent instanceof ClassNode) { ClassNode cNode = (ClassNode) parent; String cName = cNode.getName(); if (cNode.isInterface()) { throw new RuntimeException("Error processing interface '" + cName + "'. " + MY_TYPE_NAME + " not allowed for interfaces."); } if ((cNode.getModifiers() & ACC_FINAL) == 0) { throw new RuntimeException("Error processing class '" + cName + "'. " + MY_TYPE_NAME + " classes must be final."); } final List<PropertyNode> pList = cNode.getProperties(); for (PropertyNode pNode : pList) { adjustPropertyForImmutability(pNode, newNodes); } for (PropertyNode pNode : newNodes) { pList.remove(pNode); addProperty(cNode, pNode); } final List<FieldNode> fList = cNode.getFields(); for (FieldNode fNode : fList) { ensureNotPublic(cName, fNode); } createConstructor(cNode); createHashCode(cNode); createEquals(cNode); createToString(cNode); } }
diff --git a/opentaps/opentaps-common/src/base/org/opentaps/common/widget/screen/ScreenHelper.java b/opentaps/opentaps-common/src/base/org/opentaps/common/widget/screen/ScreenHelper.java index a89614e95..a6f4cdfe1 100644 --- a/opentaps/opentaps-common/src/base/org/opentaps/common/widget/screen/ScreenHelper.java +++ b/opentaps/opentaps-common/src/base/org/opentaps/common/widget/screen/ScreenHelper.java @@ -1,114 +1,114 @@ /* * Copyright (c) 2006 - 2009 Open Source Strategies, Inc. * * Opentaps is free software: you can redistribute it and/or modify it * under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Opentaps is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Opentaps. If not, see <http://www.gnu.org/licenses/>. */ /******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. *******************************************************************************/ /* This file has been modified by Open Source Strategies, Inc. */ package org.opentaps.common.widget.screen; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.Locale; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import org.ofbiz.base.util.GeneralException; import org.ofbiz.base.util.collections.MapStack; import org.ofbiz.entity.Delegator; import org.ofbiz.entity.GenericValue; import org.ofbiz.security.Security; import org.ofbiz.service.DispatchContext; import org.ofbiz.service.LocalDispatcher; import org.ofbiz.widget.html.HtmlScreenRenderer; import org.ofbiz.widget.screen.ModelScreen; import org.ofbiz.widget.screen.ScreenFactory; import org.ofbiz.widget.screen.ScreenRenderer; import org.ofbiz.widget.screen.ScreenStringRenderer; import org.xml.sax.SAXException; /** * Utility methods for working with screen widgets. * * @author <a href="mailto:[email protected]">Chris Liberty</a> * @version $Rev$ */ public class ScreenHelper { /** * Renders a screen widget as text. * @param screenLocation location in component:// notation * @param dctx a <code>DispatchContext</code> value * @return Rendered contents of the screen as text * @exception GeneralException if an error occurs * @exception IOException if an error occurs * @exception SAXException if an error occurs * @exception ParserConfigurationException if an error occurs */ public static String renderScreenLocationAsText(String screenLocation, DispatchContext dctx, Map<String, Object> screenContext, Map<String, Object> screenParameters) throws GeneralException, IOException, SAXException, ParserConfigurationException { return renderScreenLocationAsText(screenLocation, dctx.getDelegator(), dctx.getDispatcher(), dctx.getSecurity(), screenContext, screenParameters); } /** * Renders a screen widget as text. * @param screenLocation location in component:// notation * @param delegator a <code>Delegator</code> value * @param dispatcher a <code>LocalDispatcher</code> value * @param security a <code>Security</code> value * @return Rendered contents of the screen as text * @exception GeneralException if an error occurs * @exception IOException if an error occurs * @exception SAXException if an error occurs * @exception ParserConfigurationException if an error occurs */ public static String renderScreenLocationAsText(String screenLocation, Delegator delegator, LocalDispatcher dispatcher, Security security, Map<String, Object> screenContext, Map<String, Object> screenParameters) throws GeneralException, IOException, SAXException, ParserConfigurationException { // Construct a new writer and use it to construct a new ScreenRenderer instead of using // any ScreenRenderer that might exist in the context, so that output from any nested calls to // ${screens.render(...)} is captured Writer writer = new StringWriter(); ScreenRenderer screens = new ScreenRenderer(writer, MapStack.<String>create(screenContext), new HtmlScreenRenderer()); - ScreenRenderer.populateBasicContext(MapStack.<String>create(screenContext), screens, screenParameters, delegator, dispatcher, security, (Locale) screenContext.get("locale"), (GenericValue) screenContext.get("userLogin")); + ScreenRenderer.populateBasicContext(MapStack.<String>create(screenContext), screens, screenParameters, delegator, dispatcher, dispatcher.getAuthorization(), security, (Locale) screenContext.get("locale"), (GenericValue) screenContext.get("userLogin")); // Get the screen and render it ScreenStringRenderer renderer = screens.getScreenStringRenderer(); ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(screenLocation); modelScreen.renderScreenString(writer, screenContext, renderer); // Return the rendered text return writer.toString(); } }
true
true
public static String renderScreenLocationAsText(String screenLocation, Delegator delegator, LocalDispatcher dispatcher, Security security, Map<String, Object> screenContext, Map<String, Object> screenParameters) throws GeneralException, IOException, SAXException, ParserConfigurationException { // Construct a new writer and use it to construct a new ScreenRenderer instead of using // any ScreenRenderer that might exist in the context, so that output from any nested calls to // ${screens.render(...)} is captured Writer writer = new StringWriter(); ScreenRenderer screens = new ScreenRenderer(writer, MapStack.<String>create(screenContext), new HtmlScreenRenderer()); ScreenRenderer.populateBasicContext(MapStack.<String>create(screenContext), screens, screenParameters, delegator, dispatcher, security, (Locale) screenContext.get("locale"), (GenericValue) screenContext.get("userLogin")); // Get the screen and render it ScreenStringRenderer renderer = screens.getScreenStringRenderer(); ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(screenLocation); modelScreen.renderScreenString(writer, screenContext, renderer); // Return the rendered text return writer.toString(); }
public static String renderScreenLocationAsText(String screenLocation, Delegator delegator, LocalDispatcher dispatcher, Security security, Map<String, Object> screenContext, Map<String, Object> screenParameters) throws GeneralException, IOException, SAXException, ParserConfigurationException { // Construct a new writer and use it to construct a new ScreenRenderer instead of using // any ScreenRenderer that might exist in the context, so that output from any nested calls to // ${screens.render(...)} is captured Writer writer = new StringWriter(); ScreenRenderer screens = new ScreenRenderer(writer, MapStack.<String>create(screenContext), new HtmlScreenRenderer()); ScreenRenderer.populateBasicContext(MapStack.<String>create(screenContext), screens, screenParameters, delegator, dispatcher, dispatcher.getAuthorization(), security, (Locale) screenContext.get("locale"), (GenericValue) screenContext.get("userLogin")); // Get the screen and render it ScreenStringRenderer renderer = screens.getScreenStringRenderer(); ModelScreen modelScreen = ScreenFactory.getScreenFromLocation(screenLocation); modelScreen.renderScreenString(writer, screenContext, renderer); // Return the rendered text return writer.toString(); }
diff --git a/src/ar/edu/it/itba/pdc/v2/implementations/utils/DecoderImpl.java b/src/ar/edu/it/itba/pdc/v2/implementations/utils/DecoderImpl.java index 5c0b2df..07422a9 100755 --- a/src/ar/edu/it/itba/pdc/v2/implementations/utils/DecoderImpl.java +++ b/src/ar/edu/it/itba/pdc/v2/implementations/utils/DecoderImpl.java @@ -1,470 +1,473 @@ package ar.edu.it.itba.pdc.v2.implementations.utils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.Map; import ar.edu.it.itba.pdc.v2.implementations.HTML; import ar.edu.it.itba.pdc.v2.implementations.RebuiltHeader; import ar.edu.it.itba.pdc.v2.interfaces.Configurator; import ar.edu.it.itba.pdc.v2.interfaces.Decoder; import ar.edu.it.itba.pdc.v2.interfaces.HTTPHeaders; public class DecoderImpl implements Decoder { private boolean read = true; private int index = 0; private HTTPHeaders headers = null; private String fileName; private int keepReadingBytes = 0; private boolean isImage = false; private boolean isText = false; private boolean generatingKeep = false; private String keepReadingBytesHexa; private Configurator configurator; public DecoderImpl(int buffSize) { headers = new HTTPPacket(); } public void decode(byte[] bytes, int count) { // headers.parse(bytes, count); String length; if (headers.getHeader("Method").contains("GET")) { read = false; } length = headers.getHeader("Content-Length"); // remove spaces if (length != null) { length = length.replaceAll(" ", ""); int expectedRead = Integer.parseInt(length); if (expectedRead >= headers.getReadBytes()) { if (!headers.contentExpected()) read = false; read = true; } else { read = false; } } else { String transferEncoding = headers.getHeader("Transfer-Encoding"); if (transferEncoding != null && transferEncoding.contains("chunked")) { } } } public byte[] getExtra(byte[] data, int count) { String read = null; read = new String(data).substring(0, count); String[] lines = read.split("\r\n"); boolean found = false; ByteBuffer buffer = ByteBuffer.allocate(count - headers.getReadBytes()); for (int i = 0; i < lines.length; i++) { if (found) { if (i < lines.length - 1) lines[i] += "\r\n"; buffer.put(lines[i].getBytes()); } if (lines[i].equals("")) { found = true; } } return buffer.array(); } public boolean keepReading() { return read; } private boolean isChunked() { return (headers.getHeader("Transfer-Encoding") != null) && (headers.getHeader("Transfer-Encoding").contains("chunked")); } public int getBufferSize() { return index; } public String getHeader(String header) { return headers.getHeader(header); } private void analizeMediaType() { if (headers.getHeader("Content-Type") != null) { isImage = headers.getHeader("Content-Type").contains("image/"); isText = headers.getHeader("Content-Type").contains("text/plain"); } } public boolean applyTransformations() { this.analizeMediaType(); return configurator.applyTransformation() && (isImage || isText); } public void applyRestrictions(byte[] bytes, int count, HTTPHeaders requestHeaders) { this.analizeMediaType(); if (isImage && configurator.applyRotations()) { if (fileName == null) { String path[] = requestHeaders.getHeader("RequestedURI").split( "/"); File f = new File("/tmp/prueba"); f.mkdir(); if (path[path.length - 1].length() < 10) fileName = "/tmp/prueba/" + String.valueOf(System.currentTimeMillis()) + Thread.currentThread().getId() + path[path.length - 1]; else { fileName = "/tmp/prueba/" + path[path.length - 1].substring(0, 6) + String.valueOf(System.currentTimeMillis()) + Thread.currentThread().getId() + "." + headers.getHeader("Content-Type").split("/")[1] .split(";")[0]; } } try { FileOutputStream fw = new FileOutputStream(fileName, true); fw.write(bytes, 0, count); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (isText && configurator.applyTextTransformation()) { if (fileName == null) { String path[] = requestHeaders.getHeader("RequestedURI").split( "/"); File f = new File("/tmp/prueba"); f.mkdir(); if (path[path.length - 1].length() < 10) fileName = "/tmp/prueba/" + path[path.length - 1] + ".txt"; else { fileName = "/tmp/prueba/" + path[path.length - 1].substring(0, 6) + "." + "txt"; } } try { FileOutputStream fw = new FileOutputStream(fileName, true); fw.write(bytes, 0, count); fw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public boolean isImage() { return isImage; } public boolean isText() { return isText; } public synchronized byte[] getRotatedImage() throws IOException { Transformations im = new Transformations(); // InputStream is = null; // try { // is = new BufferedInputStream(new FileInputStream((fileName))); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } byte[] modified = im.rotate(fileName, 180); // try { // is.close(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } fileName = null; return modified; } public byte[] getTransformed() { Transformations im = new Transformations(); InputStream is = null; try { System.out.println(fileName); is = new BufferedInputStream(new FileInputStream((fileName))); } catch (FileNotFoundException e) { e.printStackTrace(); } byte[] modified = null; try { modified = im.transformL33t(is); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fileName = null; return modified; } public void applyTransformations(byte[] bytes, int count) { // TODO Auto-generated method stub } public void applyFilters() { // TODO Auto-generated method stub } public boolean completeHeaders(byte[] bytes, int count) { String read = null; read = new String(bytes).substring(0, count); String[] lines = read.split("\r\n"); for (String line : lines) { if (line.equals("")) { return true; } } return false; } public synchronized void analize(byte[] bytes, int count) { if (!headers.contentExpected()) { keepReadingBytes = 0; read = false; return; } - String[] array = headers.getHeader("Content-Type").split(";"); + String[] array = null; String charset; - if (array.length >= 2) + if (headers.getHeader("Content-Type") != null) { + array = headers.getHeader("Content-Type").split(";"); + } + if (array != null && array.length >= 2) charset = array[1].split("=")[1]; else charset = "ISO-8859-1"; CharBuffer charBuf = Charset.forName(charset).decode( ByteBuffer.wrap(bytes, 0, count)); String converted = new String(charBuf.array()); if (isChunked()) { String[] chunks = null; chunks = converted.split("\r\n"); for (int j = 0; j < chunks.length; j++) { if (keepReadingBytes == 0) { Integer sizeLine = null; try { sizeLine = Integer.parseInt(chunks[j], 16); keepReadingBytesHexa = chunks[j]; } catch (NumberFormatException e) { sizeLine = 0; } if (sizeLine == 0) { read = false; } keepReadingBytes = sizeLine; generatingKeep = true; } else { if (generatingKeep && j == 0) { try { Integer.parseInt(chunks[0], 16); keepReadingBytesHexa += chunks[0]; keepReadingBytes = Integer.parseInt( keepReadingBytesHexa, 16); continue; } catch (NumberFormatException e) { } } keepReadingBytes -= chunks[j].getBytes().length; if (keepReadingBytes < 0) { System.out .println("ESTO NO DEBERIA PASAR, keepReadingBytes <0"); } generatingKeep = false; } } } else if (headers.getHeader("Content-Length") != null) { if (keepReadingBytes == 0) { keepReadingBytes = Integer.parseInt(headers.getHeader( "Content-Length").replaceAll(" ", "")); } keepReadingBytes -= count; if (keepReadingBytes == 0) read = false; } else { read = true; } } public void reset() { read = true; index = 0; headers = new HTTPPacket(); fileName = null; keepReadingBytes = 0; generatingKeep = false; keepReadingBytesHexa = ""; isImage = false; isText = false; } public void parseHeaders(byte[] data, int count) { headers.parseHeaders(data, count); } public HTTPHeaders getHeaders() { return headers; } public RebuiltHeader rebuildHeaders() { Map<String, String> allHeaders = headers.getAllHeaders(); String sb = ""; allHeaders.remove("Accept-Encoding"); allHeaders.remove("Proxy-Connection"); allHeaders.put("Accept-Encoding", "identity"); sb += allHeaders.get("Method") + " "; sb += allHeaders.get("RequestedURI") + " "; sb += allHeaders.get("HTTPVersion") + "\r\n"; for (String key : allHeaders.keySet()) { if (!key.equals("Method") && !key.equals("RequestedURI") && !key.equals("HTTPVersion")) sb += (key + ":" + allHeaders.get(key) + "\r\n"); } // allHeaders.put("Via", " mu0Proxy"); // sb += "Via:" + allHeaders.get("Via") + "\r\n"; sb += ("\r\n"); return new RebuiltHeader(sb.getBytes(), sb.length()); } public void setConfigurator(Configurator configurator) { this.configurator = configurator; } public RebuiltHeader generateBlockedHeader(String cause) { HTTPHeaders newHeaders = new HTTPPacket(); if (cause.equals("URI")) { newHeaders.addHeader("StatusCode", "666"); newHeaders.addHeader("Reason", "Blocked URL"); } else if (cause.equals("CONTENT-TYPE")) { newHeaders.addHeader("StatusCode", "777"); newHeaders.addHeader("Reason", "Blocked MediaType"); } else if (cause.equals("IP")) { newHeaders.addHeader("StatusCode", "888"); newHeaders.addHeader("Reason", "Blocked IP"); } else if (cause.equals("MAXSIZE")) { newHeaders.addHeader("StatusCode", "999"); newHeaders.addHeader("Reason", "Blocked File Size"); } newHeaders.addHeader("HTTPVersion", "HTTP/1.1"); newHeaders.addHeader("Via", " mu0"); newHeaders.addHeader("Content-Type", " text/html; charset=iso-8859-1"); newHeaders.addHeader("Connection", " close"); Map<String, String> allHeaders = newHeaders.getAllHeaders(); String sb = ""; sb += allHeaders.get("HTTPVersion") + " "; sb += allHeaders.get("StatusCode") + " "; sb += allHeaders.get("Reason") + "\r\n"; for (String key : allHeaders.keySet()) { if (!key.equals("HTTPVersion") && !key.equals("StatusCode") && !key.equals("Reason")) sb += (key + ":" + allHeaders.get(key) + "\r\n"); } sb += ("\r\n"); return new RebuiltHeader(sb.getBytes(), sb.length()); } public HTML generateBlockedHTML(String cause) { String html = ""; if (cause.equals("URI")) { html = "<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>" + "<html><head>" + "<title>666 URL bloqueada</title>" + "</head><body>" + "<h1>URL Bloqueada</h1>" + "<p>Su proxy bloqueo esta url<br />" + "</p>" + "</body></html>"; } else if (cause.equals("CONTENT-TYPE")) { html = "<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>" + "<html><head>" + "<title>777 MediaType bloqueada</title>" + "</head><body>" + "<h1>MediaType Bloqueada</h1>" + "<p>Su proxy bloqueo este tipo de archivos<br />" + "</p>" + "</body></html>"; } else if (cause.equals("IP")) { html = "<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>" + "<html><head>" + "<title>888 IP bloqueada</title>" + "</head><body>" + "<h1>IP Bloqueada</h1>" + "<p>Su proxy bloqueo esta IP<br />" + "</p>" + "</body></html>"; } else if (cause.equals("MAXSIZE")) { html = "<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>" + "<html><head>" + "<title>999 Tamano de archivo bloqueado</title>" + "</head><body>" + "<h1>Tamano de archivo Bloqueada</h1>" + "<p>Su proxy bloqueo archivos de este tamano<br />" + "</p>" + "</body></html>"; } return new HTML(html.getBytes(), html.length()); } public RebuiltHeader modifiedContentLength(int contentLength) { Map<String, String> allHeaders = headers.getAllHeaders(); String sb = ""; allHeaders.remove("Accept-Encoding"); allHeaders.remove("Proxy-Connection"); allHeaders.put("Accept-Encoding", "identity"); allHeaders.remove("Content-Length"); allHeaders.remove("Transfer-Encoding"); allHeaders.put("Content-Length", String.valueOf(contentLength)); sb += allHeaders.get("HTTPVersion") + " "; sb += allHeaders.get("StatusCode") + " "; sb += allHeaders.get("Reason") + "\r\n"; for (String key : allHeaders.keySet()) { if (!key.equals("Method") && !key.equals("RequestedURI") && !key.equals("HTTPVersion")) sb += (key + ":" + allHeaders.get(key) + "\r\n"); } // allHeaders.put("Via", " mu0Proxy"); // sb += "Via:" + allHeaders.get("Via") + "\r\n"; sb += ("\r\n"); return new RebuiltHeader(sb.getBytes(), sb.length()); } }
false
true
public synchronized void analize(byte[] bytes, int count) { if (!headers.contentExpected()) { keepReadingBytes = 0; read = false; return; } String[] array = headers.getHeader("Content-Type").split(";"); String charset; if (array.length >= 2) charset = array[1].split("=")[1]; else charset = "ISO-8859-1"; CharBuffer charBuf = Charset.forName(charset).decode( ByteBuffer.wrap(bytes, 0, count)); String converted = new String(charBuf.array()); if (isChunked()) { String[] chunks = null; chunks = converted.split("\r\n"); for (int j = 0; j < chunks.length; j++) { if (keepReadingBytes == 0) { Integer sizeLine = null; try { sizeLine = Integer.parseInt(chunks[j], 16); keepReadingBytesHexa = chunks[j]; } catch (NumberFormatException e) { sizeLine = 0; } if (sizeLine == 0) { read = false; } keepReadingBytes = sizeLine; generatingKeep = true; } else { if (generatingKeep && j == 0) { try { Integer.parseInt(chunks[0], 16); keepReadingBytesHexa += chunks[0]; keepReadingBytes = Integer.parseInt( keepReadingBytesHexa, 16); continue; } catch (NumberFormatException e) { } } keepReadingBytes -= chunks[j].getBytes().length; if (keepReadingBytes < 0) { System.out .println("ESTO NO DEBERIA PASAR, keepReadingBytes <0"); } generatingKeep = false; } } } else if (headers.getHeader("Content-Length") != null) { if (keepReadingBytes == 0) { keepReadingBytes = Integer.parseInt(headers.getHeader( "Content-Length").replaceAll(" ", "")); } keepReadingBytes -= count; if (keepReadingBytes == 0) read = false; } else { read = true; } }
public synchronized void analize(byte[] bytes, int count) { if (!headers.contentExpected()) { keepReadingBytes = 0; read = false; return; } String[] array = null; String charset; if (headers.getHeader("Content-Type") != null) { array = headers.getHeader("Content-Type").split(";"); } if (array != null && array.length >= 2) charset = array[1].split("=")[1]; else charset = "ISO-8859-1"; CharBuffer charBuf = Charset.forName(charset).decode( ByteBuffer.wrap(bytes, 0, count)); String converted = new String(charBuf.array()); if (isChunked()) { String[] chunks = null; chunks = converted.split("\r\n"); for (int j = 0; j < chunks.length; j++) { if (keepReadingBytes == 0) { Integer sizeLine = null; try { sizeLine = Integer.parseInt(chunks[j], 16); keepReadingBytesHexa = chunks[j]; } catch (NumberFormatException e) { sizeLine = 0; } if (sizeLine == 0) { read = false; } keepReadingBytes = sizeLine; generatingKeep = true; } else { if (generatingKeep && j == 0) { try { Integer.parseInt(chunks[0], 16); keepReadingBytesHexa += chunks[0]; keepReadingBytes = Integer.parseInt( keepReadingBytesHexa, 16); continue; } catch (NumberFormatException e) { } } keepReadingBytes -= chunks[j].getBytes().length; if (keepReadingBytes < 0) { System.out .println("ESTO NO DEBERIA PASAR, keepReadingBytes <0"); } generatingKeep = false; } } } else if (headers.getHeader("Content-Length") != null) { if (keepReadingBytes == 0) { keepReadingBytes = Integer.parseInt(headers.getHeader( "Content-Length").replaceAll(" ", "")); } keepReadingBytes -= count; if (keepReadingBytes == 0) read = false; } else { read = true; } }
diff --git a/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java b/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java index bd76b28ae..858e728e8 100644 --- a/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java +++ b/src/contributions/resources/policymanager/src/java/org/wyona/yanel/impl/resources/policymanager/PolicyManagerResource.java @@ -1,280 +1,282 @@ /* * Copyright 2007 Wyona */ package org.wyona.yanel.impl.resources.policymanager; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.Policy; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.User; import org.wyona.yanel.core.Resource; import org.wyona.yanel.impl.resources.BasicXMLResource; import org.wyona.yanel.impl.resources.policymanager.PolicyViewer; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Vector; import org.apache.log4j.Logger; /** * */ public class PolicyManagerResource extends BasicXMLResource { private static Logger log = Logger.getLogger(PolicyManager.class); private static String PARAMETER_EDIT_PATH = "policy-path"; private static String PARAMETER_USECASE = "yanel.policy"; /** * */ protected InputStream getContentXML(String viewId) throws Exception { // For example ?policy-path=/foo/bar.html String policyPath = request.getParameter(PARAMETER_EDIT_PATH); if (policyPath == null) { - log.error("No policy path specified! Please specify a policy path, e.g. ?policy-path=/foo/bar.html"); + log.warn("No policy path specified, e.g. ?policy-path=/foo/bar.html"); + log.warn("Request path used as default: " + getPath()); + policyPath = getPath(); } // For example ?yanel.policy=read String policyUsecase = "read"; if (request.getParameter(PARAMETER_USECASE) != null) { policyUsecase = request.getParameter(PARAMETER_USECASE); } Resource resToEditPolicy = getYanel().getResourceManager().getResource(getEnvironment(), getRealm(), policyPath); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(getPath()); StringBuffer sb = new StringBuffer(""); try { if (policyUsecase.equals("read")) { // Either order by usecases or identities String orderedByParam = request.getParameter("orderedBy"); int orderedBy = 0; if (orderedByParam != null) orderedBy = new java.lang.Integer(orderedByParam).intValue(); // Either show parent policies or do not show them boolean showParents = false; String showParentsParam = request.getParameter("showParents"); if (showParentsParam != null) showParents = new java.lang.Boolean(showParentsParam).booleanValue(); // Either show tabs or do not show them boolean showTabs = true; String showTabsParam = request.getParameter("showTabs"); if (showTabsParam != null) showTabs = new java.lang.Boolean(showTabsParam).booleanValue(); sb.append(PolicyViewer.getXHTMLView(resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath(), null, orderedBy, showParents, showTabs)); } else if (policyUsecase.equals("update")) { String getXML = request.getParameter("get"); String postXML = request.getParameter("post"); if (getXML != null && getXML.equals("identities")) { sb.append(getIdentitiesAndRightsAsXML(resToEditPolicy.getRealm().getIdentityManager(), resToEditPolicy.getRealm().getPolicyManager(), getRequestedLanguage())); } else if (getXML != null && getXML.equals("policy")) { sb.append(getPolicyAsXML(resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath())); } else if (postXML != null && postXML.equals("policy")) { try { writePolicy(request.getInputStream(), resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath()); sb.append("<?xml version=\"1.0\"?><saved/>"); } catch(Exception e) { log.error(e,e); sb.append("<?xml version=\"1.0\"?><not-saved>" + e.getMessage() + "</not-saved>"); } } else { String identitiesURL = "../.." + getPath() + "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;get=identities"; //String saveURL = "../.." + resToEditPolicy.getPath() + "?yanel.policy=update&post=policy"; String saveURL = "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;post=policy"; String cancelURL = org.wyona.commons.io.PathUtil.getName(resToEditPolicy.getPath()); if (resToEditPolicy.getPath().endsWith("/")) cancelURL = "./"; sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); sb.append("<title>Update Access Policy</title>"); sb.append("<link rel=\"stylesheet\" href=\"" + backToRealm + getYanel().getReservedPrefix() + "/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/style.css\" type=\"text/css\"/>"); sb.append("</head>"); sb.append("<body><h1>Update Access Policy</h1><p><script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"../.." + getPath() + "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;get=policy\", \"cancel-url\": \"" + cancelURL + "\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + backToRealm + getYanel().getReservedPrefix() + "/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script></p></body></html>"); } } else { - sb.append("<html><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>"); + sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>"); } } catch(Exception e) { log.error(e, e); throw new Exception(e.getMessage()); } return new ByteArrayInputStream(sb.toString().getBytes()); } /** * */ private String getIdentitiesAndRightsAsXML(IdentityManager im, PolicyManager pm, String language) { org.wyona.security.core.api.UserManager um = im.getUserManager(); org.wyona.security.core.api.GroupManager gm = im.getGroupManager(); StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<access-control xmlns=\"http://www.wyona.org/security/1.0\">"); try { User[] users = um.getUsers(); sb.append("<users>"); for (int i = 0; i < users.length; i++) { sb.append("<user id=\"" + users[i].getID() + "\">" + users[i].getName() + "</user>"); } sb.append("</users>"); org.wyona.security.core.api.Group[] groups = gm.getGroups(); sb.append("<groups>"); for (int i = 0; i < groups.length; i++) { sb.append("<group id=\"" + groups[i].getID() + "\">" + groups[i].getName() + "</group>"); } sb.append("</groups>"); sb.append("<rights>"); String[] rights = pm.getUsecases(); if (rights != null) { for (int i = 0; i < rights.length; i++) { sb.append("<right id=\"" + rights[i] + "\">" + pm.getUsecaseLabel(rights[i], language) + "</right>"); } } sb.append("</rights>"); } catch (Exception e) { log.error(e, e); sb.append("<exception>" + e.getMessage() + "</exception>"); } sb.append("</access-control>"); return sb.toString(); } /** * */ private String getPolicyAsXML(PolicyManager pm, String path) { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); try { Policy policy = pm.getPolicy(path, false); if (policy == null) { sb.append("<policy xmlns=\"http://www.wyona.org/security/1.0\" use-inherited-policies=\"false\">"); log.warn("No policy yet for path: " + path + " (Return empty policy)"); } else { sb.append("<policy xmlns=\"http://www.wyona.org/security/1.0\" use-inherited-policies=\"" + policy.useInheritedPolicies() + "\">"); sb.append(getPolicyIdentities(policy)); sb.append(getPolicyGroups(policy)); } } catch(Exception e) { log.error(e, e); sb.append("<policy xmlns=\"http://www.wyona.org/security/1.0\">"); sb.append("<exception>" + e.getMessage() + "</exception>"); } sb.append("</policy>"); return sb.toString(); } /** * Get users (TODO: Move this code into the security package) */ static public StringBuffer getPolicyIdentities(Policy p) { Vector world = new Vector(); java.util.HashMap users = new java.util.HashMap(); org.wyona.security.core.UsecasePolicy[] up = p.getUsecasePolicies(); if (up != null && up.length > 0) { for (int i = 0; i < up.length; i++) { org.wyona.security.core.IdentityPolicy[] idps = up[i].getIdentityPolicies(); for (int j = 0; j < idps.length; j++) { //log.debug("Usecase Identity Policy: " + up[i].getName() + ", " + idps[j].getIdentity().getUsername() + ", " + idps[j].getPermission()); if (idps[j].getIdentity().isWorld()) { world.add(up[i].getName()); } else { Vector userRights; if ((userRights = (Vector) users.get(idps[j].getIdentity().getUsername())) != null) { log.debug("User has already been added: " + idps[j].getIdentity().getUsername()); } else { userRights = new Vector(); users.put(idps[j].getIdentity().getUsername(), userRights); } if (idps[j].getPermission()) { userRights.add(up[i].getName()); } } } } } else { log.warn("No policy usecases!"); } StringBuffer sb = new StringBuffer(); //sb.append("<li>WORLD (" + getCommaSeparatedList(world) + ")</li>"); java.util.Iterator userIterator = users.keySet().iterator(); while (userIterator.hasNext()) { String userName = (String) userIterator.next(); sb.append("<user id=\""+userName+"\">"); Vector rights = (Vector) users.get(userName); for (int k = 0; k < rights.size(); k++) { // TODO: Do not hardcode permission sb.append("<right id=\"" + (String) rights.elementAt(k) + "\" permission=\"true\"/>"); } sb.append("</user>"); } return sb; } /** * Get groups (TODO: Move this code into the security package) */ static public StringBuffer getPolicyGroups(Policy p) { Vector world = new Vector(); java.util.HashMap groups = new java.util.HashMap(); org.wyona.security.core.UsecasePolicy[] up = p.getUsecasePolicies(); if (up != null && up.length > 0) { for (int i = 0; i < up.length; i++) { org.wyona.security.core.GroupPolicy[] ids = up[i].getGroupPolicies(); for (int j = 0; j < ids.length; j++) { Vector groupRights; if ((groupRights = (Vector) groups.get(ids[j].getId())) != null) { log.debug("Group has already been added: " + ids[j].getId()); } else { groupRights = new Vector(); groups.put(ids[j].getId(), groupRights); } if (ids[j].getPermission()) { groupRights.add(up[i].getName()); } } } } else { log.warn("No policy usecases!"); } StringBuffer sb = new StringBuffer(); java.util.Iterator userIterator = groups.keySet().iterator(); while (userIterator.hasNext()) { String userName = (String) userIterator.next(); sb.append("<group id=\""+userName+"\">"); Vector rights = (Vector) groups.get(userName); for (int k = 0; k < rights.size(); k++) { //TODO: Do not hardcode permission! sb.append("<right id=\"" + (String) rights.elementAt(k) + "\" permission=\"true\"/>"); } sb.append("</group>"); } return sb; } /** * Write/Save policy */ private void writePolicy(InputStream policyAsInputStream, PolicyManager pm, String path) throws Exception { Policy policy = new PolicyParser().parseXML(policyAsInputStream); pm.setPolicy(path, policy); } }
false
true
protected InputStream getContentXML(String viewId) throws Exception { // For example ?policy-path=/foo/bar.html String policyPath = request.getParameter(PARAMETER_EDIT_PATH); if (policyPath == null) { log.error("No policy path specified! Please specify a policy path, e.g. ?policy-path=/foo/bar.html"); } // For example ?yanel.policy=read String policyUsecase = "read"; if (request.getParameter(PARAMETER_USECASE) != null) { policyUsecase = request.getParameter(PARAMETER_USECASE); } Resource resToEditPolicy = getYanel().getResourceManager().getResource(getEnvironment(), getRealm(), policyPath); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(getPath()); StringBuffer sb = new StringBuffer(""); try { if (policyUsecase.equals("read")) { // Either order by usecases or identities String orderedByParam = request.getParameter("orderedBy"); int orderedBy = 0; if (orderedByParam != null) orderedBy = new java.lang.Integer(orderedByParam).intValue(); // Either show parent policies or do not show them boolean showParents = false; String showParentsParam = request.getParameter("showParents"); if (showParentsParam != null) showParents = new java.lang.Boolean(showParentsParam).booleanValue(); // Either show tabs or do not show them boolean showTabs = true; String showTabsParam = request.getParameter("showTabs"); if (showTabsParam != null) showTabs = new java.lang.Boolean(showTabsParam).booleanValue(); sb.append(PolicyViewer.getXHTMLView(resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath(), null, orderedBy, showParents, showTabs)); } else if (policyUsecase.equals("update")) { String getXML = request.getParameter("get"); String postXML = request.getParameter("post"); if (getXML != null && getXML.equals("identities")) { sb.append(getIdentitiesAndRightsAsXML(resToEditPolicy.getRealm().getIdentityManager(), resToEditPolicy.getRealm().getPolicyManager(), getRequestedLanguage())); } else if (getXML != null && getXML.equals("policy")) { sb.append(getPolicyAsXML(resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath())); } else if (postXML != null && postXML.equals("policy")) { try { writePolicy(request.getInputStream(), resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath()); sb.append("<?xml version=\"1.0\"?><saved/>"); } catch(Exception e) { log.error(e,e); sb.append("<?xml version=\"1.0\"?><not-saved>" + e.getMessage() + "</not-saved>"); } } else { String identitiesURL = "../.." + getPath() + "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;get=identities"; //String saveURL = "../.." + resToEditPolicy.getPath() + "?yanel.policy=update&post=policy"; String saveURL = "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;post=policy"; String cancelURL = org.wyona.commons.io.PathUtil.getName(resToEditPolicy.getPath()); if (resToEditPolicy.getPath().endsWith("/")) cancelURL = "./"; sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); sb.append("<title>Update Access Policy</title>"); sb.append("<link rel=\"stylesheet\" href=\"" + backToRealm + getYanel().getReservedPrefix() + "/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/style.css\" type=\"text/css\"/>"); sb.append("</head>"); sb.append("<body><h1>Update Access Policy</h1><p><script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"../.." + getPath() + "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;get=policy\", \"cancel-url\": \"" + cancelURL + "\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + backToRealm + getYanel().getReservedPrefix() + "/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script></p></body></html>"); } } else { sb.append("<html><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>"); } } catch(Exception e) { log.error(e, e); throw new Exception(e.getMessage()); } return new ByteArrayInputStream(sb.toString().getBytes()); }
protected InputStream getContentXML(String viewId) throws Exception { // For example ?policy-path=/foo/bar.html String policyPath = request.getParameter(PARAMETER_EDIT_PATH); if (policyPath == null) { log.warn("No policy path specified, e.g. ?policy-path=/foo/bar.html"); log.warn("Request path used as default: " + getPath()); policyPath = getPath(); } // For example ?yanel.policy=read String policyUsecase = "read"; if (request.getParameter(PARAMETER_USECASE) != null) { policyUsecase = request.getParameter(PARAMETER_USECASE); } Resource resToEditPolicy = getYanel().getResourceManager().getResource(getEnvironment(), getRealm(), policyPath); String backToRealm = org.wyona.yanel.core.util.PathUtil.backToRealm(getPath()); StringBuffer sb = new StringBuffer(""); try { if (policyUsecase.equals("read")) { // Either order by usecases or identities String orderedByParam = request.getParameter("orderedBy"); int orderedBy = 0; if (orderedByParam != null) orderedBy = new java.lang.Integer(orderedByParam).intValue(); // Either show parent policies or do not show them boolean showParents = false; String showParentsParam = request.getParameter("showParents"); if (showParentsParam != null) showParents = new java.lang.Boolean(showParentsParam).booleanValue(); // Either show tabs or do not show them boolean showTabs = true; String showTabsParam = request.getParameter("showTabs"); if (showTabsParam != null) showTabs = new java.lang.Boolean(showTabsParam).booleanValue(); sb.append(PolicyViewer.getXHTMLView(resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath(), null, orderedBy, showParents, showTabs)); } else if (policyUsecase.equals("update")) { String getXML = request.getParameter("get"); String postXML = request.getParameter("post"); if (getXML != null && getXML.equals("identities")) { sb.append(getIdentitiesAndRightsAsXML(resToEditPolicy.getRealm().getIdentityManager(), resToEditPolicy.getRealm().getPolicyManager(), getRequestedLanguage())); } else if (getXML != null && getXML.equals("policy")) { sb.append(getPolicyAsXML(resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath())); } else if (postXML != null && postXML.equals("policy")) { try { writePolicy(request.getInputStream(), resToEditPolicy.getRealm().getPolicyManager(), resToEditPolicy.getPath()); sb.append("<?xml version=\"1.0\"?><saved/>"); } catch(Exception e) { log.error(e,e); sb.append("<?xml version=\"1.0\"?><not-saved>" + e.getMessage() + "</not-saved>"); } } else { String identitiesURL = "../.." + getPath() + "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;get=identities"; //String saveURL = "../.." + resToEditPolicy.getPath() + "?yanel.policy=update&post=policy"; String saveURL = "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;post=policy"; String cancelURL = org.wyona.commons.io.PathUtil.getName(resToEditPolicy.getPath()); if (resToEditPolicy.getPath().endsWith("/")) cancelURL = "./"; sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head>"); sb.append("<title>Update Access Policy</title>"); sb.append("<link rel=\"stylesheet\" href=\"" + backToRealm + getYanel().getReservedPrefix() + "/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/style.css\" type=\"text/css\"/>"); sb.append("</head>"); sb.append("<body><h1>Update Access Policy</h1><p><script language=\"javascript\">var getURLs = {\"identities-url\": \"" + identitiesURL + "\", \"policy-url\": \"../.." + getPath() + "?policy-path=" + policyPath + "&amp;yanel.policy=update&amp;get=policy\", \"cancel-url\": \"" + cancelURL + "\", \"save-url\": \"" + saveURL + "\"};</script><script language=\"javascript\" src=\"" + backToRealm + getYanel().getReservedPrefix() + "/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor/org.wyona.security.gwt.accesspolicyeditor.AccessPolicyEditor.nocache.js\"></script></p></body></html>"); } } else { sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\"><body>Policy usecase not implemented yet: " + policyUsecase + "</body></html>"); } } catch(Exception e) { log.error(e, e); throw new Exception(e.getMessage()); } return new ByteArrayInputStream(sb.toString().getBytes()); }
diff --git a/psl-rewriter/src/main/java/edu/umd/cs/linqs/embers/JointPredictionTester.java b/psl-rewriter/src/main/java/edu/umd/cs/linqs/embers/JointPredictionTester.java index 290f3b6..c056b18 100644 --- a/psl-rewriter/src/main/java/edu/umd/cs/linqs/embers/JointPredictionTester.java +++ b/psl-rewriter/src/main/java/edu/umd/cs/linqs/embers/JointPredictionTester.java @@ -1,36 +1,36 @@ package edu.umd.cs.linqs.embers; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class JointPredictionTester { public static void main(String [] args) { - if (args.length < 3) + if (args.length < 2) throw new IllegalArgumentException("Usage: JointPredictionTester <input_json_file> <output_json_file> <optional_model>"); try { Scanner scanner = new Scanner(new File(args[0])); FileWriter fw; fw = new FileWriter(new File(args[1])); - PSLJointRewriter rewriter = new PSLJointRewriter(args[2]); + PSLJointRewriter rewriter = (args.length < 3)? new PSLJointRewriter(): new PSLJointRewriter(args[2]); while (scanner.hasNext()) { String line = scanner.nextLine(); String result = rewriter.process(line); fw.write(result + "\n"); } fw.close(); } catch (IOException e) { e.printStackTrace(); } } }
false
true
public static void main(String [] args) { if (args.length < 3) throw new IllegalArgumentException("Usage: JointPredictionTester <input_json_file> <output_json_file> <optional_model>"); try { Scanner scanner = new Scanner(new File(args[0])); FileWriter fw; fw = new FileWriter(new File(args[1])); PSLJointRewriter rewriter = new PSLJointRewriter(args[2]); while (scanner.hasNext()) { String line = scanner.nextLine(); String result = rewriter.process(line); fw.write(result + "\n"); } fw.close(); } catch (IOException e) { e.printStackTrace(); } }
public static void main(String [] args) { if (args.length < 2) throw new IllegalArgumentException("Usage: JointPredictionTester <input_json_file> <output_json_file> <optional_model>"); try { Scanner scanner = new Scanner(new File(args[0])); FileWriter fw; fw = new FileWriter(new File(args[1])); PSLJointRewriter rewriter = (args.length < 3)? new PSLJointRewriter(): new PSLJointRewriter(args[2]); while (scanner.hasNext()) { String line = scanner.nextLine(); String result = rewriter.process(line); fw.write(result + "\n"); } fw.close(); } catch (IOException e) { e.printStackTrace(); } }
diff --git a/src/view/pokemetrics/PokeGenerationsPanel.java b/src/view/pokemetrics/PokeGenerationsPanel.java index dc6b5c4..d6edbfc 100644 --- a/src/view/pokemetrics/PokeGenerationsPanel.java +++ b/src/view/pokemetrics/PokeGenerationsPanel.java @@ -1,302 +1,307 @@ package view.pokemetrics; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import javax.imageio.ImageIO; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import data.DataFetch; import net.miginfocom.swing.MigLayout; @SuppressWarnings("serial") public class PokeGenerationsPanel extends JPanel { public JButton metricsBtn; public JButton genBtn; public JLabel name; protected static final String DEFAULT = "Search Pokemon..."; private ButtonGroup group; private DataFetch df; private JTextArea jta; private JTable table; private JScrollPane jsp; private JRadioButton redblue; private JRadioButton yellow; private JRadioButton gold; private JRadioButton silver; private JRadioButton crystal; private JRadioButton ruby; private JRadioButton sapphire; private JRadioButton emerald; private JRadioButton firered; private JRadioButton leafgreen; private JRadioButton diamond; private JRadioButton pearl; private JLabel idLbl; private JLabel id; private JLabel nameLbl; private JLabel imageLbl; private JLabel pokedexEntry; private int national_id; public PokeGenerationsPanel(){ super(new MigLayout()); this.df = DataFetch.getInstance(); initComponents(); } private void initComponents(){ jta = new JTextArea(DEFAULT); jta.setPreferredSize(new Dimension(90,30)); table = new JTable(); jsp = new JScrollPane(table); table.getTableHeader().setReorderingAllowed(false); jsp.setPreferredSize(new Dimension(160,200)); metricsBtn = new JButton("Base Stats"); genBtn = new JButton("Through the Generations"); redblue = new JRadioButton("Red/Blue"); yellow = new JRadioButton("Yellow"); gold = new JRadioButton("Gold"); silver = new JRadioButton("Silver"); crystal = new JRadioButton("Crystal"); ruby = new JRadioButton("Ruby"); sapphire = new JRadioButton("Sapphire"); emerald = new JRadioButton("Emerald"); firered = new JRadioButton("Fire Red"); leafgreen = new JRadioButton("Leaf Green"); diamond = new JRadioButton("Diamond"); pearl = new JRadioButton("Pearl"); ActionListener listener = new ActionListener(){ public void actionPerformed(ActionEvent e){ String option = e.getActionCommand().replaceAll("/", "_").replaceAll(" ", "_"); String query = "select " + option + " from pokedex_description where national_id = '" + national_id + "';"; String result = "<html>" + df.getDexEntry(query) + "</html>"; // result = result.replaceAll(".", ".\n"); - pokedexEntry.setText(result); + System.out.println(result); + if(!result.equalsIgnoreCase("<html>null</html>")){ + pokedexEntry.setText(result); + }else{ + pokedexEntry.setText("No Pokedex Entry for this Version."); + } } }; redblue.addActionListener(listener); yellow.addActionListener(listener); gold.addActionListener(listener); silver.addActionListener(listener); crystal.addActionListener(listener); ruby.addActionListener(listener); sapphire.addActionListener(listener); emerald.addActionListener(listener); firered.addActionListener(listener); leafgreen.addActionListener(listener); diamond.addActionListener(listener); pearl.addActionListener(listener); group = new ButtonGroup(); group.add(redblue); group.add(yellow); group.add(gold); group.add(silver); group.add(crystal); group.add(ruby); group.add(sapphire); group.add(emerald); group.add(firered); group.add(leafgreen); group.add(diamond); group.add(pearl); idLbl = new JLabel(""); id = new JLabel(""); nameLbl = new JLabel(""); name = new JLabel(""); imageLbl = new JLabel(""); pokedexEntry = new JLabel(""); pokedexEntry.setPreferredSize(new Dimension(400,200)); pokedexEntry.setFont(new Font("Serif", Font.PLAIN, 24)); JPanel western = new JPanel(new MigLayout()); western.add(jta, "wrap"); western.add(jsp); this.add(western, "west"); JPanel northern = new JPanel(new MigLayout()); northern.add(metricsBtn); northern.add(genBtn); this.add(northern, "north"); JPanel west = new JPanel(new MigLayout()); west.add(idLbl); west.add(id, "wrap"); west.add(nameLbl); west.add(name, "wrap"); west.add(imageLbl, "south"); west.setBorder(BorderFactory.createEtchedBorder()); this.add(west, "west"); JPanel east = new JPanel(new MigLayout()); east.add(pokedexEntry, "east, wrap"); this.add(east, "center"); JPanel south = new JPanel(new MigLayout()); south.add(redblue); south.add(yellow); south.add(gold); south.add(silver); south.add(crystal); south.add(ruby, "wrap"); south.add(sapphire); south.add(emerald); south.add(firered); south.add(leafgreen); south.add(diamond); south.add(pearl); south.setBorder(BorderFactory.createEtchedBorder()); this.add(south, "south"); initializeActions(); updateTable(); } private void updatePokedexEntry(String pokemon){ for(Enumeration<AbstractButton> buttons = group.getElements(); buttons.hasMoreElements();){ AbstractButton button = buttons.nextElement(); if(button.isSelected()){ button.doClick(); } } } public void updatePokeGenerations(String pokemon){ ArrayList<String> metricsData = df.getMetricsQuery(pokemon); national_id = Integer.parseInt(metricsData.get(0)); String ID = metricsData.get(0); if(ID.length() < 3){ if(ID.length() == 1){ ID = "00" + ID; }else{ ID = "0" + ID; } } String path = "resources/images/" + ID + ".png"; Toolkit tk = Toolkit.getDefaultToolkit(); Image img = tk.createImage(path); BufferedImage imgs = null; try { imgs = ImageIO.read(new File(path)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Image resizeImg = imgs == null ? img.getScaledInstance(150, 150, 0) : img.getScaledInstance(imgs.getWidth()/2, imgs.getHeight()/2, 0); imageLbl.setIcon(new ImageIcon(resizeImg)); id.setText(ID); name.setText(metricsData.get(1)); idLbl.setText("ID:"); nameLbl.setText("Name:"); } private void initializeActions(){ this.jta.addFocusListener(new FocusListener(){ public void focusGained(FocusEvent e){ if(jta.getText().equals(DEFAULT)){ jta.setText(""); } } public void focusLost(FocusEvent e){ if(jta.getText().equals("")){ jta.setText(DEFAULT); } updateTable(); } }); this.jta.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if(e.getKeyChar() == KeyEvent.VK_ESCAPE) { jta.setText(DEFAULT); } updateTable(); } }); this.table.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent arg0) { int index = table.getSelectedRow(); if(index != -1){ String pokemon = (String) table.getValueAt(index, 1); updatePokeGenerations(pokemon); updatePokedexEntry(pokemon); } } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } }); } private void updateTable(){ if(jta.getText().equals(DEFAULT)){ this.table.setModel(df.getSimplifiedDefaultPokemonModel()); this.table.getColumnModel().getColumn(0).setHeaderValue("ID"); this.table.getColumnModel().getColumn(1).setHeaderValue("Name"); this.table.getColumnModel().getColumn(0).setMaxWidth(40); this.table.getColumnModel().getColumn(1).setMaxWidth(100); }else{ this.table.setModel(df.getSimplifiedSearchPokemonModel(jta.getText())); this.table.getColumnModel().getColumn(0).setHeaderValue("ID"); this.table.getColumnModel().getColumn(1).setHeaderValue("Name"); this.table.getColumnModel().getColumn(0).setMaxWidth(40); this.table.getColumnModel().getColumn(1).setMaxWidth(100); } } }
true
true
private void initComponents(){ jta = new JTextArea(DEFAULT); jta.setPreferredSize(new Dimension(90,30)); table = new JTable(); jsp = new JScrollPane(table); table.getTableHeader().setReorderingAllowed(false); jsp.setPreferredSize(new Dimension(160,200)); metricsBtn = new JButton("Base Stats"); genBtn = new JButton("Through the Generations"); redblue = new JRadioButton("Red/Blue"); yellow = new JRadioButton("Yellow"); gold = new JRadioButton("Gold"); silver = new JRadioButton("Silver"); crystal = new JRadioButton("Crystal"); ruby = new JRadioButton("Ruby"); sapphire = new JRadioButton("Sapphire"); emerald = new JRadioButton("Emerald"); firered = new JRadioButton("Fire Red"); leafgreen = new JRadioButton("Leaf Green"); diamond = new JRadioButton("Diamond"); pearl = new JRadioButton("Pearl"); ActionListener listener = new ActionListener(){ public void actionPerformed(ActionEvent e){ String option = e.getActionCommand().replaceAll("/", "_").replaceAll(" ", "_"); String query = "select " + option + " from pokedex_description where national_id = '" + national_id + "';"; String result = "<html>" + df.getDexEntry(query) + "</html>"; // result = result.replaceAll(".", ".\n"); pokedexEntry.setText(result); } }; redblue.addActionListener(listener); yellow.addActionListener(listener); gold.addActionListener(listener); silver.addActionListener(listener); crystal.addActionListener(listener); ruby.addActionListener(listener); sapphire.addActionListener(listener); emerald.addActionListener(listener); firered.addActionListener(listener); leafgreen.addActionListener(listener); diamond.addActionListener(listener); pearl.addActionListener(listener); group = new ButtonGroup(); group.add(redblue); group.add(yellow); group.add(gold); group.add(silver); group.add(crystal); group.add(ruby); group.add(sapphire); group.add(emerald); group.add(firered); group.add(leafgreen); group.add(diamond); group.add(pearl); idLbl = new JLabel(""); id = new JLabel(""); nameLbl = new JLabel(""); name = new JLabel(""); imageLbl = new JLabel(""); pokedexEntry = new JLabel(""); pokedexEntry.setPreferredSize(new Dimension(400,200)); pokedexEntry.setFont(new Font("Serif", Font.PLAIN, 24)); JPanel western = new JPanel(new MigLayout()); western.add(jta, "wrap"); western.add(jsp); this.add(western, "west"); JPanel northern = new JPanel(new MigLayout()); northern.add(metricsBtn); northern.add(genBtn); this.add(northern, "north"); JPanel west = new JPanel(new MigLayout()); west.add(idLbl); west.add(id, "wrap"); west.add(nameLbl); west.add(name, "wrap"); west.add(imageLbl, "south"); west.setBorder(BorderFactory.createEtchedBorder()); this.add(west, "west"); JPanel east = new JPanel(new MigLayout()); east.add(pokedexEntry, "east, wrap"); this.add(east, "center"); JPanel south = new JPanel(new MigLayout()); south.add(redblue); south.add(yellow); south.add(gold); south.add(silver); south.add(crystal); south.add(ruby, "wrap"); south.add(sapphire); south.add(emerald); south.add(firered); south.add(leafgreen); south.add(diamond); south.add(pearl); south.setBorder(BorderFactory.createEtchedBorder()); this.add(south, "south"); initializeActions(); updateTable(); }
private void initComponents(){ jta = new JTextArea(DEFAULT); jta.setPreferredSize(new Dimension(90,30)); table = new JTable(); jsp = new JScrollPane(table); table.getTableHeader().setReorderingAllowed(false); jsp.setPreferredSize(new Dimension(160,200)); metricsBtn = new JButton("Base Stats"); genBtn = new JButton("Through the Generations"); redblue = new JRadioButton("Red/Blue"); yellow = new JRadioButton("Yellow"); gold = new JRadioButton("Gold"); silver = new JRadioButton("Silver"); crystal = new JRadioButton("Crystal"); ruby = new JRadioButton("Ruby"); sapphire = new JRadioButton("Sapphire"); emerald = new JRadioButton("Emerald"); firered = new JRadioButton("Fire Red"); leafgreen = new JRadioButton("Leaf Green"); diamond = new JRadioButton("Diamond"); pearl = new JRadioButton("Pearl"); ActionListener listener = new ActionListener(){ public void actionPerformed(ActionEvent e){ String option = e.getActionCommand().replaceAll("/", "_").replaceAll(" ", "_"); String query = "select " + option + " from pokedex_description where national_id = '" + national_id + "';"; String result = "<html>" + df.getDexEntry(query) + "</html>"; // result = result.replaceAll(".", ".\n"); System.out.println(result); if(!result.equalsIgnoreCase("<html>null</html>")){ pokedexEntry.setText(result); }else{ pokedexEntry.setText("No Pokedex Entry for this Version."); } } }; redblue.addActionListener(listener); yellow.addActionListener(listener); gold.addActionListener(listener); silver.addActionListener(listener); crystal.addActionListener(listener); ruby.addActionListener(listener); sapphire.addActionListener(listener); emerald.addActionListener(listener); firered.addActionListener(listener); leafgreen.addActionListener(listener); diamond.addActionListener(listener); pearl.addActionListener(listener); group = new ButtonGroup(); group.add(redblue); group.add(yellow); group.add(gold); group.add(silver); group.add(crystal); group.add(ruby); group.add(sapphire); group.add(emerald); group.add(firered); group.add(leafgreen); group.add(diamond); group.add(pearl); idLbl = new JLabel(""); id = new JLabel(""); nameLbl = new JLabel(""); name = new JLabel(""); imageLbl = new JLabel(""); pokedexEntry = new JLabel(""); pokedexEntry.setPreferredSize(new Dimension(400,200)); pokedexEntry.setFont(new Font("Serif", Font.PLAIN, 24)); JPanel western = new JPanel(new MigLayout()); western.add(jta, "wrap"); western.add(jsp); this.add(western, "west"); JPanel northern = new JPanel(new MigLayout()); northern.add(metricsBtn); northern.add(genBtn); this.add(northern, "north"); JPanel west = new JPanel(new MigLayout()); west.add(idLbl); west.add(id, "wrap"); west.add(nameLbl); west.add(name, "wrap"); west.add(imageLbl, "south"); west.setBorder(BorderFactory.createEtchedBorder()); this.add(west, "west"); JPanel east = new JPanel(new MigLayout()); east.add(pokedexEntry, "east, wrap"); this.add(east, "center"); JPanel south = new JPanel(new MigLayout()); south.add(redblue); south.add(yellow); south.add(gold); south.add(silver); south.add(crystal); south.add(ruby, "wrap"); south.add(sapphire); south.add(emerald); south.add(firered); south.add(leafgreen); south.add(diamond); south.add(pearl); south.setBorder(BorderFactory.createEtchedBorder()); this.add(south, "south"); initializeActions(); updateTable(); }
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListDropAdapter.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListDropAdapter.java index 1d7683817..078d5e3f1 100644 --- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListDropAdapter.java +++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/views/TaskListDropAdapter.java @@ -1,344 +1,344 @@ /******************************************************************************* * Copyright (c) 2004, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.internal.tasks.ui.views; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerDropAdapter; import org.eclipse.mylyn.context.core.ContextCorePlugin; import org.eclipse.mylyn.internal.context.core.InteractionContext; import org.eclipse.mylyn.internal.tasks.core.ScheduledTaskContainer; import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil; import org.eclipse.mylyn.internal.tasks.core.TaskCategory; import org.eclipse.mylyn.internal.tasks.core.UnfiledCategory; import org.eclipse.mylyn.internal.tasks.ui.ITasksUiConstants; import org.eclipse.mylyn.internal.tasks.ui.RetrieveTitleFromUrlJob; import org.eclipse.mylyn.internal.tasks.ui.TaskTransfer; import org.eclipse.mylyn.internal.tasks.ui.actions.QueryImportAction; import org.eclipse.mylyn.internal.tasks.ui.actions.TaskActivateAction; import org.eclipse.mylyn.internal.tasks.ui.actions.TaskImportAction; import org.eclipse.mylyn.monitor.core.StatusHandler; import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector; import org.eclipse.mylyn.tasks.core.AbstractRepositoryQuery; import org.eclipse.mylyn.tasks.core.AbstractTask; import org.eclipse.mylyn.tasks.core.AbstractTaskContainer; import org.eclipse.mylyn.tasks.core.TaskRepository; import org.eclipse.mylyn.tasks.ui.TasksUiPlugin; import org.eclipse.mylyn.tasks.ui.TasksUiUtil; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTargetEvent; import org.eclipse.swt.dnd.FileTransfer; import org.eclipse.swt.dnd.TextTransfer; import org.eclipse.swt.dnd.TransferData; /** * @author Mik Kersten * @author Rob Elves (added URL based task creation support) * @author Jevgeni Holodkov */ public class TaskListDropAdapter extends ViewerDropAdapter { private AbstractTask newTask = null; private TransferData currentTransfer; public TaskListDropAdapter(Viewer viewer) { super(viewer); setFeedbackEnabled(true); } @Override public void dragOver(DropTargetEvent event) { // support dragging from sources only supporting DROP_LINK if (event.detail == DND.DROP_NONE && (event.operations & DND.DROP_LINK) == DND.DROP_LINK) { event.detail = DND.DROP_LINK; } super.dragOver(event); } @Override public boolean performDrop(Object data) { Object currentTarget = getCurrentTarget(); List<AbstractTask> tasksToMove = new ArrayList<AbstractTask>(); ISelection selection = ((TreeViewer) getViewer()).getSelection(); if (isUrl(data) && createTaskFromUrl(data)) { tasksToMove.add(newTask); } else if (TaskTransfer.getInstance().isSupportedType(currentTransfer)) { for (Object selectedObject : ((IStructuredSelection) selection).toList()) { AbstractTask toMove = null; if (selectedObject instanceof AbstractTask) { toMove = (AbstractTask) selectedObject; } if (toMove != null) { tasksToMove.add(toMove); } } } else if (data instanceof String && createTaskFromString((String) data)) { tasksToMove.add(newTask); } else if (FileTransfer.getInstance().isSupportedType(currentTransfer)) { // transfer the context if the target is a Task if (getCurrentTarget() instanceof AbstractTask) { AbstractTask targetTask = (AbstractTask) getCurrentTarget(); final String[] names = (String[]) data; boolean confirmed = MessageDialog.openConfirm(getViewer().getControl().getShell(), ITasksUiConstants.TITLE_DIALOG, "Overwrite the context of the target task with the source's?"); if (confirmed) { String path = names[0]; File file = new File(path); if (ContextCorePlugin.getContextManager().isValidContextFile(file)) { - ContextCorePlugin.getContextManager().transferContextAndActivate( + ContextCorePlugin.getContextManager().copyContext( targetTask.getHandleIdentifier(), file); new TaskActivateAction().run(targetTask); } } } else { // otherwise it is queries or tasks final String[] names = (String[]) data; List<AbstractRepositoryQuery> queries = new ArrayList<AbstractRepositoryQuery>(); Map<AbstractTask, InteractionContext> taskContexts = new HashMap<AbstractTask, InteractionContext>(); Set<TaskRepository> repositories = new HashSet<TaskRepository>(); for (int i = 0; i < names.length; i++) { String path = names[i]; File file = new File(path); if (file.isFile()) { List<AbstractRepositoryQuery> readQueries = TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readQueries(file); if (readQueries.size() > 0) { queries.addAll(readQueries); repositories.addAll(TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readRepositories(file)); } else { List<AbstractTask> readTasks = TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readTasks(file); for (AbstractTask task : readTasks) { taskContexts.put(task, ContextCorePlugin.getContextManager().loadContext( task.getHandleIdentifier(), file)); } repositories.addAll(TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readRepositories(file)); } } } if (queries.size() > 0) { new QueryImportAction().importQueries(queries, repositories, getViewer().getControl().getShell()); } else { TaskImportAction action = new TaskImportAction(); action.importTasks(taskContexts, repositories, getViewer().getControl().getShell()); action.refreshTaskListView(); } } } for (AbstractTask task : tasksToMove) { if (currentTarget instanceof UnfiledCategory) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, (UnfiledCategory) currentTarget); } else if (currentTarget instanceof TaskCategory) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, (TaskCategory) currentTarget); } else if (currentTarget instanceof AbstractTask) { AbstractTask targetTask = (AbstractTask) currentTarget; TaskCategory targetCategory = null; // TODO: just look for categories? if (targetTask.getParentContainers().size() > 0) { AbstractTaskContainer container = targetTask.getParentContainers().iterator().next(); if (container instanceof TaskCategory) { targetCategory = (TaskCategory) container; } } if (targetCategory == null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory()); } else { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, targetCategory); } } else if (currentTarget instanceof ScheduledTaskContainer) { ScheduledTaskContainer container = (ScheduledTaskContainer) currentTarget; Calendar newSchedule = Calendar.getInstance(); newSchedule.setTimeInMillis(container.getStart().getTimeInMillis()); TaskActivityUtil.snapEndOfWorkDay(newSchedule); TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, newSchedule.getTime()); } else if (currentTarget == null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(newTask, TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory()); } } // Make new task the current selection in the view if (newTask != null) { StructuredSelection ss = new StructuredSelection(newTask); getViewer().setSelection(ss); getViewer().refresh(); } return true; } /** * @return true if string is a http(s) url */ public boolean isUrl(Object data) { String uri = ""; if (data instanceof String) { uri = (String) data; if ((uri.startsWith("http://") || uri.startsWith("https://"))) { return true; } } return false; } /** * @param data * string containing url and title separated by <quote>\n</quote> * @return true if task succesfully created, false otherwise */ public boolean createTaskFromUrl(Object data) { if (!(data instanceof String)) return false; String[] urlTransfer = ((String) data).split("\n"); String url = ""; String urlTitle = "<retrieving from URL>"; if (urlTransfer.length > 0) { url = urlTransfer[0]; } else { return false; } AbstractRepositoryConnector connector = TasksUiPlugin.getRepositoryManager().getConnectorForRepositoryTaskUrl( url); if (connector != null) { String repositoryUrl = connector.getRepositoryUrlFromTaskUrl(url); String id = connector.getTaskIdFromTaskUrl(url); if (repositoryUrl == null || id == null) { return false; } for (TaskRepository repository : TasksUiPlugin.getRepositoryManager().getRepositories( connector.getConnectorKind())) { if (repository.getUrl().equals(repositoryUrl)) { try { newTask = connector.createTaskFromExistingId(repository, id, new NullProgressMonitor()); TasksUiUtil.refreshAndOpenTaskListElement(newTask); return true; } catch (CoreException e) { StatusHandler.fail(e, "could not create task", false); return false; } } } return false; } else { // Removed in order to default to retrieving title from url rather // than // accepting what was sent by the brower's DnD code. (see bug // 114401) // If a Title is provided, use it. // if (urlTransfer.length > 1) { // urlTitle = urlTransfer[1]; // } // if (urlTransfer.length < 2) { // no title provided // retrieveTaskDescription(url); // } retrieveTaskDescription(url); newTask = TasksUiPlugin.getTaskListManager().createNewLocalTask(urlTitle); if (newTask == null) { return false; } newTask.setUrl(url); // NOTE: setting boolean param as false so that we go directly to // the // browser tab as with a previously-created task TasksUiUtil.openEditor(newTask, false); return true; } } public boolean createTaskFromString(String title) { //newTask = new Task(TasksUiPlugin.getTaskListManager().genUniqueTaskHandle(), title); newTask = TasksUiPlugin.getTaskListManager().createNewLocalTask(title); if (newTask == null) { return false; } else { //newTask.setPriority(Task.PriorityLevel.P3.toString()); TasksUiUtil.openEditor(newTask, false); return true; } } @Override public boolean validateDrop(Object targetObject, int operation, TransferData transferType) { currentTransfer = transferType; Object selectedObject = ((IStructuredSelection) ((TreeViewer) getViewer()).getSelection()).getFirstElement(); if (FileTransfer.getInstance().isSupportedType(currentTransfer)) { // handle all files return true; } else if (selectedObject != null && !(selectedObject instanceof AbstractRepositoryQuery)) { if (getCurrentTarget() instanceof TaskCategory || getCurrentTarget() instanceof UnfiledCategory || getCurrentTarget() instanceof ScheduledTaskContainer) { return true; } else if (getCurrentTarget() instanceof AbstractTaskContainer && (getCurrentLocation() == ViewerDropAdapter.LOCATION_AFTER || getCurrentLocation() == ViewerDropAdapter.LOCATION_BEFORE)) { return true; } else { return false; } } return TextTransfer.getInstance().isSupportedType(transferType); } /** * Attempts to set the task pageTitle to the title from the specified url */ protected void retrieveTaskDescription(final String url) { try { RetrieveTitleFromUrlJob job = new RetrieveTitleFromUrlJob(url) { @Override protected void setTitle(final String pageTitle) { newTask.setSummary(pageTitle); TasksUiPlugin.getTaskListManager().getTaskList().notifyTaskChanged(newTask, false); } }; job.schedule(); } catch (RuntimeException e) { StatusHandler.fail(e, "could not open task web page", false); } } }
true
true
public boolean performDrop(Object data) { Object currentTarget = getCurrentTarget(); List<AbstractTask> tasksToMove = new ArrayList<AbstractTask>(); ISelection selection = ((TreeViewer) getViewer()).getSelection(); if (isUrl(data) && createTaskFromUrl(data)) { tasksToMove.add(newTask); } else if (TaskTransfer.getInstance().isSupportedType(currentTransfer)) { for (Object selectedObject : ((IStructuredSelection) selection).toList()) { AbstractTask toMove = null; if (selectedObject instanceof AbstractTask) { toMove = (AbstractTask) selectedObject; } if (toMove != null) { tasksToMove.add(toMove); } } } else if (data instanceof String && createTaskFromString((String) data)) { tasksToMove.add(newTask); } else if (FileTransfer.getInstance().isSupportedType(currentTransfer)) { // transfer the context if the target is a Task if (getCurrentTarget() instanceof AbstractTask) { AbstractTask targetTask = (AbstractTask) getCurrentTarget(); final String[] names = (String[]) data; boolean confirmed = MessageDialog.openConfirm(getViewer().getControl().getShell(), ITasksUiConstants.TITLE_DIALOG, "Overwrite the context of the target task with the source's?"); if (confirmed) { String path = names[0]; File file = new File(path); if (ContextCorePlugin.getContextManager().isValidContextFile(file)) { ContextCorePlugin.getContextManager().transferContextAndActivate( targetTask.getHandleIdentifier(), file); new TaskActivateAction().run(targetTask); } } } else { // otherwise it is queries or tasks final String[] names = (String[]) data; List<AbstractRepositoryQuery> queries = new ArrayList<AbstractRepositoryQuery>(); Map<AbstractTask, InteractionContext> taskContexts = new HashMap<AbstractTask, InteractionContext>(); Set<TaskRepository> repositories = new HashSet<TaskRepository>(); for (int i = 0; i < names.length; i++) { String path = names[i]; File file = new File(path); if (file.isFile()) { List<AbstractRepositoryQuery> readQueries = TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readQueries(file); if (readQueries.size() > 0) { queries.addAll(readQueries); repositories.addAll(TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readRepositories(file)); } else { List<AbstractTask> readTasks = TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readTasks(file); for (AbstractTask task : readTasks) { taskContexts.put(task, ContextCorePlugin.getContextManager().loadContext( task.getHandleIdentifier(), file)); } repositories.addAll(TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readRepositories(file)); } } } if (queries.size() > 0) { new QueryImportAction().importQueries(queries, repositories, getViewer().getControl().getShell()); } else { TaskImportAction action = new TaskImportAction(); action.importTasks(taskContexts, repositories, getViewer().getControl().getShell()); action.refreshTaskListView(); } } } for (AbstractTask task : tasksToMove) { if (currentTarget instanceof UnfiledCategory) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, (UnfiledCategory) currentTarget); } else if (currentTarget instanceof TaskCategory) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, (TaskCategory) currentTarget); } else if (currentTarget instanceof AbstractTask) { AbstractTask targetTask = (AbstractTask) currentTarget; TaskCategory targetCategory = null; // TODO: just look for categories? if (targetTask.getParentContainers().size() > 0) { AbstractTaskContainer container = targetTask.getParentContainers().iterator().next(); if (container instanceof TaskCategory) { targetCategory = (TaskCategory) container; } } if (targetCategory == null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory()); } else { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, targetCategory); } } else if (currentTarget instanceof ScheduledTaskContainer) { ScheduledTaskContainer container = (ScheduledTaskContainer) currentTarget; Calendar newSchedule = Calendar.getInstance(); newSchedule.setTimeInMillis(container.getStart().getTimeInMillis()); TaskActivityUtil.snapEndOfWorkDay(newSchedule); TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, newSchedule.getTime()); } else if (currentTarget == null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(newTask, TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory()); } } // Make new task the current selection in the view if (newTask != null) { StructuredSelection ss = new StructuredSelection(newTask); getViewer().setSelection(ss); getViewer().refresh(); } return true; }
public boolean performDrop(Object data) { Object currentTarget = getCurrentTarget(); List<AbstractTask> tasksToMove = new ArrayList<AbstractTask>(); ISelection selection = ((TreeViewer) getViewer()).getSelection(); if (isUrl(data) && createTaskFromUrl(data)) { tasksToMove.add(newTask); } else if (TaskTransfer.getInstance().isSupportedType(currentTransfer)) { for (Object selectedObject : ((IStructuredSelection) selection).toList()) { AbstractTask toMove = null; if (selectedObject instanceof AbstractTask) { toMove = (AbstractTask) selectedObject; } if (toMove != null) { tasksToMove.add(toMove); } } } else if (data instanceof String && createTaskFromString((String) data)) { tasksToMove.add(newTask); } else if (FileTransfer.getInstance().isSupportedType(currentTransfer)) { // transfer the context if the target is a Task if (getCurrentTarget() instanceof AbstractTask) { AbstractTask targetTask = (AbstractTask) getCurrentTarget(); final String[] names = (String[]) data; boolean confirmed = MessageDialog.openConfirm(getViewer().getControl().getShell(), ITasksUiConstants.TITLE_DIALOG, "Overwrite the context of the target task with the source's?"); if (confirmed) { String path = names[0]; File file = new File(path); if (ContextCorePlugin.getContextManager().isValidContextFile(file)) { ContextCorePlugin.getContextManager().copyContext( targetTask.getHandleIdentifier(), file); new TaskActivateAction().run(targetTask); } } } else { // otherwise it is queries or tasks final String[] names = (String[]) data; List<AbstractRepositoryQuery> queries = new ArrayList<AbstractRepositoryQuery>(); Map<AbstractTask, InteractionContext> taskContexts = new HashMap<AbstractTask, InteractionContext>(); Set<TaskRepository> repositories = new HashSet<TaskRepository>(); for (int i = 0; i < names.length; i++) { String path = names[i]; File file = new File(path); if (file.isFile()) { List<AbstractRepositoryQuery> readQueries = TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readQueries(file); if (readQueries.size() > 0) { queries.addAll(readQueries); repositories.addAll(TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readRepositories(file)); } else { List<AbstractTask> readTasks = TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readTasks(file); for (AbstractTask task : readTasks) { taskContexts.put(task, ContextCorePlugin.getContextManager().loadContext( task.getHandleIdentifier(), file)); } repositories.addAll(TasksUiPlugin.getTaskListManager() .getTaskListWriter() .readRepositories(file)); } } } if (queries.size() > 0) { new QueryImportAction().importQueries(queries, repositories, getViewer().getControl().getShell()); } else { TaskImportAction action = new TaskImportAction(); action.importTasks(taskContexts, repositories, getViewer().getControl().getShell()); action.refreshTaskListView(); } } } for (AbstractTask task : tasksToMove) { if (currentTarget instanceof UnfiledCategory) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, (UnfiledCategory) currentTarget); } else if (currentTarget instanceof TaskCategory) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, (TaskCategory) currentTarget); } else if (currentTarget instanceof AbstractTask) { AbstractTask targetTask = (AbstractTask) currentTarget; TaskCategory targetCategory = null; // TODO: just look for categories? if (targetTask.getParentContainers().size() > 0) { AbstractTaskContainer container = targetTask.getParentContainers().iterator().next(); if (container instanceof TaskCategory) { targetCategory = (TaskCategory) container; } } if (targetCategory == null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory()); } else { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(task, targetCategory); } } else if (currentTarget instanceof ScheduledTaskContainer) { ScheduledTaskContainer container = (ScheduledTaskContainer) currentTarget; Calendar newSchedule = Calendar.getInstance(); newSchedule.setTimeInMillis(container.getStart().getTimeInMillis()); TaskActivityUtil.snapEndOfWorkDay(newSchedule); TasksUiPlugin.getTaskActivityManager().setScheduledFor(task, newSchedule.getTime()); } else if (currentTarget == null) { TasksUiPlugin.getTaskListManager().getTaskList().moveToContainer(newTask, TasksUiPlugin.getTaskListManager().getTaskList().getDefaultCategory()); } } // Make new task the current selection in the view if (newTask != null) { StructuredSelection ss = new StructuredSelection(newTask); getViewer().setSelection(ss); getViewer().refresh(); } return true; }
diff --git a/src/com/android/browser/CombinedBookmarkHistoryView.java b/src/com/android/browser/CombinedBookmarkHistoryView.java index 184314e1..4b3e6d84 100644 --- a/src/com/android/browser/CombinedBookmarkHistoryView.java +++ b/src/com/android/browser/CombinedBookmarkHistoryView.java @@ -1,392 +1,396 @@ /* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.browser; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Browser; import android.view.Gravity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.webkit.WebIconDatabase; import android.webkit.WebIconDatabase.IconListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import com.android.browser.UI.ComboViews; import java.util.HashMap; import java.util.Vector; interface BookmarksHistoryCallbacks { public void onUrlSelected(String url, boolean newWindow); public void onRemoveParentChildRelationships(); } public class CombinedBookmarkHistoryView extends LinearLayout implements OnTouchListener, TabListener, OptionsMenuHandler { final static String STARTING_FRAGMENT = "fragment"; final static int INVALID_ID = 0; final static int FRAGMENT_ID_BOOKMARKS = 1; final static int FRAGMENT_ID_HISTORY = 2; final static int FRAGMENT_ID_SNAPSHOTS = 3; private UiController mUiController; private Activity mActivity; private ActionBar mActionBar; private Bundle mExtras; int mCurrentFragment = INVALID_ID; ActionBar.Tab mTabBookmarks; ActionBar.Tab mTabHistory; ActionBar.Tab mTabSnapshots; ViewGroup mBookmarksHeader; BrowserBookmarksPage mBookmarks; BrowserHistoryPage mHistory; BrowserSnapshotPage mSnapshots; boolean mIsAnimating; static class IconListenerSet implements IconListener { // Used to store favicons as we get them from the database // FIXME: We use a different method to get the Favicons in // BrowserBookmarksAdapter. They should probably be unified. private HashMap<String, Bitmap> mUrlsToIcons; private Vector<IconListener> mListeners; public IconListenerSet() { mUrlsToIcons = new HashMap<String, Bitmap>(); mListeners = new Vector<IconListener>(); } @Override public void onReceivedIcon(String url, Bitmap icon) { mUrlsToIcons.put(url, icon); for (IconListener listener : mListeners) { listener.onReceivedIcon(url, icon); } } public void addListener(IconListener listener) { mListeners.add(listener); } public void removeListener(IconListener listener) { mListeners.remove(listener); } public Bitmap getFavicon(String url) { return mUrlsToIcons.get(url); } } private static IconListenerSet sIconListenerSet; static IconListenerSet getIconListenerSet() { if (null == sIconListenerSet) { sIconListenerSet = new IconListenerSet(); } return sIconListenerSet; } public CombinedBookmarkHistoryView(Activity activity, UiController controller, ComboViews startingView, Bundle extras) { super(activity); mUiController = controller; mActivity = activity; mExtras = extras; mActionBar = mActivity.getActionBar(); View v = LayoutInflater.from(activity).inflate(R.layout.bookmarks_history, this); v.setOnTouchListener(this); // setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mBookmarksHeader = new FrameLayout(mActivity); mBookmarksHeader.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL)); // Start up the default fragment initFragments(mExtras); // XXX: Must do this before launching the AsyncTask to avoid a // potential crash if the icon database has not been created. WebIconDatabase.getInstance(); // Do this every time the view is created in case a new favicon was // added to the webkit db. (new AsyncTask<Void, Void, Void>() { @Override public Void doInBackground(Void... v) { Browser.requestAllIcons(mActivity.getContentResolver(), Browser.BookmarkColumns.FAVICON + " is NULL", getIconListenerSet()); return null; } }).execute(); mIsAnimating = true; setAlpha(0f); Resources res = mActivity.getResources(); animate().alpha(1f) .setDuration(res.getInteger(R.integer.comboViewFadeInDuration)) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mIsAnimating = false; + if (mActionBar == null) { + // We were destroyed, return + return; + } FragmentManager fm = mActivity.getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); onTabSelected(mActionBar.getSelectedTab(), ft); ft.commit(); } }); setupActionBar(startingView); mUiController.registerOptionsMenuHandler(this); } void setupActionBar(ComboViews startingView) { if (BrowserActivity.isTablet(mContext)) { mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_USE_LOGO); } else { mActionBar.setDisplayOptions(0); } mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mActionBar.removeAllTabs(); mTabBookmarks = mActionBar.newTab(); mTabBookmarks.setText(R.string.tab_bookmarks); mTabBookmarks.setTabListener(this); mActionBar.addTab(mTabBookmarks, ComboViews.Bookmarks == startingView); mTabHistory = mActionBar.newTab(); mTabHistory.setText(R.string.tab_history); mTabHistory.setTabListener(this); mActionBar.addTab(mTabHistory, ComboViews.History == startingView); mTabSnapshots = mActionBar.newTab(); mTabSnapshots.setText(R.string.tab_snapshots); mTabSnapshots.setTabListener(this); mActionBar.addTab(mTabSnapshots, ComboViews.Snapshots == startingView); mActionBar.setCustomView(mBookmarksHeader); mActionBar.show(); } void tearDownActionBar() { if (mActionBar != null) { mActionBar.removeAllTabs(); mTabBookmarks.setTabListener(null); mTabHistory.setTabListener(null); mTabSnapshots.setTabListener(null); mTabBookmarks = null; mTabHistory = null; mTabSnapshots = null; mActionBar = null; } } @Override protected void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (mCurrentFragment == FRAGMENT_ID_HISTORY) { // Warning, ugly hack below // This is done because history uses orientation-specific padding FragmentManager fm = mActivity.getFragmentManager(); mHistory = BrowserHistoryPage.newInstance(mUiController, mHistory.getArguments()); fm.beginTransaction().replace(R.id.fragment, mHistory).commit(); } } private BookmarksPageCallbacks mBookmarkCallbackWrapper = new BookmarksPageCallbacks() { @Override public boolean onOpenInNewWindow(Cursor c) { mUiController.onUrlSelected(BrowserBookmarksPage.getUrl(c), true); return true; } @Override public boolean onBookmarkSelected(Cursor c, boolean isFolder) { if (isFolder) { return false; } mUiController.onUrlSelected(BrowserBookmarksPage.getUrl(c), false); return true; } }; private void initFragments(Bundle extras) { mBookmarks = BrowserBookmarksPage.newInstance(mBookmarkCallbackWrapper, extras, mBookmarksHeader); mHistory = BrowserHistoryPage.newInstance(mUiController, extras); mSnapshots = BrowserSnapshotPage.newInstance(mUiController, extras); } private void loadFragment(int id, FragmentTransaction ft) { if (mCurrentFragment == id) return; switch (id) { case FRAGMENT_ID_BOOKMARKS: ft.replace(R.id.fragment, mBookmarks); break; case FRAGMENT_ID_HISTORY: ft.replace(R.id.fragment, mHistory); break; case FRAGMENT_ID_SNAPSHOTS: ft.replace(R.id.fragment, mSnapshots); break; default: throw new IllegalArgumentException(); } mCurrentFragment = id; } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); tearDownActionBar(); if (mCurrentFragment != INVALID_ID) { try { FragmentManager fm = mActivity.getFragmentManager(); FragmentTransaction transaction = fm.beginTransaction(); if (mCurrentFragment == FRAGMENT_ID_BOOKMARKS) { transaction.remove(mBookmarks); } else if (mCurrentFragment == FRAGMENT_ID_HISTORY) { transaction.remove(mHistory); } else if (mCurrentFragment == FRAGMENT_ID_SNAPSHOTS) { transaction.remove(mSnapshots); } transaction.commit(); } catch (IllegalStateException ex) { // This exception is thrown if the fragment isn't added // This will happen if the activity is finishing, and the // fragment was already removed before this view was detached // Aka, success! } mCurrentFragment = INVALID_ID; } mUiController.unregisterOptionsMenuHandler(this); } /** * callback for back key presses */ boolean onBackPressed() { if (mIsAnimating) { return true; } if (mCurrentFragment == FRAGMENT_ID_BOOKMARKS) { return mBookmarks.onBackPressed(); } return false; } /** * capture touch events to prevent them from going to the underlying * WebView */ @Override public boolean onTouch(View v, MotionEvent event) { return true; } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // Ignore } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { if (mIsAnimating) { // We delay set while animating (smooth animations) // TODO: Signal to the fragment in advance so that it can start // loading its data asynchronously return; } if (tab == mTabBookmarks) { loadFragment(FRAGMENT_ID_BOOKMARKS, ft); } else if (tab == mTabHistory) { loadFragment(FRAGMENT_ID_HISTORY, ft); } else if (tab == mTabSnapshots) { loadFragment(FRAGMENT_ID_SNAPSHOTS, ft); } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // Ignore } @Override public boolean onCreateOptionsMenu(Menu menu) { // Handled by fragment return false; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // Handled by fragment return false; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: mUiController.getUi().onBackKey(); return true; case R.id.go_home: BrowserSettings settings = BrowserSettings.getInstance(); mUiController.onUrlSelected(settings.getHomePage(), false); return true; case R.id.add_bookmark: mUiController.bookmarkCurrentPage(false); return true; case R.id.preferences_menu_id: Intent intent = new Intent(mActivity, BrowserPreferencesPage.class); intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE, mUiController.getCurrentTopWebView().getUrl()); mActivity.startActivityForResult(intent, Controller.PREFERENCES_PAGE); return true; } switch (mCurrentFragment) { case FRAGMENT_ID_BOOKMARKS: return mBookmarks.onOptionsItemSelected(item); case FRAGMENT_ID_HISTORY: return mHistory.onOptionsItemSelected(item); } return false; } }
true
true
public CombinedBookmarkHistoryView(Activity activity, UiController controller, ComboViews startingView, Bundle extras) { super(activity); mUiController = controller; mActivity = activity; mExtras = extras; mActionBar = mActivity.getActionBar(); View v = LayoutInflater.from(activity).inflate(R.layout.bookmarks_history, this); v.setOnTouchListener(this); // setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mBookmarksHeader = new FrameLayout(mActivity); mBookmarksHeader.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL)); // Start up the default fragment initFragments(mExtras); // XXX: Must do this before launching the AsyncTask to avoid a // potential crash if the icon database has not been created. WebIconDatabase.getInstance(); // Do this every time the view is created in case a new favicon was // added to the webkit db. (new AsyncTask<Void, Void, Void>() { @Override public Void doInBackground(Void... v) { Browser.requestAllIcons(mActivity.getContentResolver(), Browser.BookmarkColumns.FAVICON + " is NULL", getIconListenerSet()); return null; } }).execute(); mIsAnimating = true; setAlpha(0f); Resources res = mActivity.getResources(); animate().alpha(1f) .setDuration(res.getInteger(R.integer.comboViewFadeInDuration)) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mIsAnimating = false; FragmentManager fm = mActivity.getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); onTabSelected(mActionBar.getSelectedTab(), ft); ft.commit(); } }); setupActionBar(startingView); mUiController.registerOptionsMenuHandler(this); }
public CombinedBookmarkHistoryView(Activity activity, UiController controller, ComboViews startingView, Bundle extras) { super(activity); mUiController = controller; mActivity = activity; mExtras = extras; mActionBar = mActivity.getActionBar(); View v = LayoutInflater.from(activity).inflate(R.layout.bookmarks_history, this); v.setOnTouchListener(this); // setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); mBookmarksHeader = new FrameLayout(mActivity); mBookmarksHeader.setLayoutParams(new FrameLayout.LayoutParams( FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL)); // Start up the default fragment initFragments(mExtras); // XXX: Must do this before launching the AsyncTask to avoid a // potential crash if the icon database has not been created. WebIconDatabase.getInstance(); // Do this every time the view is created in case a new favicon was // added to the webkit db. (new AsyncTask<Void, Void, Void>() { @Override public Void doInBackground(Void... v) { Browser.requestAllIcons(mActivity.getContentResolver(), Browser.BookmarkColumns.FAVICON + " is NULL", getIconListenerSet()); return null; } }).execute(); mIsAnimating = true; setAlpha(0f); Resources res = mActivity.getResources(); animate().alpha(1f) .setDuration(res.getInteger(R.integer.comboViewFadeInDuration)) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mIsAnimating = false; if (mActionBar == null) { // We were destroyed, return return; } FragmentManager fm = mActivity.getFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); onTabSelected(mActionBar.getSelectedTab(), ft); ft.commit(); } }); setupActionBar(startingView); mUiController.registerOptionsMenuHandler(this); }
diff --git a/src/Powerup.java b/src/Powerup.java index 20eb50a..2fc4bd2 100644 --- a/src/Powerup.java +++ b/src/Powerup.java @@ -1,26 +1,26 @@ import org.newdawn.slick.Image; import org.newdawn.slick.geom.Shape; import org.newdawn.slick.geom.Vector2f; /** * A class that implements a screen object that gives advantageous conditions to the player when acquired in the game */ public abstract class Powerup extends CollidableInteractiveEntity { /** * Initializes powerup values * @param name * @param image * @param position * @param collisionShape */ - public Powerup(String name, Image image, Vector2f position, Shape collisionShape) { - super(name, image, position, collisionShape); + public Powerup(String name, Image image, Vector2f position, Shape collisionShape, int speed) { + super(name, image, position, collisionShape, speed); } /** * Utilize function */ public abstract void utilize(); }
true
true
public Powerup(String name, Image image, Vector2f position, Shape collisionShape) { super(name, image, position, collisionShape); }
public Powerup(String name, Image image, Vector2f position, Shape collisionShape, int speed) { super(name, image, position, collisionShape, speed); }
diff --git a/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java b/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java index 7cfc44bd7..d9bff0f45 100644 --- a/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java +++ b/src/org/apache/xerces/impl/xs/XMLSchemaValidator.java @@ -1,4604 +1,4604 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.impl.xs; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Stack; import java.util.Vector; import javax.xml.XMLConstants; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.RevalidationHandler; import org.apache.xerces.impl.XMLEntityManager; import org.apache.xerces.impl.XMLErrorReporter; import org.apache.xerces.impl.dv.DatatypeException; import org.apache.xerces.impl.dv.InvalidDatatypeValueException; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl; import org.apache.xerces.impl.validation.ConfigurableValidationState; import org.apache.xerces.impl.validation.ValidationManager; import org.apache.xerces.impl.validation.ValidationState; import org.apache.xerces.impl.xs.identity.Field; import org.apache.xerces.impl.xs.identity.FieldActivator; import org.apache.xerces.impl.xs.identity.IdentityConstraint; import org.apache.xerces.impl.xs.identity.KeyRef; import org.apache.xerces.impl.xs.identity.Selector; import org.apache.xerces.impl.xs.identity.UniqueOrKey; import org.apache.xerces.impl.xs.identity.ValueStore; import org.apache.xerces.impl.xs.identity.XPathMatcher; import org.apache.xerces.impl.xs.models.CMBuilder; import org.apache.xerces.impl.xs.models.CMNodeFactory; import org.apache.xerces.impl.xs.models.XSCMValidator; import org.apache.xerces.util.AugmentationsImpl; import org.apache.xerces.util.IntStack; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.util.XMLAttributesImpl; import org.apache.xerces.util.XMLChar; import org.apache.xerces.util.XMLSymbols; import org.apache.xerces.util.URI.MalformedURIException; import org.apache.xerces.xni.Augmentations; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.QName; import org.apache.xerces.xni.XMLAttributes; import org.apache.xerces.xni.XMLDocumentHandler; import org.apache.xerces.xni.XMLLocator; import org.apache.xerces.xni.XMLResourceIdentifier; import org.apache.xerces.xni.XMLString; import org.apache.xerces.xni.XNIException; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XMLGrammarPool; import org.apache.xerces.xni.parser.XMLComponent; import org.apache.xerces.xni.parser.XMLComponentManager; import org.apache.xerces.xni.parser.XMLConfigurationException; import org.apache.xerces.xni.parser.XMLDocumentFilter; import org.apache.xerces.xni.parser.XMLDocumentSource; import org.apache.xerces.xni.parser.XMLEntityResolver; import org.apache.xerces.xni.parser.XMLInputSource; import org.apache.xerces.xs.AttributePSVI; import org.apache.xerces.xs.ElementPSVI; import org.apache.xerces.xs.ShortList; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSTypeDefinition; /** * The XML Schema validator. The validator implements a document * filter: receiving document events from the scanner; validating * the content and structure; augmenting the InfoSet, if applicable; * and notifying the parser of the information resulting from the * validation process. * <p> * This component requires the following features and properties from the * component manager that uses it: * <ul> * <li>http://xml.org/sax/features/validation</li> * <li>http://apache.org/xml/properties/internal/symbol-table</li> * <li>http://apache.org/xml/properties/internal/error-reporter</li> * <li>http://apache.org/xml/properties/internal/entity-resolver</li> * </ul> * * @xerces.internal * * @author Sandy Gao IBM * @author Elena Litani IBM * @author Andy Clark IBM * @author Neeraj Bajaj, Sun Microsystems, inc. * @version $Id$ */ public class XMLSchemaValidator implements XMLComponent, XMLDocumentFilter, FieldActivator, RevalidationHandler, XSElementDeclHelper { // // Constants // private static final boolean DEBUG = false; // feature identifiers /** Feature identifier: validation. */ protected static final String VALIDATION = Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE; /** Feature identifier: validation. */ protected static final String SCHEMA_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE; /** Feature identifier: schema full checking*/ protected static final String SCHEMA_FULL_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_FULL_CHECKING; /** Feature identifier: dynamic validation. */ protected static final String DYNAMIC_VALIDATION = Constants.XERCES_FEATURE_PREFIX + Constants.DYNAMIC_VALIDATION_FEATURE; /** Feature identifier: expose schema normalized value */ protected static final String NORMALIZE_DATA = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_NORMALIZED_VALUE; /** Feature identifier: send element default value via characters() */ protected static final String SCHEMA_ELEMENT_DEFAULT = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_ELEMENT_DEFAULT; /** Feature identifier: augment PSVI */ protected static final String SCHEMA_AUGMENT_PSVI = Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_AUGMENT_PSVI; /** Feature identifier: whether to recognize java encoding names */ protected static final String ALLOW_JAVA_ENCODINGS = Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE; /** Feature identifier: standard uri conformant feature. */ protected static final String STANDARD_URI_CONFORMANT_FEATURE = Constants.XERCES_FEATURE_PREFIX + Constants.STANDARD_URI_CONFORMANT_FEATURE; /** Feature: generate synthetic annotations */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE; /** Feature identifier: validate annotations. */ protected static final String VALIDATE_ANNOTATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.VALIDATE_ANNOTATIONS_FEATURE; /** Feature identifier: honour all schemaLocations */ protected static final String HONOUR_ALL_SCHEMALOCATIONS = Constants.XERCES_FEATURE_PREFIX + Constants.HONOUR_ALL_SCHEMALOCATIONS_FEATURE; /** Feature identifier: use grammar pool only */ protected static final String USE_GRAMMAR_POOL_ONLY = Constants.XERCES_FEATURE_PREFIX + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE; /** Feature identifier: whether to continue parsing a schema after a fatal error is encountered */ protected static final String CONTINUE_AFTER_FATAL_ERROR = Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE; protected static final String PARSER_SETTINGS = Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; /** Feature identifier: namespace growth */ protected static final String NAMESPACE_GROWTH = Constants.XERCES_FEATURE_PREFIX + Constants.NAMESPACE_GROWTH_FEATURE; /** Feature identifier: tolerate duplicates */ protected static final String TOLERATE_DUPLICATES = Constants.XERCES_FEATURE_PREFIX + Constants.TOLERATE_DUPLICATES_FEATURE; /** Feature identifier: whether to ignore xsi:type attributes until a global element declaration is encountered */ protected static final String IGNORE_XSI_TYPE = Constants.XERCES_FEATURE_PREFIX + Constants.IGNORE_XSI_TYPE_FEATURE; /** Feature identifier: whether to ignore ID/IDREF errors */ protected static final String ID_IDREF_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.ID_IDREF_CHECKING_FEATURE; /** Feature identifier: whether to ignore unparsed entity errors */ protected static final String UNPARSED_ENTITY_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.UNPARSED_ENTITY_CHECKING_FEATURE; /** Feature identifier: whether to ignore identity constraint errors */ protected static final String IDENTITY_CONSTRAINT_CHECKING = Constants.XERCES_FEATURE_PREFIX + Constants.IDC_CHECKING_FEATURE; // property identifiers /** Property identifier: symbol table. */ public static final String SYMBOL_TABLE = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; /** Property identifier: error reporter. */ public static final String ERROR_REPORTER = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; /** Property identifier: entity resolver. */ public static final String ENTITY_RESOLVER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; /** Property identifier: grammar pool. */ public static final String XMLGRAMMAR_POOL = Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY; protected static final String VALIDATION_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; protected static final String ENTITY_MANAGER = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_MANAGER_PROPERTY; /** Property identifier: schema location. */ protected static final String SCHEMA_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_LOCATION; /** Property identifier: no namespace schema location. */ protected static final String SCHEMA_NONS_LOCATION = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_NONS_LOCATION; /** Property identifier: JAXP schema source. */ protected static final String JAXP_SCHEMA_SOURCE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_SOURCE; /** Property identifier: JAXP schema language. */ protected static final String JAXP_SCHEMA_LANGUAGE = Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE; /** Property identifier: root type definition. */ protected static final String ROOT_TYPE_DEF = Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_TYPE_DEFINITION_PROPERTY; /** Property identifier: root element declaration. */ protected static final String ROOT_ELEMENT_DECL = Constants.XERCES_PROPERTY_PREFIX + Constants.ROOT_ELEMENT_DECLARATION_PROPERTY; /** Property identifier: Schema DV Factory */ protected static final String SCHEMA_DV_FACTORY = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_DV_FACTORY_PROPERTY; // recognized features and properties /** Recognized features. */ private static final String[] RECOGNIZED_FEATURES = { VALIDATION, SCHEMA_VALIDATION, DYNAMIC_VALIDATION, SCHEMA_FULL_CHECKING, ALLOW_JAVA_ENCODINGS, CONTINUE_AFTER_FATAL_ERROR, STANDARD_URI_CONFORMANT_FEATURE, GENERATE_SYNTHETIC_ANNOTATIONS, VALIDATE_ANNOTATIONS, HONOUR_ALL_SCHEMALOCATIONS, USE_GRAMMAR_POOL_ONLY, IGNORE_XSI_TYPE, ID_IDREF_CHECKING, IDENTITY_CONSTRAINT_CHECKING, UNPARSED_ENTITY_CHECKING, NAMESPACE_GROWTH, TOLERATE_DUPLICATES }; /** Feature defaults. */ private static final Boolean[] FEATURE_DEFAULTS = { null, // NOTE: The following defaults are nulled out on purpose. // If they are set, then when the XML Schema validator // is constructed dynamically, these values may override // those set by the application. This goes against the // whole purpose of XMLComponent#getFeatureDefault but // it can't be helped in this case. -Ac // NOTE: Instead of adding default values here, add them (and // the corresponding recognized features) to the objects // that have an XMLSchemaValidator instance as a member, // such as the parser configurations. -PM null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, //Boolean.FALSE, null, null, null, null, null, null, null, null, null, null, null }; /** Recognized properties. */ private static final String[] RECOGNIZED_PROPERTIES = { SYMBOL_TABLE, ERROR_REPORTER, ENTITY_RESOLVER, VALIDATION_MANAGER, SCHEMA_LOCATION, SCHEMA_NONS_LOCATION, JAXP_SCHEMA_SOURCE, JAXP_SCHEMA_LANGUAGE, ROOT_TYPE_DEF, ROOT_ELEMENT_DECL, SCHEMA_DV_FACTORY, }; /** Property defaults. */ private static final Object[] PROPERTY_DEFAULTS = { null, null, null, null, null, null, null, null, null, null, null}; // this is the number of valuestores of each kind // we expect an element to have. It's almost // never > 1; so leave it at that. protected static final int ID_CONSTRAINT_NUM = 1; // xsi:* attribute declarations static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); // private static final Hashtable EMPTY_TABLE = new Hashtable(); // // Data // /** current PSVI element info */ protected ElementPSVImpl fCurrentPSVI = new ElementPSVImpl(); // since it is the responsibility of each component to an // Augmentations parameter if one is null, to save ourselves from // having to create this object continually, it is created here. // If it is not present in calls that we're passing on, we *must* // clear this before we introduce it into the pipeline. protected final AugmentationsImpl fAugmentations = new AugmentationsImpl(); // this is included for the convenience of handleEndElement protected XMLString fDefaultValue; // Validation features protected boolean fDynamicValidation = false; protected boolean fSchemaDynamicValidation = false; protected boolean fDoValidation = false; protected boolean fFullChecking = false; protected boolean fNormalizeData = true; protected boolean fSchemaElementDefault = true; protected boolean fAugPSVI = true; protected boolean fIdConstraint = false; protected boolean fUseGrammarPoolOnly = false; // Namespace growth feature protected boolean fNamespaceGrowth = false; /** Schema type: None, DTD, Schema */ private String fSchemaType = null; // to indicate whether we are in the scope of entity reference or CData protected boolean fEntityRef = false; protected boolean fInCDATA = false; // properties /** Symbol table. */ protected SymbolTable fSymbolTable; /** * While parsing a document, keep the location of the document. */ private XMLLocator fLocator; /** * A wrapper of the standard error reporter. We'll store all schema errors * in this wrapper object, so that we can get all errors (error codes) of * a specific element. This is useful for PSVI. */ protected final class XSIErrorReporter { // the error reporter property XMLErrorReporter fErrorReporter; // store error codes; starting position of the errors for each element; // number of element (depth); and whether to record error Vector fErrors = new Vector(); int[] fContext = new int[INITIAL_STACK_SIZE]; int fContextCount; // set the external error reporter, clear errors public void reset(XMLErrorReporter errorReporter) { fErrorReporter = errorReporter; fErrors.removeAllElements(); fContextCount = 0; } // should be called when starting process an element or an attribute. // store the starting position for the current context public void pushContext() { if (!fAugPSVI) { return; } // resize array if necessary if (fContextCount == fContext.length) { int newSize = fContextCount + INC_STACK_SIZE; int[] newArray = new int[newSize]; System.arraycopy(fContext, 0, newArray, 0, fContextCount); fContext = newArray; } fContext[fContextCount++] = fErrors.size(); } // should be called on endElement: get all errors of the current element public String[] popContext() { if (!fAugPSVI) { return null; } // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String) fErrors.elementAt(contextPos + i); } // remove errors of the current element fErrors.setSize(contextPos); return errors; } // should be called when an attribute is done: get all errors of // this attribute, but leave the errors to the containing element // also called after an element was strictly assessed. public String[] mergeContext() { if (!fAugPSVI) { return null; } // get starting position of the current element int contextPos = fContext[--fContextCount]; // number of errors of the current element int size = fErrors.size() - contextPos; // if no errors, return null if (size == 0) return null; // copy errors from the list to an string array String[] errors = new String[size]; for (int i = 0; i < size; i++) { errors[i] = (String) fErrors.elementAt(contextPos + i); } // don't resize the vector: leave the errors for this attribute // to the containing element return errors; } public void reportError(String domain, String key, Object[] arguments, short severity) throws XNIException { String message = fErrorReporter.reportError(domain, key, arguments, severity); if (fAugPSVI) { fErrors.addElement(key); fErrors.addElement(message); } } // reportError(String,String,Object[],short) public void reportError( XMLLocator location, String domain, String key, Object[] arguments, short severity) throws XNIException { String message = fErrorReporter.reportError(location, domain, key, arguments, severity); if (fAugPSVI) { fErrors.addElement(key); fErrors.addElement(message); } } // reportError(XMLLocator,String,String,Object[],short) } /** Error reporter. */ protected final XSIErrorReporter fXSIErrorReporter = new XSIErrorReporter(); /** Entity resolver */ protected XMLEntityResolver fEntityResolver; // updated during reset protected ValidationManager fValidationManager = null; protected ConfigurableValidationState fValidationState = new ConfigurableValidationState(); protected XMLGrammarPool fGrammarPool; // schema location property values protected String fExternalSchemas = null; protected String fExternalNoNamespaceSchema = null; //JAXP Schema Source property protected Object fJaxpSchemaSource = null; /** Schema Grammar Description passed, to give a chance to application to supply the Grammar */ protected final XSDDescription fXSDDescription = new XSDDescription(); protected final Hashtable fLocationPairs = new Hashtable(); protected final Hashtable fExpandedLocationPairs = new Hashtable(); protected final ArrayList fUnparsedLocations = new ArrayList(); // handlers /** Document handler. */ protected XMLDocumentHandler fDocumentHandler; protected XMLDocumentSource fDocumentSource; // // XMLComponent methods // /** * Returns a list of feature identifiers that are recognized by * this component. This method may return null if no features * are recognized by this component. */ public String[] getRecognizedFeatures() { return (String[]) (RECOGNIZED_FEATURES.clone()); } // getRecognizedFeatures():String[] /** * Sets the state of a feature. This method is called by the component * manager any time after reset when a feature changes state. * <p> * <strong>Note:</strong> Components should silently ignore features * that do not affect the operation of the component. * * @param featureId The feature identifier. * @param state The state of the feature. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setFeature(String featureId, boolean state) throws XMLConfigurationException { } // setFeature(String,boolean) /** * Returns a list of property identifiers that are recognized by * this component. This method may return null if no properties * are recognized by this component. */ public String[] getRecognizedProperties() { return (String[]) (RECOGNIZED_PROPERTIES.clone()); } // getRecognizedProperties():String[] /** * Sets the value of a property. This method is called by the component * manager any time after reset when a property changes value. * <p> * <strong>Note:</strong> Components should silently ignore properties * that do not affect the operation of the component. * * @param propertyId The property identifier. * @param value The value of the property. * * @throws SAXNotRecognizedException The component should not throw * this exception. * @throws SAXNotSupportedException The component should not throw * this exception. */ public void setProperty(String propertyId, Object value) throws XMLConfigurationException { if (propertyId.equals(ROOT_TYPE_DEF)) { if (value == null) { fRootTypeQName = null; fRootTypeDefinition = null; } else if (value instanceof javax.xml.namespace.QName) { fRootTypeQName = (javax.xml.namespace.QName) value; fRootTypeDefinition = null; } else { fRootTypeDefinition = (XSTypeDefinition) value; fRootTypeQName = null; } } else if (propertyId.equals(ROOT_ELEMENT_DECL)) { if (value == null) { fRootElementDeclQName = null; fRootElementDeclaration = null; } else if (value instanceof javax.xml.namespace.QName) { fRootElementDeclQName = (javax.xml.namespace.QName) value; fRootElementDeclaration = null; } else { fRootElementDeclaration = (XSElementDecl) value; fRootElementDeclQName = null; } } } // setProperty(String,Object) /** * Returns the default state for a feature, or null if this * component does not want to report a default value for this * feature. * * @param featureId The feature identifier. * * @since Xerces 2.2.0 */ public Boolean getFeatureDefault(String featureId) { for (int i = 0; i < RECOGNIZED_FEATURES.length; i++) { if (RECOGNIZED_FEATURES[i].equals(featureId)) { return FEATURE_DEFAULTS[i]; } } return null; } // getFeatureDefault(String):Boolean /** * Returns the default state for a property, or null if this * component does not want to report a default value for this * property. * * @param propertyId The property identifier. * * @since Xerces 2.2.0 */ public Object getPropertyDefault(String propertyId) { for (int i = 0; i < RECOGNIZED_PROPERTIES.length; i++) { if (RECOGNIZED_PROPERTIES[i].equals(propertyId)) { return PROPERTY_DEFAULTS[i]; } } return null; } // getPropertyDefault(String):Object // // XMLDocumentSource methods // /** Sets the document handler to receive information about the document. */ public void setDocumentHandler(XMLDocumentHandler documentHandler) { fDocumentHandler = documentHandler; } // setDocumentHandler(XMLDocumentHandler) /** Returns the document handler */ public XMLDocumentHandler getDocumentHandler() { return fDocumentHandler; } // setDocumentHandler(XMLDocumentHandler) // // XMLDocumentHandler methods // /** Sets the document source */ public void setDocumentSource(XMLDocumentSource source) { fDocumentSource = source; } // setDocumentSource /** Returns the document source */ public XMLDocumentSource getDocumentSource() { return fDocumentSource; } // getDocumentSource /** * The start of the document. * * @param locator The system identifier of the entity if the entity * is external, null otherwise. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param namespaceContext * The namespace context in effect at the * start of this document. * This object represents the current context. * Implementors of this class are responsible * for copying the namespace bindings from the * the current context (and its parent contexts) * if that information is important. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startDocument( XMLLocator locator, String encoding, NamespaceContext namespaceContext, Augmentations augs) throws XNIException { fValidationState.setNamespaceSupport(namespaceContext); fState4XsiType.setNamespaceSupport(namespaceContext); fState4ApplyDefault.setNamespaceSupport(namespaceContext); fLocator = locator; handleStartDocument(locator, encoding); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startDocument(locator, encoding, namespaceContext, augs); } } // startDocument(XMLLocator,String) /** * Notifies of the presence of an XMLDecl line in the document. If * present, this method will be called immediately following the * startDocument call. * * @param version The XML version. * @param encoding The IANA encoding name of the document, or null if * not specified. * @param standalone The standalone value, or null if not specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void xmlDecl(String version, String encoding, String standalone, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.xmlDecl(version, encoding, standalone, augs); } } // xmlDecl(String,String,String) /** * Notifies of the presence of the DOCTYPE line in the document. * * @param rootElement The name of the root element. * @param publicId The public identifier if an external DTD or null * if the external DTD is specified using SYSTEM. * @param systemId The system identifier if an external DTD, null * otherwise. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void doctypeDecl( String rootElement, String publicId, String systemId, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.doctypeDecl(rootElement, publicId, systemId, augs); } } // doctypeDecl(String,String,String) /** * The start of an element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // call handlers if (fDocumentHandler != null) { fDocumentHandler.startElement(element, attributes, modifiedAugs); } } // startElement(QName,XMLAttributes, Augmentations) /** * An empty element. * * @param element The name of the element. * @param attributes The element attributes. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void emptyElement(QName element, XMLAttributes attributes, Augmentations augs) throws XNIException { Augmentations modifiedAugs = handleStartElement(element, attributes, augs); // in the case where there is a {value constraint}, and the element // doesn't have any text content, change emptyElement call to // start + characters + end fDefaultValue = null; // fElementDepth == -2 indicates that the schema validator was removed // from the pipeline. then we don't need to call handleEndElement. if (fElementDepth != -2) modifiedAugs = handleEndElement(element, modifiedAugs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.emptyElement(element, attributes, modifiedAugs); } else { fDocumentHandler.startElement(element, attributes, modifiedAugs); fDocumentHandler.characters(fDefaultValue, null); fDocumentHandler.endElement(element, modifiedAugs); } } } // emptyElement(QName,XMLAttributes, Augmentations) /** * Character content. * * @param text The content. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void characters(XMLString text, Augmentations augs) throws XNIException { text = handleCharacters(text); // call handlers if (fDocumentHandler != null) { if (fNormalizeData && fUnionType) { // for union types we can't normalize data // thus we only need to send augs information if any; // the normalized data for union will be send // after normalization is performed (at the endElement()) if (augs != null) fDocumentHandler.characters(fEmptyXMLStr, augs); } else { fDocumentHandler.characters(text, augs); } } } // characters(XMLString) /** * Ignorable whitespace. For this method to be called, the document * source must have some way of determining that the text containing * only whitespace characters should be considered ignorable. For * example, the validator can determine if a length of whitespace * characters in the document are ignorable based on the element * content model. * * @param text The ignorable whitespace. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void ignorableWhitespace(XMLString text, Augmentations augs) throws XNIException { handleIgnorableWhitespace(text); // call handlers if (fDocumentHandler != null) { fDocumentHandler.ignorableWhitespace(text, augs); } } // ignorableWhitespace(XMLString) /** * The end of an element. * * @param element The name of the element. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endElement(QName element, Augmentations augs) throws XNIException { // in the case where there is a {value constraint}, and the element // doesn't have any text content, add a characters call. fDefaultValue = null; Augmentations modifiedAugs = handleEndElement(element, augs); // call handlers if (fDocumentHandler != null) { if (!fSchemaElementDefault || fDefaultValue == null) { fDocumentHandler.endElement(element, modifiedAugs); } else { fDocumentHandler.characters(fDefaultValue, null); fDocumentHandler.endElement(element, modifiedAugs); } } } // endElement(QName, Augmentations) /** * The start of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void startCDATA(Augmentations augs) throws XNIException { // REVISIT: what should we do here if schema normalization is on?? fInCDATA = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startCDATA(augs); } } // startCDATA() /** * The end of a CDATA section. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endCDATA(Augmentations augs) throws XNIException { // call handlers fInCDATA = false; if (fDocumentHandler != null) { fDocumentHandler.endCDATA(augs); } } // endCDATA() /** * The end of the document. * * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void endDocument(Augmentations augs) throws XNIException { handleEndDocument(); // call handlers if (fDocumentHandler != null) { fDocumentHandler.endDocument(augs); } fLocator = null; } // endDocument(Augmentations) // // DOMRevalidationHandler methods // public boolean characterData(String data, Augmentations augs) { fSawText = fSawText || data.length() > 0; // REVISIT: this methods basically duplicates implementation of // handleCharacters(). We should be able to reuse some code // if whitespace == -1 skip normalization, because it is a complexType // or a union type. if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data normalizeWhitespace(data, fWhiteSpace == XSSimpleType.WS_COLLAPSE); fBuffer.append(fNormalizedStr.ch, fNormalizedStr.offset, fNormalizedStr.length); } else { if (fAppendBuffer) fBuffer.append(data); } // When it's a complex type with element-only content, we need to // find out whether the content contains any non-whitespace character. boolean allWhiteSpace = true; if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // data outside of element content for (int i = 0; i < data.length(); i++) { if (!XMLChar.isSpace(data.charAt(i))) { allWhiteSpace = false; fSawCharacters = true; break; } } } } return allWhiteSpace; } public void elementDefault(String data) { // no-op } // // XMLDocumentHandler and XMLDTDHandler methods // /** * This method notifies the start of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the general entity. * @param identifier The resource identifier. * @param encoding The auto-detected IANA encoding name of the entity * stream. This value will be null in those situations * where the entity encoding is not auto-detected (e.g. * internal entities or a document entity that is * parsed from a java.io.Reader). * @param augs Additional information that may include infoset augmentations * * @exception XNIException Thrown by handler to signal an error. */ public void startGeneralEntity( String name, XMLResourceIdentifier identifier, String encoding, Augmentations augs) throws XNIException { // REVISIT: what should happen if normalize_data_ is on?? fEntityRef = true; // call handlers if (fDocumentHandler != null) { fDocumentHandler.startGeneralEntity(name, identifier, encoding, augs); } } // startEntity(String,String,String,String,String) /** * Notifies of the presence of a TextDecl line in an entity. If present, * this method will be called immediately following the startEntity call. * <p> * <strong>Note:</strong> This method will never be called for the * document entity; it is only called for external general entities * referenced in document content. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param version The XML version, or null if not specified. * @param encoding The IANA encoding name of the entity. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void textDecl(String version, String encoding, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.textDecl(version, encoding, augs); } } // textDecl(String,String) /** * A comment. * * @param text The text in the comment. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by application to signal an error. */ public void comment(XMLString text, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.comment(text, augs); } } // comment(XMLString) /** * A processing instruction. Processing instructions consist of a * target name and, optionally, text data. The data is only meaningful * to the application. * <p> * Typically, a processing instruction's data will contain a series * of pseudo-attributes. These pseudo-attributes follow the form of * element attributes but are <strong>not</strong> parsed or presented * to the application as anything other than text. The application is * responsible for parsing the data. * * @param target The target. * @param data The data or null if none specified. * @param augs Additional information that may include infoset augmentations * * @throws XNIException Thrown by handler to signal an error. */ public void processingInstruction(String target, XMLString data, Augmentations augs) throws XNIException { // call handlers if (fDocumentHandler != null) { fDocumentHandler.processingInstruction(target, data, augs); } } // processingInstruction(String,XMLString) /** * This method notifies the end of a general entity. * <p> * <strong>Note:</strong> This method is not called for entity references * appearing as part of attribute values. * * @param name The name of the entity. * @param augs Additional information that may include infoset augmentations * * @exception XNIException * Thrown by handler to signal an error. */ public void endGeneralEntity(String name, Augmentations augs) throws XNIException { // call handlers fEntityRef = false; if (fDocumentHandler != null) { fDocumentHandler.endGeneralEntity(name, augs); } } // endEntity(String) // constants static final int INITIAL_STACK_SIZE = 8; static final int INC_STACK_SIZE = 8; // // Data // // Schema Normalization private static final boolean DEBUG_NORMALIZATION = false; // temporary empty string buffer. private final XMLString fEmptyXMLStr = new XMLString(null, 0, -1); // temporary character buffer, and empty string buffer. private static final int BUFFER_SIZE = 20; private final XMLString fNormalizedStr = new XMLString(); private boolean fFirstChunk = true; // got first chunk in characters() (SAX) private boolean fTrailing = false; // Previous chunk had a trailing space private short fWhiteSpace = -1; //whiteSpace: preserve/replace/collapse private boolean fUnionType = false; /** Schema grammar resolver. */ private final XSGrammarBucket fGrammarBucket = new XSGrammarBucket(); private final SubstitutionGroupHandler fSubGroupHandler = new SubstitutionGroupHandler(this); /** the DV usd to convert xsi:type to a QName */ // REVISIT: in new simple type design, make things in DVs static, // so that we can QNameDV.getCompiledForm() private final XSSimpleType fQNameDV = (XSSimpleType) SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_QNAME); private final CMNodeFactory nodeFactory = new CMNodeFactory(); /** used to build content models */ // REVISIT: create decl pool, and pass it to each traversers private final CMBuilder fCMBuilder = new CMBuilder(nodeFactory); // Schema grammar loader private final XMLSchemaLoader fSchemaLoader = new XMLSchemaLoader( fXSIErrorReporter.fErrorReporter, fGrammarBucket, fSubGroupHandler, fCMBuilder); // state /** String representation of the validation root. */ // REVISIT: what do we store here? QName, XPATH, some ID? use rawname now. private String fValidationRoot; /** Skip validation: anything below this level should be skipped */ private int fSkipValidationDepth; /** anything above this level has validation_attempted != full */ private int fNFullValidationDepth; /** anything above this level has validation_attempted != none */ private int fNNoneValidationDepth; /** Element depth: -2: validator not in pipeline; >= -1 current depth. */ private int fElementDepth; /** Seen sub elements. */ private boolean fSubElement; /** Seen sub elements stack. */ private boolean[] fSubElementStack = new boolean[INITIAL_STACK_SIZE]; /** Current element declaration. */ private XSElementDecl fCurrentElemDecl; /** Element decl stack. */ private XSElementDecl[] fElemDeclStack = new XSElementDecl[INITIAL_STACK_SIZE]; /** nil value of the current element */ private boolean fNil; /** nil value stack */ private boolean[] fNilStack = new boolean[INITIAL_STACK_SIZE]; /** notation value of the current element */ private XSNotationDecl fNotation; /** notation stack */ private XSNotationDecl[] fNotationStack = new XSNotationDecl[INITIAL_STACK_SIZE]; /** Current type. */ private XSTypeDefinition fCurrentType; /** type stack. */ private XSTypeDefinition[] fTypeStack = new XSTypeDefinition[INITIAL_STACK_SIZE]; /** Current content model. */ private XSCMValidator fCurrentCM; /** Content model stack. */ private XSCMValidator[] fCMStack = new XSCMValidator[INITIAL_STACK_SIZE]; /** the current state of the current content model */ private int[] fCurrCMState; /** stack to hold content model states */ private int[][] fCMStateStack = new int[INITIAL_STACK_SIZE][]; /** whether the curret element is strictly assessed */ private boolean fStrictAssess = true; /** strict assess stack */ private boolean[] fStrictAssessStack = new boolean[INITIAL_STACK_SIZE]; /** Temporary string buffers. */ private final StringBuffer fBuffer = new StringBuffer(); /** Whether need to append characters to fBuffer */ private boolean fAppendBuffer = true; /** Did we see any character data? */ private boolean fSawText = false; /** stack to record if we saw character data */ private boolean[] fSawTextStack = new boolean[INITIAL_STACK_SIZE]; /** Did we see non-whitespace character data? */ private boolean fSawCharacters = false; /** Stack to record if we saw character data outside of element content*/ private boolean[] fStringContent = new boolean[INITIAL_STACK_SIZE]; /** temporary qname */ private final QName fTempQName = new QName(); /** value of the "root-type-definition" property. */ private javax.xml.namespace.QName fRootTypeQName = null; private XSTypeDefinition fRootTypeDefinition = null; /** value of the "root-element-declaration" property. */ private javax.xml.namespace.QName fRootElementDeclQName = null; private XSElementDecl fRootElementDeclaration = null; private int fIgnoreXSITypeDepth; private boolean fIDCChecking; /** temporary validated info */ private ValidatedInfo fValidatedInfo = new ValidatedInfo(); // used to validate default/fixed values against xsi:type // only need to check facets, so we set extraChecking to false (in reset) private ValidationState fState4XsiType = new ValidationState(); // used to apply default/fixed values // only need to check id/idref/entity, so we set checkFacets to false private ValidationState fState4ApplyDefault = new ValidationState(); // identity constraint information /** * Stack of active XPath matchers for identity constraints. All * active XPath matchers are notified of startElement * and endElement callbacks in order to perform their matches. * <p> * For each element with identity constraints, the selector of * each identity constraint is activated. When the selector matches * its XPath, then all the fields of the identity constraint are * activated. * <p> * <strong>Note:</strong> Once the activation scope is left, the * XPath matchers are automatically removed from the stack of * active matchers and no longer receive callbacks. */ protected XPathMatcherStack fMatcherStack = new XPathMatcherStack(); /** Cache of value stores for identity constraint fields. */ protected ValueStoreCache fValueStoreCache = new ValueStoreCache(); // // Constructors // /** Default constructor. */ public XMLSchemaValidator() { fState4XsiType.setExtraChecking(false); fState4ApplyDefault.setFacetChecking(false); } // <init>() /* * Resets the component. The component can query the component manager * about any features and properties that affect the operation of the * component. * * @param componentManager The component manager. * * @throws SAXException Thrown by component on finitialization error. * For example, if a feature or property is * required for the operation of the component, the * component manager may throw a * SAXNotRecognizedException or a * SAXNotSupportedException. */ public void reset(XMLComponentManager componentManager) throws XMLConfigurationException { fIdConstraint = false; //reset XSDDescription fLocationPairs.clear(); fExpandedLocationPairs.clear(); // cleanup id table fValidationState.resetIDTables(); // reset schema loader fSchemaLoader.reset(componentManager); // initialize state fCurrentElemDecl = null; fCurrentCM = null; fCurrCMState = null; fSkipValidationDepth = -1; fNFullValidationDepth = -1; fNNoneValidationDepth = -1; fElementDepth = -1; fSubElement = false; fSchemaDynamicValidation = false; // datatype normalization fEntityRef = false; fInCDATA = false; fMatcherStack.clear(); // get error reporter fXSIErrorReporter.reset((XMLErrorReporter) componentManager.getProperty(ERROR_REPORTER)); boolean parser_settings; try { parser_settings = componentManager.getFeature(PARSER_SETTINGS); } catch (XMLConfigurationException e){ parser_settings = true; } if (!parser_settings) { // parser settings have not been changed fValidationManager.addValidationState(fValidationState); // the node limit on the SecurityManager may have changed so need to refresh. nodeFactory.reset(); // Re-parse external schema location properties. XMLSchemaLoader.processExternalHints( fExternalSchemas, fExternalNoNamespaceSchema, fLocationPairs, fXSIErrorReporter.fErrorReporter); return; } // pass the component manager to the factory.. nodeFactory.reset(componentManager); // get symbol table. if it's a new one, add symbols to it. SymbolTable symbolTable = (SymbolTable) componentManager.getProperty(SYMBOL_TABLE); if (symbolTable != fSymbolTable) { fSymbolTable = symbolTable; } try { fNamespaceGrowth = componentManager.getFeature(NAMESPACE_GROWTH); } catch (XMLConfigurationException e) { fNamespaceGrowth = false; } try { fDynamicValidation = componentManager.getFeature(DYNAMIC_VALIDATION); } catch (XMLConfigurationException e) { fDynamicValidation = false; } if (fDynamicValidation) { fDoValidation = true; } else { try { fDoValidation = componentManager.getFeature(VALIDATION); } catch (XMLConfigurationException e) { fDoValidation = false; } } if (fDoValidation) { try { fDoValidation = componentManager.getFeature(XMLSchemaValidator.SCHEMA_VALIDATION); } catch (XMLConfigurationException e) { } } try { fFullChecking = componentManager.getFeature(SCHEMA_FULL_CHECKING); } catch (XMLConfigurationException e) { fFullChecking = false; } try { fNormalizeData = componentManager.getFeature(NORMALIZE_DATA); } catch (XMLConfigurationException e) { fNormalizeData = false; } try { fSchemaElementDefault = componentManager.getFeature(SCHEMA_ELEMENT_DEFAULT); } catch (XMLConfigurationException e) { fSchemaElementDefault = false; } try { fAugPSVI = componentManager.getFeature(SCHEMA_AUGMENT_PSVI); } catch (XMLConfigurationException e) { fAugPSVI = true; } try { fSchemaType = (String) componentManager.getProperty( Constants.JAXP_PROPERTY_PREFIX + Constants.SCHEMA_LANGUAGE); } catch (XMLConfigurationException e) { fSchemaType = null; } try { fUseGrammarPoolOnly = componentManager.getFeature(USE_GRAMMAR_POOL_ONLY); } catch (XMLConfigurationException e) { fUseGrammarPoolOnly = false; } fEntityResolver = (XMLEntityResolver) componentManager.getProperty(ENTITY_MANAGER); fValidationManager = (ValidationManager) componentManager.getProperty(VALIDATION_MANAGER); fValidationManager.addValidationState(fValidationState); fValidationState.setSymbolTable(fSymbolTable); try { final Object rootType = componentManager.getProperty(ROOT_TYPE_DEF); if (rootType == null) { fRootTypeQName = null; fRootTypeDefinition = null; } else if (rootType instanceof javax.xml.namespace.QName) { fRootTypeQName = (javax.xml.namespace.QName) rootType; fRootTypeDefinition = null; } else { fRootTypeDefinition = (XSTypeDefinition) rootType; fRootTypeQName = null; } } catch (XMLConfigurationException e) { fRootTypeQName = null; fRootTypeDefinition = null; } try { final Object rootDecl = componentManager.getProperty(ROOT_ELEMENT_DECL); if (rootDecl == null) { fRootElementDeclQName = null; fRootElementDeclaration = null; } else if (rootDecl instanceof javax.xml.namespace.QName) { fRootElementDeclQName = (javax.xml.namespace.QName) rootDecl; fRootElementDeclaration = null; } else { fRootElementDeclaration = (XSElementDecl) rootDecl; fRootElementDeclQName = null; } } catch (XMLConfigurationException e) { fRootElementDeclQName = null; fRootElementDeclaration = null; } boolean ignoreXSIType; try { ignoreXSIType = componentManager.getFeature(IGNORE_XSI_TYPE); } catch (XMLConfigurationException e) { ignoreXSIType = false; } // An initial value of -1 means that the root element considers itself // below the depth where xsi:type stopped being ignored (which means that // xsi:type attributes will not be ignored for the entire document) fIgnoreXSITypeDepth = ignoreXSIType ? 0 : -1; try { fIDCChecking = componentManager.getFeature(IDENTITY_CONSTRAINT_CHECKING); } catch (XMLConfigurationException e) { fIDCChecking = true; } try { fValidationState.setIdIdrefChecking(componentManager.getFeature(ID_IDREF_CHECKING)); } catch (XMLConfigurationException e) { fValidationState.setIdIdrefChecking(true); } try { fValidationState.setUnparsedEntityChecking(componentManager.getFeature(UNPARSED_ENTITY_CHECKING)); } catch (XMLConfigurationException e) { fValidationState.setUnparsedEntityChecking(true); } // get schema location properties try { fExternalSchemas = (String) componentManager.getProperty(SCHEMA_LOCATION); fExternalNoNamespaceSchema = (String) componentManager.getProperty(SCHEMA_NONS_LOCATION); } catch (XMLConfigurationException e) { fExternalSchemas = null; fExternalNoNamespaceSchema = null; } // store the external schema locations. they are set when reset is called, // so any other schemaLocation declaration for the same namespace will be // effectively ignored. becuase we choose to take first location hint // available for a particular namespace. XMLSchemaLoader.processExternalHints( fExternalSchemas, fExternalNoNamespaceSchema, fLocationPairs, fXSIErrorReporter.fErrorReporter); try { fJaxpSchemaSource = componentManager.getProperty(JAXP_SCHEMA_SOURCE); } catch (XMLConfigurationException e) { fJaxpSchemaSource = null; } // clear grammars, and put the one for schema namespace there try { fGrammarPool = (XMLGrammarPool) componentManager.getProperty(XMLGRAMMAR_POOL); } catch (XMLConfigurationException e) { fGrammarPool = null; } fState4XsiType.setSymbolTable(symbolTable); fState4ApplyDefault.setSymbolTable(symbolTable); } // reset(XMLComponentManager) // // FieldActivator methods // /** * Start the value scope for the specified identity constraint. This * method is called when the selector matches in order to initialize * the value store. * * @param identityConstraint The identity constraint. */ public void startValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.startValueScope(); } // startValueScopeFor(IdentityConstraint identityConstraint) /** * Request to activate the specified field. This method returns the * matcher for the field. * * @param field The field to activate. */ public XPathMatcher activateField(Field field, int initialDepth) { ValueStore valueStore = fValueStoreCache.getValueStoreFor(field.getIdentityConstraint(), initialDepth); XPathMatcher matcher = field.createMatcher(valueStore); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(); return matcher; } // activateField(Field):XPathMatcher /** * Ends the value scope for the specified identity constraint. * * @param identityConstraint The identity constraint. */ public void endValueScopeFor(IdentityConstraint identityConstraint, int initialDepth) { ValueStoreBase valueStore = fValueStoreCache.getValueStoreFor(identityConstraint, initialDepth); valueStore.endValueScope(); } // endValueScopeFor(IdentityConstraint) // a utility method for Identity constraints private void activateSelectorFor(IdentityConstraint ic) { Selector selector = ic.getSelector(); FieldActivator activator = this; if (selector == null) return; XPathMatcher matcher = selector.createMatcher(activator, fElementDepth); fMatcherStack.addMatcher(matcher); matcher.startDocumentFragment(); } // Implements XSElementDeclHelper interface public XSElementDecl getGlobalElementDecl(QName element) { final SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, null); if (sGrammar != null) { return sGrammar.getGlobalElementDecl(element.localpart); } return null; } // // Protected methods // /** ensure element stack capacity */ void ensureStackCapacity() { if (fElementDepth == fElemDeclStack.length) { int newSize = fElementDepth + INC_STACK_SIZE; boolean[] newArrayB = new boolean[newSize]; System.arraycopy(fSubElementStack, 0, newArrayB, 0, fElementDepth); fSubElementStack = newArrayB; XSElementDecl[] newArrayE = new XSElementDecl[newSize]; System.arraycopy(fElemDeclStack, 0, newArrayE, 0, fElementDepth); fElemDeclStack = newArrayE; newArrayB = new boolean[newSize]; System.arraycopy(fNilStack, 0, newArrayB, 0, fElementDepth); fNilStack = newArrayB; XSNotationDecl[] newArrayN = new XSNotationDecl[newSize]; System.arraycopy(fNotationStack, 0, newArrayN, 0, fElementDepth); fNotationStack = newArrayN; XSTypeDefinition[] newArrayT = new XSTypeDefinition[newSize]; System.arraycopy(fTypeStack, 0, newArrayT, 0, fElementDepth); fTypeStack = newArrayT; XSCMValidator[] newArrayC = new XSCMValidator[newSize]; System.arraycopy(fCMStack, 0, newArrayC, 0, fElementDepth); fCMStack = newArrayC; newArrayB = new boolean[newSize]; System.arraycopy(fSawTextStack, 0, newArrayB, 0, fElementDepth); fSawTextStack = newArrayB; newArrayB = new boolean[newSize]; System.arraycopy(fStringContent, 0, newArrayB, 0, fElementDepth); fStringContent = newArrayB; newArrayB = new boolean[newSize]; System.arraycopy(fStrictAssessStack, 0, newArrayB, 0, fElementDepth); fStrictAssessStack = newArrayB; int[][] newArrayIA = new int[newSize][]; System.arraycopy(fCMStateStack, 0, newArrayIA, 0, fElementDepth); fCMStateStack = newArrayIA; } } // ensureStackCapacity // handle start document void handleStartDocument(XMLLocator locator, String encoding) { if (fIDCChecking) { fValueStoreCache.startDocument(); } if (fAugPSVI) { fCurrentPSVI.fGrammars = null; fCurrentPSVI.fSchemaInformation = null; } } // handleStartDocument(XMLLocator,String) void handleEndDocument() { if (fIDCChecking) { fValueStoreCache.endDocument(); } } // handleEndDocument() // handle character contents // returns the normalized string if possible, otherwise the original string XMLString handleCharacters(XMLString text) { if (fSkipValidationDepth >= 0) return text; fSawText = fSawText || text.length > 0; // Note: data in EntityRef and CDATA is normalized as well // if whitespace == -1 skip normalization, because it is a complexType // or a union type. if (fNormalizeData && fWhiteSpace != -1 && fWhiteSpace != XSSimpleType.WS_PRESERVE) { // normalize data normalizeWhitespace(text, fWhiteSpace == XSSimpleType.WS_COLLAPSE); text = fNormalizedStr; } if (fAppendBuffer) fBuffer.append(text.ch, text.offset, text.length); // When it's a complex type with element-only content, we need to // find out whether the content contains any non-whitespace character. if (fCurrentType != null && fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { // data outside of element content for (int i = text.offset; i < text.offset + text.length; i++) { if (!XMLChar.isSpace(text.ch[i])) { fSawCharacters = true; break; } } } } return text; } // handleCharacters(XMLString) /** * Normalize whitespace in an XMLString according to the rules defined * in XML Schema specifications. * @param value The string to normalize. * @param collapse replace or collapse */ private void normalizeWhitespace(XMLString value, boolean collapse) { boolean skipSpace = collapse; boolean sawNonWS = false; boolean leading = false; boolean trailing = false; char c; int size = value.offset + value.length; // ensure the ch array is big enough if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < value.length + 1) { fNormalizedStr.ch = new char[value.length + 1]; } // don't include the leading ' ' for now. might include it later. fNormalizedStr.offset = 1; fNormalizedStr.length = 1; for (int i = value.offset; i < size; i++) { c = value.ch[i]; if (XMLChar.isSpace(c)) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.ch[fNormalizedStr.length++] = ' '; skipSpace = collapse; } if (!sawNonWS) { // this is a leading whitespace, record it leading = true; } } else { fNormalizedStr.ch[fNormalizedStr.length++] = c; skipSpace = false; sawNonWS = true; } } if (skipSpace) { if (fNormalizedStr.length > 1) { // if we finished on a space trim it but also record it fNormalizedStr.length--; trailing = true; } else if (leading && !fFirstChunk) { // if all we had was whitespace we skipped record it as // trailing whitespace as well trailing = true; } } if (fNormalizedStr.length > 1) { if (!fFirstChunk && (fWhiteSpace == XSSimpleType.WS_COLLAPSE)) { if (fTrailing) { // previous chunk ended on whitespace // insert whitespace fNormalizedStr.offset = 0; fNormalizedStr.ch[0] = ' '; } else if (leading) { // previous chunk ended on character, // this chunk starts with whitespace fNormalizedStr.offset = 0; fNormalizedStr.ch[0] = ' '; } } } // The length includes the leading ' '. Now removing it. fNormalizedStr.length -= fNormalizedStr.offset; fTrailing = trailing; if (trailing || sawNonWS) fFirstChunk = false; } private void normalizeWhitespace(String value, boolean collapse) { boolean skipSpace = collapse; char c; int size = value.length(); // ensure the ch array is big enough if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < size) { fNormalizedStr.ch = new char[size]; } fNormalizedStr.offset = 0; fNormalizedStr.length = 0; for (int i = 0; i < size; i++) { c = value.charAt(i); if (XMLChar.isSpace(c)) { if (!skipSpace) { // take the first whitespace as a space and skip the others fNormalizedStr.ch[fNormalizedStr.length++] = ' '; skipSpace = collapse; } } else { fNormalizedStr.ch[fNormalizedStr.length++] = c; skipSpace = false; } } if (skipSpace) { if (fNormalizedStr.length != 0) // if we finished on a space trim it but also record it fNormalizedStr.length--; } } // handle ignorable whitespace void handleIgnorableWhitespace(XMLString text) { if (fSkipValidationDepth >= 0) return; // REVISIT: the same process needs to be performed as handleCharacters. // only it's simpler here: we know all characters are whitespaces. } // handleIgnorableWhitespace(XMLString) /** Handle element. */ Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { - reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); + reportSchemaError("cvc-complex-type.2.4.f", new Object[] { fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.fAnyType; fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.fAnyType; else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } return augs; } // handleStartElement(QName,XMLAttributes,boolean) /** * Handle end element. If there is not text content, and there is a * {value constraint} on the corresponding element decl, then * set the fDefaultValue XMLString representing the default value. */ Augmentations handleEndElement(QName element, Augmentations augs) { if (DEBUG) { System.out.println("==>handleEndElement:" + element); } // if we are skipping, return if (fSkipValidationDepth >= 0) { // but if this is the top element that we are skipping, // restore the states. if (fSkipValidationDepth == fElementDepth && fSkipValidationDepth > 0) { // set the partial validation depth to the depth of parent fNFullValidationDepth = fSkipValidationDepth - 1; fSkipValidationDepth = -1; fElementDepth--; fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; } else { fElementDepth--; } // PSVI: validation attempted: // use default values in psvi item for // validation attempted, validity, and error codes // check extra schema constraints on root element if (fElementDepth == -1 && fFullChecking && !fUseGrammarPoolOnly) { XSConstraints.fullSchemaChecking( fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // now validate the content of the element processElementContent(element); if (fIDCChecking) { // Element Locally Valid (Element) // 6 The element information item must be valid with respect to each of the {identity-constraint definitions} as per Identity-constraint Satisfied (3.11.4). // call matchers and de-activate context int oldCount = fMatcherStack.getMatcherCount(); for (int i = oldCount - 1; i >= 0; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (fCurrentElemDecl == null) { matcher.endElement(element, fCurrentType, false, fValidatedInfo.actualValue, fValidatedInfo.actualValueType, fValidatedInfo.itemValueTypes); } else { matcher.endElement( element, fCurrentType, fCurrentElemDecl.getNillable(), fDefaultValue == null ? fValidatedInfo.actualValue : fCurrentElemDecl.fDefault.actualValue, fDefaultValue == null ? fValidatedInfo.actualValueType : fCurrentElemDecl.fDefault.actualValueType, fDefaultValue == null ? fValidatedInfo.itemValueTypes : fCurrentElemDecl.fDefault.itemValueTypes); } } if (fMatcherStack.size() > 0) { fMatcherStack.popContext(); } int newCount = fMatcherStack.getMatcherCount(); // handle everything *but* keyref's. for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher) matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() != IdentityConstraint.IC_KEYREF) { fValueStoreCache.transplant(id, selMatcher.getInitialDepth()); } } } // now handle keyref's/... for (int i = oldCount - 1; i >= newCount; i--) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); if (matcher instanceof Selector.Matcher) { Selector.Matcher selMatcher = (Selector.Matcher) matcher; IdentityConstraint id; if ((id = selMatcher.getIdentityConstraint()) != null && id.getCategory() == IdentityConstraint.IC_KEYREF) { ValueStoreBase values = fValueStoreCache.getValueStoreFor(id, selMatcher.getInitialDepth()); if (values != null) // nothing to do if nothing matched! values.endDocumentFragment(); } } } fValueStoreCache.endElement(); } // Check if we should modify the xsi:type ignore depth // This check is independent of whether this is the validation root, // and should be done before the element depth is decremented. if (fElementDepth < fIgnoreXSITypeDepth) { fIgnoreXSITypeDepth--; } SchemaGrammar[] grammars = null; // have we reached the end tag of the validation root? if (fElementDepth == 0) { // 7 If the element information item is the validation root, it must be valid per Validation Root Valid (ID/IDREF) (3.3.4). String invIdRef = fValidationState.checkIDRefID(); fValidationState.resetIDTables(); if (invIdRef != null) { reportSchemaError("cvc-id.1", new Object[] { invIdRef }); } // check extra schema constraints if (fFullChecking && !fUseGrammarPoolOnly) { XSConstraints.fullSchemaChecking( fGrammarBucket, fSubGroupHandler, fCMBuilder, fXSIErrorReporter.fErrorReporter); } grammars = fGrammarBucket.getGrammars(); // return the final set of grammars validator ended up with if (fGrammarPool != null) { // Set grammars as immutable for (int k=0; k < grammars.length; k++) { grammars[k].setImmutable(true); } fGrammarPool.cacheGrammars(XMLGrammarDescription.XML_SCHEMA, grammars); } augs = endElementPSVI(true, grammars, augs); } else { augs = endElementPSVI(false, grammars, augs); // decrease element depth and restore states fElementDepth--; // get the states for the parent element. fSubElement = fSubElementStack[fElementDepth]; fCurrentElemDecl = fElemDeclStack[fElementDepth]; fNil = fNilStack[fElementDepth]; fNotation = fNotationStack[fElementDepth]; fCurrentType = fTypeStack[fElementDepth]; fCurrentCM = fCMStack[fElementDepth]; fStrictAssess = fStrictAssessStack[fElementDepth]; fCurrCMState = fCMStateStack[fElementDepth]; fSawText = fSawTextStack[fElementDepth]; fSawCharacters = fStringContent[fElementDepth]; // We should have a stack for whitespace value, and pop it up here. // But when fWhiteSpace != -1, and we see a sub-element, it must be // an error (at least for Schema 1.0). So for valid documents, the // only value we are going to push/pop in the stack is -1. // Here we just mimic the effect of popping -1. -SG fWhiteSpace = -1; // Same for append buffer. Simple types and elements with fixed // value constraint don't allow sub-elements. -SG fAppendBuffer = false; // same here. fUnionType = false; } return augs; } // handleEndElement(QName,boolean)*/ final Augmentations endElementPSVI( boolean root, SchemaGrammar[] grammars, Augmentations augs) { if (fAugPSVI) { augs = getEmptyAugs(augs); // the 5 properties sent on startElement calls fCurrentPSVI.fDeclaration = this.fCurrentElemDecl; fCurrentPSVI.fTypeDecl = this.fCurrentType; fCurrentPSVI.fNotation = this.fNotation; fCurrentPSVI.fValidationContext = this.fValidationRoot; fCurrentPSVI.fNil = this.fNil; // PSVI: validation attempted // nothing below or at the same level has none or partial // (which means this level is strictly assessed, and all chidren // are full), so this one has full if (fElementDepth > fNFullValidationDepth) { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_FULL; } // nothing below or at the same level has full or partial // (which means this level is not strictly assessed, and all chidren // are none), so this one has none else if (fElementDepth > fNNoneValidationDepth) { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_NONE; } // otherwise partial, and anything above this level will be partial else { fCurrentPSVI.fValidationAttempted = ElementPSVI.VALIDATION_PARTIAL; } // this guarantees that depth settings do not cross-over between sibling nodes if (fNFullValidationDepth == fElementDepth) { fNFullValidationDepth = fElementDepth - 1; } if (fNNoneValidationDepth == fElementDepth) { fNNoneValidationDepth = fElementDepth - 1; } if (fDefaultValue != null) fCurrentPSVI.fSpecified = true; fCurrentPSVI.fValue.copyFrom(fValidatedInfo); if (fStrictAssess) { // get all errors for the current element, its attribute, // and subelements (if they were strictly assessed). // any error would make this element invalid. // and we merge these errors to the parent element. String[] errors = fXSIErrorReporter.mergeContext(); // PSVI: error codes fCurrentPSVI.fErrors = errors; // PSVI: validity fCurrentPSVI.fValidity = (errors == null) ? ElementPSVI.VALIDITY_VALID : ElementPSVI.VALIDITY_INVALID; } else { // PSVI: validity fCurrentPSVI.fValidity = ElementPSVI.VALIDITY_NOTKNOWN; // Discard the current context: ignore any error happened within // the sub-elements/attributes of this element, because those // errors won't affect the validity of the parent elements. fXSIErrorReporter.popContext(); } if (root) { // store [schema information] in the PSVI fCurrentPSVI.fGrammars = grammars; fCurrentPSVI.fSchemaInformation = null; } } return augs; } Augmentations getEmptyAugs(Augmentations augs) { if (augs == null) { augs = fAugmentations; augs.removeAllItems(); } augs.putItem(Constants.ELEMENT_PSVI, fCurrentPSVI); fCurrentPSVI.reset(); return augs; } void storeLocations(String sLocation, String nsLocation) { if (sLocation != null) { if (!XMLSchemaLoader.tokenizeSchemaLocationStr(sLocation, fLocationPairs, fLocator == null ? null : fLocator.getExpandedSystemId())) { // error! fXSIErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "SchemaLocation", new Object[] { sLocation }, XMLErrorReporter.SEVERITY_WARNING); } } if (nsLocation != null) { XMLSchemaLoader.LocationArray la = ((XMLSchemaLoader.LocationArray) fLocationPairs.get(XMLSymbols.EMPTY_STRING)); if (la == null) { la = new XMLSchemaLoader.LocationArray(); fLocationPairs.put(XMLSymbols.EMPTY_STRING, la); } if (fLocator != null) { try { nsLocation = XMLEntityManager.expandSystemId(nsLocation, fLocator.getExpandedSystemId(), false); } catch (MalformedURIException e) { } } la.addLocation(nsLocation); } } //storeLocations //this is the function where logic of retrieving grammar is written , parser first tries to get the grammar from //the local pool, if not in local pool, it gives chance to application to be able to retrieve the grammar, then it //tries to parse the grammar using location hints from the give namespace. SchemaGrammar findSchemaGrammar( short contextType, String namespace, QName enclosingElement, QName triggeringComponent, XMLAttributes attributes) { SchemaGrammar grammar = null; //get the grammar from local pool... grammar = fGrammarBucket.getGrammar(namespace); if (grammar == null) { fXSDDescription.setNamespace(namespace); if (fGrammarPool != null) { grammar = (SchemaGrammar) fGrammarPool.retrieveGrammar(fXSDDescription); if (grammar != null) { // put this grammar into the bucket, along with grammars // imported by it (directly or indirectly) if (!fGrammarBucket.putGrammar(grammar, true, fNamespaceGrowth)) { // REVISIT: a conflict between new grammar(s) and grammars // in the bucket. What to do? A warning? An exception? fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "GrammarConflict", null, XMLErrorReporter.SEVERITY_WARNING); grammar = null; } } } } if (!fUseGrammarPoolOnly && (grammar == null || (fNamespaceGrowth && !hasSchemaComponent(grammar, contextType, triggeringComponent)))) { fXSDDescription.reset(); fXSDDescription.fContextType = contextType; fXSDDescription.setNamespace(namespace); fXSDDescription.fEnclosedElementName = enclosingElement; fXSDDescription.fTriggeringComponent = triggeringComponent; fXSDDescription.fAttributes = attributes; if (fLocator != null) { fXSDDescription.setBaseSystemId(fLocator.getExpandedSystemId()); } Hashtable locationPairs = fLocationPairs; Object locationArray = locationPairs.get(namespace == null ? XMLSymbols.EMPTY_STRING : namespace); if (locationArray != null) { String[] temp = ((XMLSchemaLoader.LocationArray) locationArray).getLocationArray(); if (temp.length != 0) { setLocationHints(fXSDDescription, temp, grammar); } } if (grammar == null || fXSDDescription.fLocationHints != null) { boolean toParseSchema = true; if (grammar != null) { // use location hints instead locationPairs = EMPTY_TABLE; } // try to parse the grammar using location hints from that namespace.. try { XMLInputSource xis = XMLSchemaLoader.resolveDocument( fXSDDescription, locationPairs, fEntityResolver); if (grammar != null && fNamespaceGrowth) { try { // if we are dealing with a different schema location, then include the new schema // into the existing grammar if (grammar.getDocumentLocations().contains(XMLEntityManager.expandSystemId(xis.getSystemId(), xis.getBaseSystemId(), false))) { toParseSchema = false; } } catch (MalformedURIException e) { } } if (toParseSchema) { grammar = fSchemaLoader.loadSchema(fXSDDescription, xis, fLocationPairs); } } catch (IOException ex) { final String [] locationHints = fXSDDescription.getLocationHints(); fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "schema_reference.4", new Object[] { locationHints != null ? locationHints[0] : XMLSymbols.EMPTY_STRING }, XMLErrorReporter.SEVERITY_WARNING, ex); } } } return grammar; } //findSchemaGrammar private boolean hasSchemaComponent(SchemaGrammar grammar, short contextType, QName triggeringComponent) { if (grammar != null && triggeringComponent != null) { String localName = triggeringComponent.localpart; if (localName != null && localName.length() > 0) { switch (contextType) { case XSDDescription.CONTEXT_ELEMENT: return grammar.getElementDeclaration(localName) != null; case XSDDescription.CONTEXT_ATTRIBUTE: return grammar.getAttributeDeclaration(localName) != null; case XSDDescription.CONTEXT_XSITYPE: return grammar.getTypeDefinition(localName) != null; } } } return false; } private void setLocationHints(XSDDescription desc, String[] locations, SchemaGrammar grammar) { int length = locations.length; if (grammar == null) { fXSDDescription.fLocationHints = new String[length]; System.arraycopy(locations, 0, fXSDDescription.fLocationHints, 0, length); } else { setLocationHints(desc, locations, grammar.getDocumentLocations()); } } private void setLocationHints(XSDDescription desc, String[] locations, StringList docLocations) { int length = locations.length; String[] hints = new String[length]; int counter = 0; for (int i=0; i<length; i++) { if (!docLocations.contains(locations[i])) { hints[counter++] = locations[i]; } } if (counter > 0) { if (counter == length) { fXSDDescription.fLocationHints = hints; } else { fXSDDescription.fLocationHints = new String[counter]; System.arraycopy(hints, 0, fXSDDescription.fLocationHints, 0, counter); } } } XSTypeDefinition getAndCheckXsiType(QName element, String xsiType, XMLAttributes attributes) { // This method also deals with clause 1.2.1.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // Element Locally Valid (Element) // 4 If there is an attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is type, then all of the following must be true: // 4.1 The normalized value of that attribute information item must be valid with respect to the built-in QName simple type, as defined by String Valid (3.14.4); QName typeName = null; try { typeName = (QName) fQNameDV.validate(xsiType, fValidationState, null); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError( "cvc-elt.4.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_TYPE, xsiType }); return null; } // 4.2 The local name and namespace name (as defined in QName Interpretation (3.15.3)), of the actual value of that attribute information item must resolve to a type definition, as defined in QName resolution (Instance) (3.15.4) XSTypeDefinition type = null; // if the namespace is schema namespace, first try built-in types if (typeName.uri == SchemaSymbols.URI_SCHEMAFORSCHEMA) { type = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(typeName.localpart); } // if it's not schema built-in types, then try to get a grammar if (type == null) { //try to find schema grammar by different means.... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_XSITYPE, typeName.uri, element, typeName, attributes); if (grammar != null) type = grammar.getGlobalTypeDecl(typeName.localpart); } // still couldn't find the type, report an error if (type == null) { reportSchemaError("cvc-elt.4.2", new Object[] { element.rawname, xsiType }); return null; } // if there is no current type, set this one as current. // and we don't need to do extra checking if (fCurrentType != null) { short block = XSConstants.DERIVATION_NONE; // 4.3 The local type definition must be validly derived from the {type definition} given the union of the {disallowed substitutions} and the {type definition}'s {prohibited substitutions}, as defined in Type Derivation OK (Complex) (3.4.6) (if it is a complex type definition), or given {disallowed substitutions} as defined in Type Derivation OK (Simple) (3.14.6) (if it is a simple type definition). // Note: It's possible to have fCurrentType be non-null and fCurrentElemDecl // be null, if the current type is set using the property "root-type-definition". // In that case, we don't disallow any substitutions. -PM if (fCurrentElemDecl != null) { block = fCurrentElemDecl.fBlock; } if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { block |= ((XSComplexTypeDecl) fCurrentType).fBlock; } if (!XSConstraints.checkTypeDerivationOk(type, fCurrentType, block)) { reportSchemaError( "cvc-elt.4.3", new Object[] { element.rawname, xsiType, fCurrentType.getName()}); } } return type; } //getAndCheckXsiType boolean getXsiNil(QName element, String xsiNil) { // Element Locally Valid (Element) // 3 The appropriate case among the following must be true: // 3.1 If {nillable} is false, then there must be no attribute information item among the element information item's [attributes] whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is nil. if (fCurrentElemDecl != null && !fCurrentElemDecl.getNillable()) { reportSchemaError( "cvc-elt.3.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } // 3.2 If {nillable} is true and there is such an attribute information item and its actual value is true , then all of the following must be true: // 3.2.2 There must be no fixed {value constraint}. else { String value = XMLChar.trim(xsiNil); if (value.equals(SchemaSymbols.ATTVAL_TRUE) || value.equals(SchemaSymbols.ATTVAL_TRUE_1)) { if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { reportSchemaError( "cvc-elt.3.2.2", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } return true; } } return false; } void processAttributes(QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { if (DEBUG) { System.out.println("==>processAttributes: " + attributes.getLength()); } // whether we have seen a Wildcard ID. String wildcardIDName = null; // for each present attribute int attCount = attributes.getLength(); Augmentations augs = null; AttributePSVImpl attrPSVI = null; boolean isSimple = fCurrentType == null || fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE; XSObjectList attrUses = null; int useCount = 0; XSWildcardDecl attrWildcard = null; if (!isSimple) { attrUses = attrGrp.getAttributeUses(); useCount = attrUses.getLength(); attrWildcard = attrGrp.fAttributeWC; } // Element Locally Valid (Complex Type) // 3 For each attribute information item in the element information item's [attributes] excepting those whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation, the appropriate case among the following must be true: // get the corresponding attribute decl for (int index = 0; index < attCount; index++) { attributes.getName(index, fTempQName); if (DEBUG) { System.out.println("==>process attribute: " + fTempQName); } if (fAugPSVI || fIdConstraint) { augs = attributes.getAugmentations(index); attrPSVI = (AttributePSVImpl) augs.getItem(Constants.ATTRIBUTE_PSVI); if (attrPSVI != null) { attrPSVI.reset(); } else { attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); } // PSVI attribute: validation context attrPSVI.fValidationContext = fValidationRoot; } // Element Locally Valid (Type) // 3.1.1 The element information item's [attributes] must be empty, excepting those // whose [namespace name] is identical to http://www.w3.org/2001/XMLSchema-instance and // whose [local name] is one of type, nil, schemaLocation or noNamespaceSchemaLocation. // for the 4 xsi attributes, get appropriate decl, and validate if (fTempQName.uri == SchemaSymbols.URI_XSI) { XSAttributeDecl attrDecl = null; if (fTempQName.localpart == SchemaSymbols.XSI_TYPE) { attrDecl = XSI_TYPE; } else if (fTempQName.localpart == SchemaSymbols.XSI_NIL) { attrDecl = XSI_NIL; } else if (fTempQName.localpart == SchemaSymbols.XSI_SCHEMALOCATION) { attrDecl = XSI_SCHEMALOCATION; } else if (fTempQName.localpart == SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION) { attrDecl = XSI_NONAMESPACESCHEMALOCATION; } if (attrDecl != null) { processOneAttribute(element, attributes, index, attrDecl, null, attrPSVI); continue; } } // for namespace attributes, no_validation/unknow_validity if (fTempQName.rawname == XMLSymbols.PREFIX_XMLNS || fTempQName.rawname.startsWith("xmlns:")) { continue; } // simple type doesn't allow any other attributes if (isSimple) { reportSchemaError( "cvc-type.3.1.1", new Object[] { element.rawname, fTempQName.rawname }); continue; } // it's not xmlns, and not xsi, then we need to find a decl for it XSAttributeUseImpl currUse = null, oneUse; for (int i = 0; i < useCount; i++) { oneUse = (XSAttributeUseImpl) attrUses.item(i); if (oneUse.fAttrDecl.fName == fTempQName.localpart && oneUse.fAttrDecl.fTargetNamespace == fTempQName.uri) { currUse = oneUse; break; } } // 3.2 otherwise all of the following must be true: // 3.2.1 There must be an {attribute wildcard}. // 3.2.2 The attribute information item must be valid with respect to it as defined in Item Valid (Wildcard) (3.10.4). // if failed, get it from wildcard if (currUse == null) { //if (attrWildcard == null) // reportSchemaError("cvc-complex-type.3.2.1", new Object[]{element.rawname, fTempQName.rawname}); if (attrWildcard == null || !attrWildcard.allowNamespace(fTempQName.uri)) { // so this attribute is not allowed reportSchemaError( "cvc-complex-type.3.2.2", new Object[] { element.rawname, fTempQName.rawname }); // We have seen an attribute that was not declared fNFullValidationDepth = fElementDepth; continue; } } XSAttributeDecl currDecl = null; if (currUse != null) { currDecl = currUse.fAttrDecl; } else { // which means it matches a wildcard // skip it if processContents is skip if (attrWildcard.fProcessContents == XSWildcardDecl.PC_SKIP) continue; //try to find grammar by different means... SchemaGrammar grammar = findSchemaGrammar( XSDDescription.CONTEXT_ATTRIBUTE, fTempQName.uri, element, fTempQName, attributes); if (grammar != null) { currDecl = grammar.getGlobalAttributeDecl(fTempQName.localpart); } // if can't find if (currDecl == null) { // if strict, report error if (attrWildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { reportSchemaError( "cvc-complex-type.3.2.2", new Object[] { element.rawname, fTempQName.rawname }); } // then continue to the next attribute continue; } else { // 5 Let [Definition:] the wild IDs be the set of all attribute information item to which clause 3.2 applied and whose validation resulted in a context-determined declaration of mustFind or no context-determined declaration at all, and whose [local name] and [namespace name] resolve (as defined by QName resolution (Instance) (3.15.4)) to an attribute declaration whose {type definition} is or is derived from ID. Then all of the following must be true: // 5.1 There must be no more than one item in wild IDs. if (currDecl.fType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE && ((XSSimpleType) currDecl.fType).isIDType()) { if (wildcardIDName != null) { reportSchemaError( "cvc-complex-type.5.1", new Object[] { element.rawname, currDecl.fName, wildcardIDName }); } else wildcardIDName = currDecl.fName; } } } processOneAttribute(element, attributes, index, currDecl, currUse, attrPSVI); } // end of for (all attributes) // 5.2 If wild IDs is non-empty, there must not be any attribute uses among the {attribute uses} whose {attribute declaration}'s {type definition} is or is derived from ID. if (!isSimple && attrGrp.fIDAttrName != null && wildcardIDName != null) { reportSchemaError( "cvc-complex-type.5.2", new Object[] { element.rawname, wildcardIDName, attrGrp.fIDAttrName }); } } //processAttributes void processOneAttribute( QName element, XMLAttributes attributes, int index, XSAttributeDecl currDecl, XSAttributeUseImpl currUse, AttributePSVImpl attrPSVI) { String attrValue = attributes.getValue(index); fXSIErrorReporter.pushContext(); // Attribute Locally Valid // For an attribute information item to be locally valid with respect to an attribute declaration all of the following must be true: // 1 The declaration must not be absent (see Missing Sub-components (5.3) for how this can fail to be the case). // 2 Its {type definition} must not be absent. // 3 The item's normalized value must be locally valid with respect to that {type definition} as per String Valid (3.14.4). // get simple type XSSimpleType attDV = currDecl.fType; Object actualValue = null; try { actualValue = attDV.validate(attrValue, fValidationState, fValidatedInfo); // store the normalized value if (fNormalizeData) { attributes.setValue(index, fValidatedInfo.normalizedValue); } // PSVI: element notation if (attDV.getVariety() == XSSimpleType.VARIETY_ATOMIC && attDV.getPrimitiveKind() == XSSimpleType.PRIMITIVE_NOTATION) { QName qName = (QName) actualValue; SchemaGrammar grammar = fGrammarBucket.getGrammar(qName.uri); //REVISIT: is it possible for the notation to be in different namespace than the attribute //with which it is associated, CHECK !! <fof n1:att1 = "n2:notation1" ..> // should we give chance to the application to be able to retrieve a grammar - nb //REVISIT: what would be the triggering component here.. if it is attribute value that // triggered the loading of grammar ?? -nb if (grammar != null) { fNotation = grammar.getGlobalNotationDecl(qName.localpart); } } } catch (InvalidDatatypeValueException idve) { reportSchemaError(idve.getKey(), idve.getArgs()); reportSchemaError( "cvc-attribute.3", new Object[] { element.rawname, fTempQName.rawname, attrValue, (attDV instanceof XSSimpleTypeDecl) ? ((XSSimpleTypeDecl) attDV).getTypeName() : attDV.getName()}); } // get the value constraint from use or decl // 4 The item's actual value must match the value of the {value constraint}, if it is present and fixed. // now check the value against the simpleType if (actualValue != null && currDecl.getConstraintType() == XSConstants.VC_FIXED) { if (!ValidatedInfo.isComparable(fValidatedInfo, currDecl.fDefault) || !actualValue.equals(currDecl.fDefault.actualValue)) { reportSchemaError( "cvc-attribute.4", new Object[] { element.rawname, fTempQName.rawname, attrValue, currDecl.fDefault.stringValue()}); } } // 3.1 If there is among the {attribute uses} an attribute use with an {attribute declaration} whose {name} matches the attribute information item's [local name] and whose {target namespace} is identical to the attribute information item's [namespace name] (where an absent {target namespace} is taken to be identical to a [namespace name] with no value), then the attribute information must be valid with respect to that attribute use as per Attribute Locally Valid (Use) (3.5.4). In this case the {attribute declaration} of that attribute use is the context-determined declaration for the attribute information item with respect to Schema-Validity Assessment (Attribute) (3.2.4) and Assessment Outcome (Attribute) (3.2.5). if (actualValue != null && currUse != null && currUse.fConstraintType == XSConstants.VC_FIXED) { if (!ValidatedInfo.isComparable(fValidatedInfo, currUse.fDefault) || !actualValue.equals(currUse.fDefault.actualValue)) { reportSchemaError( "cvc-complex-type.3.1", new Object[] { element.rawname, fTempQName.rawname, attrValue, currUse.fDefault.stringValue()}); } } if (fIdConstraint) { attrPSVI.fValue.copyFrom(fValidatedInfo); } if (fAugPSVI) { // PSVI: attribute declaration attrPSVI.fDeclaration = currDecl; // PSVI: attribute type attrPSVI.fTypeDecl = attDV; // PSVI: attribute normalized value // NOTE: we always store the normalized value, even if it's invlid, // because it might still be useful to the user. But when the it's // not valid, the normalized value is not trustable. attrPSVI.fValue.copyFrom(fValidatedInfo); // PSVI: validation attempted: attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; // We have seen an attribute that was declared. fNNoneValidationDepth = fElementDepth; String[] errors = fXSIErrorReporter.mergeContext(); // PSVI: error codes attrPSVI.fErrors = errors; // PSVI: validity attrPSVI.fValidity = (errors == null) ? AttributePSVI.VALIDITY_VALID : AttributePSVI.VALIDITY_INVALID; } } void addDefaultAttributes( QName element, XMLAttributes attributes, XSAttributeGroupDecl attrGrp) { // Check after all specified attrs are scanned // (1) report error for REQUIRED attrs that are missing (V_TAGc) // REVISIT: should we check prohibited attributes? // (2) report error for PROHIBITED attrs that are present (V_TAGc) // (3) add default attrs (FIXED and NOT_FIXED) // if (DEBUG) { System.out.println("==>addDefaultAttributes: " + element); } XSObjectList attrUses = attrGrp.getAttributeUses(); int useCount = attrUses.getLength(); XSAttributeUseImpl currUse; XSAttributeDecl currDecl; short constType; ValidatedInfo defaultValue; boolean isSpecified; QName attName; // for each attribute use for (int i = 0; i < useCount; i++) { currUse = (XSAttributeUseImpl) attrUses.item(i); currDecl = currUse.fAttrDecl; // get value constraint constType = currUse.fConstraintType; defaultValue = currUse.fDefault; if (constType == XSConstants.VC_NONE) { constType = currDecl.getConstraintType(); defaultValue = currDecl.fDefault; } // whether this attribute is specified isSpecified = attributes.getValue(currDecl.fTargetNamespace, currDecl.fName) != null; // Element Locally Valid (Complex Type) // 4 The {attribute declaration} of each attribute use in the {attribute uses} whose // {required} is true matches one of the attribute information items in the element // information item's [attributes] as per clause 3.1 above. if (currUse.fUse == SchemaSymbols.USE_REQUIRED) { if (!isSpecified) reportSchemaError( "cvc-complex-type.4", new Object[] { element.rawname, currDecl.fName }); } // if the attribute is not specified, then apply the value constraint if (!isSpecified && constType != XSConstants.VC_NONE) { attName = new QName(null, currDecl.fName, currDecl.fName, currDecl.fTargetNamespace); String normalized = (defaultValue != null) ? defaultValue.stringValue() : ""; int attrIndex; if (attributes instanceof XMLAttributesImpl) { XMLAttributesImpl attrs = (XMLAttributesImpl) attributes; attrIndex = attrs.getLength(); attrs.addAttributeNS(attName, "CDATA", normalized); } else { attrIndex = attributes.addAttribute(attName, "CDATA", normalized); } if (fAugPSVI) { // PSVI: attribute is "schema" specified Augmentations augs = attributes.getAugmentations(attrIndex); AttributePSVImpl attrPSVI = new AttributePSVImpl(); augs.putItem(Constants.ATTRIBUTE_PSVI, attrPSVI); attrPSVI.fDeclaration = currDecl; attrPSVI.fTypeDecl = currDecl.fType; attrPSVI.fValue.copyFrom(defaultValue); attrPSVI.fValidationContext = fValidationRoot; attrPSVI.fValidity = AttributePSVI.VALIDITY_VALID; attrPSVI.fValidationAttempted = AttributePSVI.VALIDATION_FULL; attrPSVI.fSpecified = true; } } } // for } // addDefaultAttributes /** * If there is not text content, and there is a * {value constraint} on the corresponding element decl, then return * an XMLString representing the default value. */ void processElementContent(QName element) { // 1 If the item is ?valid? with respect to an element declaration as per Element Locally Valid (Element) (?3.3.4) and the {value constraint} is present, but clause 3.2 of Element Locally Valid (Element) (?3.3.4) above is not satisfied and the item has no element or character information item [children], then schema. Furthermore, the post-schema-validation infoset has the canonical lexical representation of the {value constraint} value as the item's [schema normalized value] property. if (fCurrentElemDecl != null && fCurrentElemDecl.fDefault != null && !fSawText && !fSubElement && !fNil) { String strv = fCurrentElemDecl.fDefault.stringValue(); int bufLen = strv.length(); if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) { fNormalizedStr.ch = new char[bufLen]; } strv.getChars(0, bufLen, fNormalizedStr.ch, 0); fNormalizedStr.offset = 0; fNormalizedStr.length = bufLen; fDefaultValue = fNormalizedStr; } // fixed values are handled later, after xsi:type determined. fValidatedInfo.normalizedValue = null; // Element Locally Valid (Element) // 3.2.1 The element information item must have no character or element information item [children]. if (fNil) { if (fSubElement || fSawText) { reportSchemaError( "cvc-elt.3.2.1", new Object[] { element.rawname, SchemaSymbols.URI_XSI + "," + SchemaSymbols.XSI_NIL }); } } this.fValidatedInfo.reset(); // 5 The appropriate case among the following must be true: // 5.1 If the declaration has a {value constraint}, the item has neither element nor character [children] and clause 3.2 has not applied, then all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() != XSConstants.VC_NONE && !fSubElement && !fSawText && !fNil) { // 5.1.1 If the actual type definition is a local type definition then the canonical lexical representation of the {value constraint} value must be a valid default for the actual type definition as defined in Element Default Valid (Immediate) (3.3.6). if (fCurrentType != fCurrentElemDecl.fType) { //REVISIT:we should pass ValidatedInfo here. if (XSConstraints .ElementDefaultValidImmediate( fCurrentType, fCurrentElemDecl.fDefault.stringValue(), fState4XsiType, null) == null) reportSchemaError( "cvc-elt.5.1.1", new Object[] { element.rawname, fCurrentType.getName(), fCurrentElemDecl.fDefault.stringValue()}); } // 5.1.2 The element information item with the canonical lexical representation of the {value constraint} value used as its normalized value must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). // REVISIT: don't use toString, but validateActualValue instead // use the fState4ApplyDefault elementLocallyValidType(element, fCurrentElemDecl.fDefault.stringValue()); } else { // The following method call also deal with clause 1.2.2 of the constraint // Validation Rule: Schema-Validity Assessment (Element) // 5.2 If the declaration has no {value constraint} or the item has either element or character [children] or clause 3.2 has applied, then all of the following must be true: // 5.2.1 The element information item must be valid with respect to the actual type definition as defined by Element Locally Valid (Type) (3.3.4). Object actualValue = elementLocallyValidType(element, fBuffer); // 5.2.2 If there is a fixed {value constraint} and clause 3.2 has not applied, all of the following must be true: if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED && !fNil) { String content = fBuffer.toString(); // 5.2.2.1 The element information item must have no element information item [children]. if (fSubElement) reportSchemaError("cvc-elt.5.2.2.1", new Object[] { element.rawname }); // 5.2.2.2 The appropriate case among the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; // 5.2.2.2.1 If the {content type} of the actual type definition is mixed, then the initial value of the item must match the canonical lexical representation of the {value constraint} value. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // REVISIT: how to get the initial value, does whiteSpace count? if (!fCurrentElemDecl.fDefault.normalizedValue.equals(content)) reportSchemaError( "cvc-elt.5.2.2.2.1", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.normalizedValue }); } // 5.2.2.2.2 If the {content type} of the actual type definition is a simple type definition, then the actual value of the item must match the canonical lexical representation of the {value constraint} value. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (actualValue != null && (!ValidatedInfo.isComparable(fValidatedInfo, fCurrentElemDecl.fDefault) || !actualValue.equals(fCurrentElemDecl.fDefault.actualValue))) { reportSchemaError( "cvc-elt.5.2.2.2.2", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.stringValue()}); } } } else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { if (actualValue != null && (!ValidatedInfo.isComparable(fValidatedInfo, fCurrentElemDecl.fDefault) || !actualValue.equals(fCurrentElemDecl.fDefault.actualValue))) { // REVISIT: the spec didn't mention this case: fixed // value with simple type reportSchemaError( "cvc-elt.5.2.2.2.2", new Object[] { element.rawname, content, fCurrentElemDecl.fDefault.stringValue()}); } } } } if (fDefaultValue == null && fNormalizeData && fDocumentHandler != null && fUnionType) { // for union types we need to send data because we delayed sending // this data when we received it in the characters() call. String content = fValidatedInfo.normalizedValue; if (content == null) content = fBuffer.toString(); int bufLen = content.length(); if (fNormalizedStr.ch == null || fNormalizedStr.ch.length < bufLen) { fNormalizedStr.ch = new char[bufLen]; } content.getChars(0, bufLen, fNormalizedStr.ch, 0); fNormalizedStr.offset = 0; fNormalizedStr.length = bufLen; fDocumentHandler.characters(fNormalizedStr, null); } } // processElementContent Object elementLocallyValidType(QName element, Object textContent) { if (fCurrentType == null) return null; Object retValue = null; // Element Locally Valid (Type) // 3 The appropriate case among the following must be true: // 3.1 If the type definition is a simple type definition, then all of the following must be true: if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { // 3.1.2 The element information item must have no element information item [children]. if (fSubElement) reportSchemaError("cvc-type.3.1.2", new Object[] { element.rawname }); // 3.1.3 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the normalized value must be valid with respect to the type definition as defined by String Valid (3.14.4). if (!fNil) { XSSimpleType dv = (XSSimpleType) fCurrentType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } retValue = dv.validate(textContent, fValidationState, fValidatedInfo); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError( "cvc-type.3.1.3", new Object[] { element.rawname, textContent }); } } } else { // 3.2 If the type definition is a complex type definition, then the element information item must be valid with respect to the type definition as per Element Locally Valid (Complex Type) (3.4.4); retValue = elementLocallyValidComplexType(element, textContent); } return retValue; } // elementLocallyValidType Object elementLocallyValidComplexType(QName element, Object textContent) { Object actualValue = null; XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; // Element Locally Valid (Complex Type) // For an element information item to be locally valid with respect to a complex type definition all of the following must be true: // 1 {abstract} is false. // 2 If clause 3.2 of Element Locally Valid (Element) (3.3.4) did not apply, then the appropriate case among the following must be true: if (!fNil) { // 2.1 If the {content type} is empty, then the element information item has no character or element information item [children]. if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_EMPTY && (fSubElement || fSawText)) { reportSchemaError("cvc-complex-type.2.1", new Object[] { element.rawname }); } // 2.2 If the {content type} is a simple type definition, then the element information item has no element information item [children], and the normalized value of the element information item is valid with respect to that simple type definition as defined by String Valid (3.14.4). else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (fSubElement) reportSchemaError("cvc-complex-type.2.2", new Object[] { element.rawname }); XSSimpleType dv = ctype.fXSSimpleType; try { if (!fNormalizeData || fUnionType) { fValidationState.setNormalizationRequired(true); } actualValue = dv.validate(textContent, fValidationState, fValidatedInfo); } catch (InvalidDatatypeValueException e) { reportSchemaError(e.getKey(), e.getArgs()); reportSchemaError("cvc-complex-type.2.2", new Object[] { element.rawname }); } // REVISIT: eventually, this method should return the same actualValue as elementLocallyValidType... // obviously it'll return null when the content is complex. } // 2.3 If the {content type} is element-only, then the element information item has no character information item [children] other than those whose [character code] is defined as a white space in [XML 1.0 (Second Edition)]. else if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT) { if (fSawCharacters) { reportSchemaError("cvc-complex-type.2.3", new Object[] { element.rawname }); } } // 2.4 If the {content type} is element-only or mixed, then the sequence of the element information item's element information item [children], if any, taken in order, is valid with respect to the {content type}'s particle, as defined in Element Sequence Locally Valid (Particle) (3.9.4). if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_ELEMENT || ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_MIXED) { // if the current state is a valid state, check whether // it's one of the final states. if (DEBUG) { System.out.println(fCurrCMState); } if (fCurrCMState[0] >= 0 && !fCurrentCM.endContentModel(fCurrCMState)) { String expected = expectedStr(fCurrentCM.whatCanGoHere(fCurrCMState)); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.j", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.i", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } else { reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.b", new Object[] { element.rawname, expected }); } } } } return actualValue; } // elementLocallyValidComplexType void processRootTypeQName(final javax.xml.namespace.QName rootTypeQName) { String rootTypeNamespace = rootTypeQName.getNamespaceURI(); if (rootTypeNamespace != null && rootTypeNamespace.equals(XMLConstants.NULL_NS_URI)) { rootTypeNamespace = null; } if (SchemaSymbols.URI_SCHEMAFORSCHEMA.equals(rootTypeNamespace)) { fCurrentType = SchemaGrammar.SG_SchemaNS.getGlobalTypeDecl(rootTypeQName.getLocalPart()); } else { final SchemaGrammar grammarForRootType = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, rootTypeNamespace, null, null, null); if (grammarForRootType != null) { fCurrentType = grammarForRootType.getGlobalTypeDecl(rootTypeQName.getLocalPart()); } } if (fCurrentType == null) { String typeName = (rootTypeQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ? rootTypeQName.getLocalPart() : rootTypeQName.getPrefix()+":"+rootTypeQName.getLocalPart(); reportSchemaError("cvc-type.1", new Object[] {typeName}); } } // processRootTypeQName void processRootElementDeclQName(final javax.xml.namespace.QName rootElementDeclQName, final QName element) { String rootElementDeclNamespace = rootElementDeclQName.getNamespaceURI(); if (rootElementDeclNamespace != null && rootElementDeclNamespace.equals(XMLConstants.NULL_NS_URI)) { rootElementDeclNamespace = null; } final SchemaGrammar grammarForRootElement = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, rootElementDeclNamespace, null, null, null); if (grammarForRootElement != null) { fCurrentElemDecl = grammarForRootElement.getGlobalElementDecl(rootElementDeclQName.getLocalPart()); } if (fCurrentElemDecl == null) { String declName = (rootElementDeclQName.getPrefix().equals(XMLConstants.DEFAULT_NS_PREFIX)) ? rootElementDeclQName.getLocalPart() : rootElementDeclQName.getPrefix()+":"+rootElementDeclQName.getLocalPart(); reportSchemaError("cvc-elt.1.a", new Object[] {declName}); } else { checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } } // processRootElementDeclQName void checkElementMatchesRootElementDecl(final XSElementDecl rootElementDecl, final QName element) { // Report an error if the name of the element does // not match the name of the specified element declaration. if (element.localpart != rootElementDecl.fName || element.uri != rootElementDecl.fTargetNamespace) { reportSchemaError("cvc-elt.1.b", new Object[] {element.rawname, rootElementDecl.fName}); } } // checkElementMatchesRootElementDecl void reportSchemaError(String key, Object[] arguments) { if (fDoValidation) fXSIErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, key, arguments, XMLErrorReporter.SEVERITY_ERROR); } private String expectedStr(Vector expected) { StringBuffer ret = new StringBuffer("{"); int size = expected.size(); for (int i = 0; i < size; i++) { if (i > 0) ret.append(", "); ret.append(expected.elementAt(i).toString()); } ret.append('}'); return ret.toString(); } /**********************************/ // xpath matcher information /** * Stack of XPath matchers for identity constraints. * * @author Andy Clark, IBM */ protected static class XPathMatcherStack { // // Data // /** Active matchers. */ protected XPathMatcher[] fMatchers = new XPathMatcher[4]; /** Count of active matchers. */ protected int fMatchersCount; /** Offset stack for contexts. */ protected IntStack fContextStack = new IntStack(); // // Constructors // public XPathMatcherStack() { } // <init>() // // Public methods // /** Resets the XPath matcher stack. */ public void clear() { for (int i = 0; i < fMatchersCount; i++) { fMatchers[i] = null; } fMatchersCount = 0; fContextStack.clear(); } // clear() /** Returns the size of the stack. */ public int size() { return fContextStack.size(); } // size():int /** Returns the count of XPath matchers. */ public int getMatcherCount() { return fMatchersCount; } // getMatcherCount():int /** Adds a matcher. */ public void addMatcher(XPathMatcher matcher) { ensureMatcherCapacity(); fMatchers[fMatchersCount++] = matcher; } // addMatcher(XPathMatcher) /** Returns the XPath matcher at the specified index. */ public XPathMatcher getMatcherAt(int index) { return fMatchers[index]; } // getMatcherAt(index):XPathMatcher /** Pushes a new context onto the stack. */ public void pushContext() { fContextStack.push(fMatchersCount); } // pushContext() /** Pops a context off of the stack. */ public void popContext() { fMatchersCount = fContextStack.pop(); } // popContext() // // Private methods // /** Ensures the size of the matchers array. */ private void ensureMatcherCapacity() { if (fMatchersCount == fMatchers.length) { XPathMatcher[] array = new XPathMatcher[fMatchers.length * 2]; System.arraycopy(fMatchers, 0, array, 0, fMatchers.length); fMatchers = array; } } // ensureMatcherCapacity() } // class XPathMatcherStack // value store implementations /** * Value store implementation base class. There are specific subclasses * for handling unique, key, and keyref. * * @author Andy Clark, IBM */ protected abstract class ValueStoreBase implements ValueStore { // // Data // /** Identity constraint. */ protected IdentityConstraint fIdentityConstraint; protected int fFieldCount = 0; protected Field[] fFields = null; /** current data */ protected Object[] fLocalValues = null; protected short[] fLocalValueTypes = null; protected ShortList[] fLocalItemValueTypes = null; /** Current data value count. */ protected int fValuesCount; /** global data */ public final Vector fValues = new Vector(); public ShortVector fValueTypes = null; public Vector fItemValueTypes = null; private boolean fUseValueTypeVector = false; private int fValueTypesLength = 0; private short fValueType = 0; private boolean fUseItemValueTypeVector = false; private int fItemValueTypesLength = 0; private ShortList fItemValueType = null; /** buffer for error messages */ final StringBuffer fTempBuffer = new StringBuffer(); // // Constructors // /** Constructs a value store for the specified identity constraint. */ protected ValueStoreBase(IdentityConstraint identityConstraint) { fIdentityConstraint = identityConstraint; fFieldCount = fIdentityConstraint.getFieldCount(); fFields = new Field[fFieldCount]; fLocalValues = new Object[fFieldCount]; fLocalValueTypes = new short[fFieldCount]; fLocalItemValueTypes = new ShortList[fFieldCount]; for (int i = 0; i < fFieldCount; i++) { fFields[i] = fIdentityConstraint.getFieldAt(i); } } // <init>(IdentityConstraint) // // Public methods // // destroys this ValueStore; useful when, for instance, a // locally-scoped ID constraint is involved. public void clear() { fValuesCount = 0; fUseValueTypeVector = false; fValueTypesLength = 0; fValueType = 0; fUseItemValueTypeVector = false; fItemValueTypesLength = 0; fItemValueType = null; fValues.setSize(0); if (fValueTypes != null) { fValueTypes.clear(); } if (fItemValueTypes != null) { fItemValueTypes.setSize(0); } } // end clear():void // appends the contents of one ValueStore to those of us. public void append(ValueStoreBase newVal) { for (int i = 0; i < newVal.fValues.size(); i++) { fValues.addElement(newVal.fValues.elementAt(i)); } } // append(ValueStoreBase) /** Start scope for value store. */ public void startValueScope() { fValuesCount = 0; for (int i = 0; i < fFieldCount; i++) { fLocalValues[i] = null; fLocalValueTypes[i] = 0; fLocalItemValueTypes[i] = null; } } // startValueScope() /** Ends scope for value store. */ public void endValueScope() { if (fValuesCount == 0) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "AbsentKeyValue"; String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { eName, cName }); } return; } // Validation Rule: Identity-constraint Satisfied // 4.2 If the {identity-constraint category} is key, then all of the following must be true: // 4.2.1 The target node set and the qualified node set are equal, that is, every member of the // target node set is also a member of the qualified node set and vice versa. // // If the IDC is a key check whether we have all the fields. if (fValuesCount != fFieldCount) { if (fIdentityConstraint.getCategory() == IdentityConstraint.IC_KEY) { String code = "KeyNotEnoughValues"; UniqueOrKey key = (UniqueOrKey) fIdentityConstraint; String eName = fIdentityConstraint.getElementName(); String cName = key.getIdentityConstraintName(); reportSchemaError(code, new Object[] { eName, cName }); } return; } } // endValueScope() // This is needed to allow keyref's to look for matched keys // in the correct scope. Unique and Key may also need to // override this method for purposes of their own. // This method is called whenever the DocumentFragment // of an ID Constraint goes out of scope. public void endDocumentFragment() { } // endDocumentFragment():void /** * Signals the end of the document. This is where the specific * instances of value stores can verify the integrity of the * identity constraints. */ public void endDocument() { } // endDocument() // // ValueStore methods // /* reports an error if an element is matched * has nillable true and is matched by a key. */ public void reportError(String key, Object[] args) { reportSchemaError(key, args); } // reportError(String,Object[]) /** * Adds the specified value to the value store. * * @param field The field associated to the value. This reference * is used to ensure that each field only adds a value * once within a selection scope. * @param mayMatch a flag indiciating whether the field may be matched. * @param actualValue The value to add. * @param valueType Type of the value to add. * @param itemValueType If the value is a list, a list of types for each of the values in the list. */ public void addValue(Field field, boolean mayMatch, Object actualValue, short valueType, ShortList itemValueType) { int i; for (i = fFieldCount - 1; i > -1; i--) { if (fFields[i] == field) { break; } } // do we even know this field? if (i == -1) { String code = "UnknownField"; String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { field.toString(), eName, cName }); return; } if (!mayMatch) { String code = "FieldMultipleMatch"; String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { field.toString(), cName }); } else { fValuesCount++; } fLocalValues[i] = actualValue; fLocalValueTypes[i] = valueType; fLocalItemValueTypes[i] = itemValueType; if (fValuesCount == fFieldCount) { checkDuplicateValues(); // store values for (i = 0; i < fFieldCount; i++) { fValues.addElement(fLocalValues[i]); addValueType(fLocalValueTypes[i]); addItemValueType(fLocalItemValueTypes[i]); } } } // addValue(String,Field) /** * Returns true if this value store contains the locally scoped value stores */ public boolean contains() { // REVISIT: we can improve performance by using hash codes, instead of // traversing global vector that could be quite large. int next = 0; final int size = fValues.size(); LOOP : for (int i = 0; i < size; i = next) { next = i + fFieldCount; for (int j = 0; j < fFieldCount; j++) { Object value1 = fLocalValues[j]; Object value2 = fValues.elementAt(i); short valueType1 = fLocalValueTypes[j]; short valueType2 = getValueTypeAt(i); if (value1 == null || value2 == null || valueType1 != valueType2 || !(value1.equals(value2))) { continue LOOP; } else if(valueType1 == XSConstants.LIST_DT || valueType1 == XSConstants.LISTOFUNION_DT) { ShortList list1 = fLocalItemValueTypes[j]; ShortList list2 = getItemValueTypeAt(i); if(list1 == null || list2 == null || !list1.equals(list2)) continue LOOP; } i++; } // found it return true; } // didn't find it return false; } // contains():boolean /** * Returns -1 if this value store contains the specified * values, otherwise the index of the first field in the * key sequence. */ public int contains(ValueStoreBase vsb) { final Vector values = vsb.fValues; final int size1 = values.size(); if (fFieldCount <= 1) { for (int i = 0; i < size1; ++i) { short val = vsb.getValueTypeAt(i); if (!valueTypeContains(val) || !fValues.contains(values.elementAt(i))) { return i; } else if(val == XSConstants.LIST_DT || val == XSConstants.LISTOFUNION_DT) { ShortList list1 = vsb.getItemValueTypeAt(i); if (!itemValueTypeContains(list1)) { return i; } } } } /** Handle n-tuples. **/ else { final int size2 = fValues.size(); /** Iterate over each set of fields. **/ OUTER: for (int i = 0; i < size1; i += fFieldCount) { /** Check whether this set is contained in the value store. **/ INNER: for (int j = 0; j < size2; j += fFieldCount) { for (int k = 0; k < fFieldCount; ++k) { final Object value1 = values.elementAt(i+k); final Object value2 = fValues.elementAt(j+k); final short valueType1 = vsb.getValueTypeAt(i+k); final short valueType2 = getValueTypeAt(j+k); if (value1 != value2 && (valueType1 != valueType2 || value1 == null || !value1.equals(value2))) { continue INNER; } else if(valueType1 == XSConstants.LIST_DT || valueType1 == XSConstants.LISTOFUNION_DT) { ShortList list1 = vsb.getItemValueTypeAt(i+k); ShortList list2 = getItemValueTypeAt(j+k); if (list1 == null || list2 == null || !list1.equals(list2)) { continue INNER; } } } continue OUTER; } return i; } } return -1; } // contains(Vector):Object // // Protected methods // protected void checkDuplicateValues() { // no-op } // duplicateValue(Hashtable) /** Returns a string of the specified values. */ protected String toString(Object[] values) { // no values int size = values.length; if (size == 0) { return ""; } fTempBuffer.setLength(0); // construct value string for (int i = 0; i < size; i++) { if (i > 0) { fTempBuffer.append(','); } fTempBuffer.append(values[i]); } return fTempBuffer.toString(); } // toString(Object[]):String /** Returns a string of the specified values. */ protected String toString(Vector values, int start, int length) { // no values if (length == 0) { return ""; } // one value if (length == 1) { return String.valueOf(values.elementAt(start)); } // construct value string StringBuffer str = new StringBuffer(); for (int i = 0; i < length; i++) { if (i > 0) { str.append(','); } str.append(values.elementAt(start + i)); } return str.toString(); } // toString(Vector,int,int):String // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { s = s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { s = s.substring(index2 + 1); } return s + '[' + fIdentityConstraint + ']'; } // toString():String // // Private methods // private void addValueType(short type) { if (fUseValueTypeVector) { fValueTypes.add(type); } else if (fValueTypesLength++ == 0) { fValueType = type; } else if (fValueType != type) { fUseValueTypeVector = true; if (fValueTypes == null) { fValueTypes = new ShortVector(fValueTypesLength * 2); } for (int i = 1; i < fValueTypesLength; ++i) { fValueTypes.add(fValueType); } fValueTypes.add(type); } } private short getValueTypeAt(int index) { if (fUseValueTypeVector) { return fValueTypes.valueAt(index); } return fValueType; } private boolean valueTypeContains(short value) { if (fUseValueTypeVector) { return fValueTypes.contains(value); } return fValueType == value; } private void addItemValueType(ShortList itemValueType) { if (fUseItemValueTypeVector) { fItemValueTypes.add(itemValueType); } else if (fItemValueTypesLength++ == 0) { fItemValueType = itemValueType; } else if (!(fItemValueType == itemValueType || (fItemValueType != null && fItemValueType.equals(itemValueType)))) { fUseItemValueTypeVector = true; if (fItemValueTypes == null) { fItemValueTypes = new Vector(fItemValueTypesLength * 2); } for (int i = 1; i < fItemValueTypesLength; ++i) { fItemValueTypes.add(fItemValueType); } fItemValueTypes.add(itemValueType); } } private ShortList getItemValueTypeAt(int index) { if (fUseItemValueTypeVector) { return (ShortList) fItemValueTypes.elementAt(index); } return fItemValueType; } private boolean itemValueTypeContains(ShortList value) { if (fUseItemValueTypeVector) { return fItemValueTypes.contains(value); } return fItemValueType == value || (fItemValueType != null && fItemValueType.equals(value)); } } // class ValueStoreBase /** * Unique value store. * * @author Andy Clark, IBM */ protected class UniqueValueStore extends ValueStoreBase { // // Constructors // /** Constructs a unique value store. */ public UniqueValueStore(UniqueOrKey unique) { super(unique); } // <init>(Unique) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. */ protected void checkDuplicateValues() { // is this value as a group duplicated? if (contains()) { String code = "DuplicateUnique"; String value = toString(fLocalValues); String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { value, eName, cName }); } } // duplicateValue(Hashtable) } // class UniqueValueStore /** * Key value store. * * @author Andy Clark, IBM */ protected class KeyValueStore extends ValueStoreBase { // REVISIT: Implement a more efficient storage mechanism. -Ac // // Constructors // /** Constructs a key value store. */ public KeyValueStore(UniqueOrKey key) { super(key); } // <init>(Key) // // ValueStoreBase protected methods // /** * Called when a duplicate value is added. */ protected void checkDuplicateValues() { if (contains()) { String code = "DuplicateKey"; String value = toString(fLocalValues); String eName = fIdentityConstraint.getElementName(); String cName = fIdentityConstraint.getIdentityConstraintName(); reportSchemaError(code, new Object[] { value, eName, cName }); } } // duplicateValue(Hashtable) } // class KeyValueStore /** * Key reference value store. * * @author Andy Clark, IBM */ protected class KeyRefValueStore extends ValueStoreBase { // // Data // /** Key value store. */ protected ValueStoreBase fKeyValueStore; // // Constructors // /** Constructs a key value store. */ public KeyRefValueStore(KeyRef keyRef, KeyValueStore keyValueStore) { super(keyRef); fKeyValueStore = keyValueStore; } // <init>(KeyRef) // // ValueStoreBase methods // // end the value Scope; here's where we have to tie // up keyRef loose ends. public void endDocumentFragment() { // do all the necessary management... super.endDocumentFragment(); // verify references // get the key store corresponding (if it exists): fKeyValueStore = (ValueStoreBase) fValueStoreCache.fGlobalIDConstraintMap.get( ((KeyRef) fIdentityConstraint).getKey()); if (fKeyValueStore == null) { // report error String code = "KeyRefOutOfScope"; String value = fIdentityConstraint.toString(); reportSchemaError(code, new Object[] { value }); return; } int errorIndex = fKeyValueStore.contains(this); if (errorIndex != -1) { String code = "KeyNotFound"; String values = toString(fValues, errorIndex, fFieldCount); String element = fIdentityConstraint.getElementName(); String name = fIdentityConstraint.getName(); reportSchemaError(code, new Object[] { name, values, element }); } } // endDocumentFragment() /** End document. */ public void endDocument() { super.endDocument(); } // endDocument() } // class KeyRefValueStore // value store management /** * Value store cache. This class is used to store the values for * identity constraints. * * @author Andy Clark, IBM */ protected class ValueStoreCache { // // Data // final LocalIDKey fLocalId = new LocalIDKey(); // values stores /** stores all global Values stores. */ protected final ArrayList fValueStores = new ArrayList(); /** * Values stores associated to specific identity constraints. * This hashtable maps IdentityConstraints and * the 0-based element on which their selectors first matched to * a corresponding ValueStore. This should take care * of all cases, including where ID constraints with * descendant-or-self axes occur on recursively-defined * elements. */ protected final HashMap fIdentityConstraint2ValueStoreMap = new HashMap(); // sketch of algorithm: // - when a constraint is first encountered, its // values are stored in the (local) fIdentityConstraint2ValueStoreMap; // - Once it is validated (i.e., when it goes out of scope), // its values are merged into the fGlobalIDConstraintMap; // - as we encounter keyref's, we look at the global table to // validate them. // // The fGlobalIDMapStack has the following structure: // - validation always occurs against the fGlobalIDConstraintMap // (which comprises all the "eligible" id constraints); // When an endElement is found, this Hashtable is merged with the one // below in the stack. // When a start tag is encountered, we create a new // fGlobalIDConstraintMap. // i.e., the top of the fGlobalIDMapStack always contains // the preceding siblings' eligible id constraints; // the fGlobalIDConstraintMap contains descendants+self. // keyrefs can only match descendants+self. protected final Stack fGlobalMapStack = new Stack(); protected final HashMap fGlobalIDConstraintMap = new HashMap(); // // Constructors // /** Default constructor. */ public ValueStoreCache() { } // <init>() // // Public methods // /** Resets the identity constraint cache. */ public void startDocument() { fValueStores.clear(); fIdentityConstraint2ValueStoreMap.clear(); fGlobalIDConstraintMap.clear(); fGlobalMapStack.removeAllElements(); } // startDocument() // startElement: pushes the current fGlobalIDConstraintMap // onto fGlobalMapStack and clears fGlobalIDConstraint map. public void startElement() { // only clone the map when there are elements if (fGlobalIDConstraintMap.size() > 0) fGlobalMapStack.push(fGlobalIDConstraintMap.clone()); else fGlobalMapStack.push(null); fGlobalIDConstraintMap.clear(); } // startElement(void) /** endElement(): merges contents of fGlobalIDConstraintMap with the * top of fGlobalMapStack into fGlobalIDConstraintMap. */ public void endElement() { if (fGlobalMapStack.isEmpty()) { return; // must be an invalid doc! } HashMap oldMap = (HashMap) fGlobalMapStack.pop(); // return if there is no element if (oldMap == null) { return; } Iterator entries = oldMap.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); IdentityConstraint id = (IdentityConstraint) entry.getKey(); ValueStoreBase oldVal = (ValueStoreBase) entry.getValue(); if (oldVal != null) { ValueStoreBase currVal = (ValueStoreBase) fGlobalIDConstraintMap.get(id); if (currVal == null) { fGlobalIDConstraintMap.put(id, oldVal); } else if (currVal != oldVal) { currVal.append(oldVal); } } } } // endElement() /** * Initializes the value stores for the specified element * declaration. */ public void initValueStoresFor(XSElementDecl eDecl, FieldActivator activator) { // initialize value stores for unique fields IdentityConstraint[] icArray = eDecl.fIDConstraints; int icCount = eDecl.fIDCPos; for (int i = 0; i < icCount; i++) { switch (icArray[i].getCategory()) { case (IdentityConstraint.IC_UNIQUE) : // initialize value stores for unique fields UniqueOrKey unique = (UniqueOrKey) icArray[i]; LocalIDKey toHash = new LocalIDKey(unique, fElementDepth); UniqueValueStore uniqueValueStore = (UniqueValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (uniqueValueStore == null) { uniqueValueStore = new UniqueValueStore(unique); fIdentityConstraint2ValueStoreMap.put(toHash, uniqueValueStore); } else { uniqueValueStore.clear(); } fValueStores.add(uniqueValueStore); activateSelectorFor(icArray[i]); break; case (IdentityConstraint.IC_KEY) : // initialize value stores for key fields UniqueOrKey key = (UniqueOrKey) icArray[i]; toHash = new LocalIDKey(key, fElementDepth); KeyValueStore keyValueStore = (KeyValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (keyValueStore == null) { keyValueStore = new KeyValueStore(key); fIdentityConstraint2ValueStoreMap.put(toHash, keyValueStore); } else { keyValueStore.clear(); } fValueStores.add(keyValueStore); activateSelectorFor(icArray[i]); break; case (IdentityConstraint.IC_KEYREF) : // initialize value stores for keyRef fields KeyRef keyRef = (KeyRef) icArray[i]; toHash = new LocalIDKey(keyRef, fElementDepth); KeyRefValueStore keyRefValueStore = (KeyRefValueStore) fIdentityConstraint2ValueStoreMap.get(toHash); if (keyRefValueStore == null) { keyRefValueStore = new KeyRefValueStore(keyRef, null); fIdentityConstraint2ValueStoreMap.put(toHash, keyRefValueStore); } else { keyRefValueStore.clear(); } fValueStores.add(keyRefValueStore); activateSelectorFor(icArray[i]); break; } } } // initValueStoresFor(XSElementDecl) /** Returns the value store associated to the specified IdentityConstraint. */ public ValueStoreBase getValueStoreFor(IdentityConstraint id, int initialDepth) { fLocalId.fDepth = initialDepth; fLocalId.fId = id; return (ValueStoreBase) fIdentityConstraint2ValueStoreMap.get(fLocalId); } // getValueStoreFor(IdentityConstraint, int):ValueStoreBase /** Returns the global value store associated to the specified IdentityConstraint. */ public ValueStoreBase getGlobalValueStoreFor(IdentityConstraint id) { return (ValueStoreBase) fGlobalIDConstraintMap.get(id); } // getValueStoreFor(IdentityConstraint):ValueStoreBase // This method takes the contents of the (local) ValueStore // associated with id and moves them into the global // hashtable, if id is a <unique> or a <key>. // If it's a <keyRef>, then we leave it for later. public void transplant(IdentityConstraint id, int initialDepth) { fLocalId.fDepth = initialDepth; fLocalId.fId = id; ValueStoreBase newVals = (ValueStoreBase) fIdentityConstraint2ValueStoreMap.get(fLocalId); if (id.getCategory() == IdentityConstraint.IC_KEYREF) return; ValueStoreBase currVals = (ValueStoreBase) fGlobalIDConstraintMap.get(id); if (currVals != null) { currVals.append(newVals); fGlobalIDConstraintMap.put(id, currVals); } else fGlobalIDConstraintMap.put(id, newVals); } // transplant(id) /** Check identity constraints. */ public void endDocument() { int count = fValueStores.size(); for (int i = 0; i < count; i++) { ValueStoreBase valueStore = (ValueStoreBase) fValueStores.get(i); valueStore.endDocument(); } } // endDocument() // // Object methods // /** Returns a string representation of this object. */ public String toString() { String s = super.toString(); int index1 = s.lastIndexOf('$'); if (index1 != -1) { return s.substring(index1 + 1); } int index2 = s.lastIndexOf('.'); if (index2 != -1) { return s.substring(index2 + 1); } return s; } // toString():String } // class ValueStoreCache // the purpose of this class is to enable IdentityConstraint,int // pairs to be used easily as keys in Hashtables. protected static final class LocalIDKey { public IdentityConstraint fId; public int fDepth; public LocalIDKey() { } public LocalIDKey(IdentityConstraint id, int depth) { fId = id; fDepth = depth; } // init(IdentityConstraint, int) // object method public int hashCode() { return fId.hashCode() + fDepth; } public boolean equals(Object localIDKey) { if (localIDKey instanceof LocalIDKey) { LocalIDKey lIDKey = (LocalIDKey) localIDKey; return (lIDKey.fId == fId && lIDKey.fDepth == fDepth); } return false; } } // class LocalIDKey /** * A simple vector for <code>short</code>s. */ protected static final class ShortVector { // // Data // /** Current length. */ private int fLength; /** Data. */ private short[] fData; // // Constructors // public ShortVector() {} public ShortVector(int initialCapacity) { fData = new short[initialCapacity]; } // // Public methods // /** Returns the length of the vector. */ public int length() { return fLength; } /** Adds the value to the vector. */ public void add(short value) { ensureCapacity(fLength + 1); fData[fLength++] = value; } /** Returns the short value at the specified position in the vector. */ public short valueAt(int position) { return fData[position]; } /** Clears the vector. */ public void clear() { fLength = 0; } /** Returns whether the short is contained in the vector. */ public boolean contains(short value) { for (int i = 0; i < fLength; ++i) { if (fData[i] == value) { return true; } } return false; } // // Private methods // /** Ensures capacity. */ private void ensureCapacity(int size) { if (fData == null) { fData = new short[8]; } else if (fData.length <= size) { short[] newdata = new short[fData.length * 2]; System.arraycopy(fData, 0, newdata, 0, fData.length); fData = newdata; } } } } // class SchemaValidator
true
true
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { element.rawname, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.fAnyType; fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.fAnyType; else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } return augs; } // handleStartElement(QName,XMLAttributes,boolean)
Augmentations handleStartElement(QName element, XMLAttributes attributes, Augmentations augs) { if (DEBUG) { System.out.println("==>handleStartElement: " + element); } // root element if (fElementDepth == -1 && fValidationManager.isGrammarFound()) { if (fSchemaType == null) { // schemaType is not specified // if a DTD grammar is found, we do the same thing as Dynamic: // if a schema grammar is found, validation is performed; // otherwise, skip the whole document. fSchemaDynamicValidation = true; } else { // [1] Either schemaType is DTD, and in this case validate/schema is turned off // [2] Validating against XML Schemas only // [a] dynamic validation is false: report error if SchemaGrammar is not found // [b] dynamic validation is true: if grammar is not found ignore. } } // get xsi:schemaLocation and xsi:noNamespaceSchemaLocation attributes, // parse them to get the grammars. But only do this if the grammar can grow. if (!fUseGrammarPoolOnly) { String sLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_SCHEMALOCATION); String nsLocation = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); //store the location hints.. we need to do it so that we can defer the loading of grammar until //there is a reference to a component from that namespace. To provide location hints to the //application for a namespace storeLocations(sLocation, nsLocation); } // if we are in the content of "skip", then just skip this element // REVISIT: is this the correct behaviour for ID constraints? -NG if (fSkipValidationDepth >= 0) { fElementDepth++; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // if we are not skipping this element, and there is a content model, // we try to find the corresponding decl object for this element. // the reason we move this part of code here is to make sure the // error reported here (if any) is stored within the parent element's // context, instead of that of the current element. Object decl = null; if (fCurrentCM != null) { decl = fCurrentCM.oneTransition(element, fCurrCMState, fSubGroupHandler); // it could be an element decl or a wildcard decl if (fCurrCMState[0] == XSCMValidator.FIRST_ERROR) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; //REVISIT: is it the only case we will have particle = null? Vector next; if (ctype.fParticle != null && (next = fCurrentCM.whatCanGoHere(fCurrCMState)).size() > 0) { String expected = expectedStr(next); final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); String elemExpandedQname = (element.uri != null) ? "{"+'"'+element.uri+'"'+":"+element.localpart+"}" : element.localpart; if (occurenceInfo != null) { final int minOccurs = occurenceInfo[0]; final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of minOccurs if (count < minOccurs) { final int required = minOccurs - count; if (required > 1) { reportSchemaError("cvc-complex-type.2.4.h", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs), Integer.toString(required) }); } else { reportSchemaError("cvc-complex-type.2.4.g", new Object[] { element.rawname, fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(minOccurs) }); } } // Check if this is a violation of maxOccurs else if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.e", new Object[] { element.rawname, expected, Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { reportSchemaError("cvc-complex-type.2.4.a", new Object[] { elemExpandedQname, expected }); } } else { final int[] occurenceInfo = fCurrentCM.occurenceInfo(fCurrCMState); if (occurenceInfo != null) { final int maxOccurs = occurenceInfo[1]; final int count = occurenceInfo[2]; // Check if this is a violation of maxOccurs if (count >= maxOccurs && maxOccurs != SchemaSymbols.OCCURRENCE_UNBOUNDED) { reportSchemaError("cvc-complex-type.2.4.f", new Object[] { fCurrentCM.getTermName(occurenceInfo[3]), Integer.toString(maxOccurs) }); } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } else { reportSchemaError("cvc-complex-type.2.4.d", new Object[] { element.rawname }); } } } } // if it's not the root element, we push the current states in the stacks if (fElementDepth != -1) { ensureStackCapacity(); fSubElementStack[fElementDepth] = true; fSubElement = false; fElemDeclStack[fElementDepth] = fCurrentElemDecl; fNilStack[fElementDepth] = fNil; fNotationStack[fElementDepth] = fNotation; fTypeStack[fElementDepth] = fCurrentType; fStrictAssessStack[fElementDepth] = fStrictAssess; fCMStack[fElementDepth] = fCurrentCM; fCMStateStack[fElementDepth] = fCurrCMState; fSawTextStack[fElementDepth] = fSawText; fStringContent[fElementDepth] = fSawCharacters; } // increase the element depth after we've saved // all states for the parent element fElementDepth++; fCurrentElemDecl = null; XSWildcardDecl wildcard = null; fCurrentType = null; fStrictAssess = true; fNil = false; fNotation = null; // and the buffer to hold the value of the element fBuffer.setLength(0); fSawText = false; fSawCharacters = false; // check what kind of declaration the "decl" from // oneTransition() maps to if (decl != null) { if (decl instanceof XSElementDecl) { fCurrentElemDecl = (XSElementDecl) decl; } else { wildcard = (XSWildcardDecl) decl; } } // if the wildcard is skip, then return if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_SKIP) { fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } if (fElementDepth == 0) { // 1.1.1.1 An element declaration was stipulated by the processor if (fRootElementDeclaration != null) { fCurrentElemDecl = fRootElementDeclaration; checkElementMatchesRootElementDecl(fCurrentElemDecl, element); } else if (fRootElementDeclQName != null) { processRootElementDeclQName(fRootElementDeclQName, element); } // 1.2.1.1 A type definition was stipulated by the processor else if (fRootTypeDefinition != null) { fCurrentType = fRootTypeDefinition; } else if (fRootTypeQName != null) { processRootTypeQName(fRootTypeQName); } } // if there was no processor stipulated type if (fCurrentType == null) { // try again to get the element decl: // case 1: find declaration for root element // case 2: find declaration for element from another namespace if (fCurrentElemDecl == null) { // try to find schema grammar by different means.. SchemaGrammar sGrammar = findSchemaGrammar( XSDDescription.CONTEXT_ELEMENT, element.uri, null, element, attributes); if (sGrammar != null) { fCurrentElemDecl = sGrammar.getGlobalElementDecl(element.localpart); } } if (fCurrentElemDecl != null) { // then get the type fCurrentType = fCurrentElemDecl.fType; } } // check if we should be ignoring xsi:type on this element if (fElementDepth == fIgnoreXSITypeDepth && fCurrentElemDecl == null) { fIgnoreXSITypeDepth++; } // process xsi:type attribute information String xsiType = null; if (fElementDepth >= fIgnoreXSITypeDepth) { xsiType = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_TYPE); } // if no decl/type found for the current element if (fCurrentType == null && xsiType == null) { // if this is the validation root, report an error, because // we can't find eith decl or type for this element // REVISIT: should we report error, or warning? if (fElementDepth == 0) { // for dynamic validation, skip the whole content, // because no grammar was found. if (fDynamicValidation || fSchemaDynamicValidation) { // no schema grammar was found, but it's either dynamic // validation, or another kind of grammar was found (DTD, // for example). The intended behavior here is to skip // the whole document. To improve performance, we try to // remove the validator from the pipeline, since it's not // supposed to do anything. if (fDocumentSource != null) { fDocumentSource.setDocumentHandler(fDocumentHandler); if (fDocumentHandler != null) fDocumentHandler.setDocumentSource(fDocumentSource); // indicate that the validator was removed. fElementDepth = -2; return augs; } fSkipValidationDepth = fElementDepth; if (fAugPSVI) augs = getEmptyAugs(augs); return augs; } // We don't call reportSchemaError here, because the spec // doesn't think it's invalid not to be able to find a // declaration or type definition for an element. Xerces is // reporting it as an error for historical reasons, but in // PSVI, we shouldn't mark this element as invalid because // of this. - SG fXSIErrorReporter.fErrorReporter.reportError( XSMessageFormatter.SCHEMA_DOMAIN, "cvc-elt.1.a", new Object[] { element.rawname }, XMLErrorReporter.SEVERITY_ERROR); } // if wildcard = strict, report error. // needs to be called before fXSIErrorReporter.pushContext() // so that the error belongs to the parent element. else if (wildcard != null && wildcard.fProcessContents == XSWildcardDecl.PC_STRICT) { // report error, because wilcard = strict reportSchemaError("cvc-complex-type.2.4.c", new Object[] { element.rawname }); } // no element decl or type found for this element. // Allowed by the spec, we can choose to either laxly assess this // element, or to skip it. Now we choose lax assessment. fCurrentType = SchemaGrammar.fAnyType; fStrictAssess = false; fNFullValidationDepth = fElementDepth; // any type has mixed content, so we don't need to append buffer fAppendBuffer = false; // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); } else { // push error reporter context: record the current position // This has to happen after we process skip contents, // otherwise push and pop won't be correctly paired. fXSIErrorReporter.pushContext(); // get xsi:type if (xsiType != null) { XSTypeDefinition oldType = fCurrentType; fCurrentType = getAndCheckXsiType(element, xsiType, attributes); // If it fails, use the old type. Use anyType if ther is no old type. if (fCurrentType == null) { if (oldType == null) fCurrentType = SchemaGrammar.fAnyType; else fCurrentType = oldType; } } fNNoneValidationDepth = fElementDepth; // if the element has a fixed value constraint, we need to append if (fCurrentElemDecl != null && fCurrentElemDecl.getConstraintType() == XSConstants.VC_FIXED) { fAppendBuffer = true; } // if the type is simple, we need to append else if (fCurrentType.getTypeCategory() == XSTypeDefinition.SIMPLE_TYPE) { fAppendBuffer = true; } else { // if the type is simple content complex type, we need to append XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; fAppendBuffer = (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE); } } // Element Locally Valid (Element) // 2 Its {abstract} must be false. if (fCurrentElemDecl != null && fCurrentElemDecl.getAbstract()) reportSchemaError("cvc-elt.2", new Object[] { element.rawname }); // make the current element validation root if (fElementDepth == 0) { fValidationRoot = element.rawname; } // update normalization flags if (fNormalizeData) { // reset values fFirstChunk = true; fTrailing = false; fUnionType = false; fWhiteSpace = -1; } // Element Locally Valid (Type) // 2 Its {abstract} must be false. if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; if (ctype.getAbstract()) { reportSchemaError("cvc-type.2", new Object[] { element.rawname }); } if (fNormalizeData) { // find out if the content type is simple and if variety is union // to be able to do character normalization if (ctype.fContentType == XSComplexTypeDecl.CONTENTTYPE_SIMPLE) { if (ctype.fXSSimpleType.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = ctype.fXSSimpleType.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } } } // normalization: simple type else if (fNormalizeData) { // if !union type XSSimpleType dv = (XSSimpleType) fCurrentType; if (dv.getVariety() == XSSimpleType.VARIETY_UNION) { fUnionType = true; } else { try { fWhiteSpace = dv.getWhitespace(); } catch (DatatypeException e) { // do nothing } } } // then try to get the content model fCurrentCM = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { fCurrentCM = ((XSComplexTypeDecl) fCurrentType).getContentModel(fCMBuilder); } // and get the initial content model state fCurrCMState = null; if (fCurrentCM != null) fCurrCMState = fCurrentCM.startContentModel(); // get information about xsi:nil String xsiNil = attributes.getValue(SchemaSymbols.URI_XSI, SchemaSymbols.XSI_NIL); // only deal with xsi:nil when there is an element declaration if (xsiNil != null && fCurrentElemDecl != null) fNil = getXsiNil(element, xsiNil); // now validate everything related with the attributes // first, get the attribute group XSAttributeGroupDecl attrGrp = null; if (fCurrentType.getTypeCategory() == XSTypeDefinition.COMPLEX_TYPE) { XSComplexTypeDecl ctype = (XSComplexTypeDecl) fCurrentType; attrGrp = ctype.getAttrGrp(); } if (fIDCChecking) { // activate identity constraints fValueStoreCache.startElement(); fMatcherStack.pushContext(); //if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0 && !fIgnoreIDC) { if (fCurrentElemDecl != null && fCurrentElemDecl.fIDCPos > 0) { fIdConstraint = true; // initialize when identity constrains are defined for the elem fValueStoreCache.initValueStoresFor(fCurrentElemDecl, this); } } processAttributes(element, attributes, attrGrp); // add default attributes if (attrGrp != null) { addDefaultAttributes(element, attributes, attrGrp); } // call all active identity constraints int count = fMatcherStack.getMatcherCount(); for (int i = 0; i < count; i++) { XPathMatcher matcher = fMatcherStack.getMatcherAt(i); matcher.startElement( element, attributes); } if (fAugPSVI) { augs = getEmptyAugs(augs); // PSVI: add validation context fCurrentPSVI.fValidationContext = fValidationRoot; // PSVI: add element declaration fCurrentPSVI.fDeclaration = fCurrentElemDecl; // PSVI: add element type fCurrentPSVI.fTypeDecl = fCurrentType; // PSVI: add notation attribute fCurrentPSVI.fNotation = fNotation; // PSVI: add nil fCurrentPSVI.fNil = fNil; } return augs; } // handleStartElement(QName,XMLAttributes,boolean)
diff --git a/astrid/src/com/todoroo/astrid/utility/AstridLitePreferenceSpec.java b/astrid/src/com/todoroo/astrid/utility/AstridLitePreferenceSpec.java index 70d6a487e..ac4a05ef5 100644 --- a/astrid/src/com/todoroo/astrid/utility/AstridLitePreferenceSpec.java +++ b/astrid/src/com/todoroo/astrid/utility/AstridLitePreferenceSpec.java @@ -1,131 +1,131 @@ package com.todoroo.astrid.utility; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Resources; import com.timsu.astrid.R; import com.todoroo.andlib.service.ContextManager; import com.todoroo.andlib.utility.Preferences; import com.todoroo.astrid.activity.BeastModePreferences; import com.todoroo.astrid.core.SortHelper; import com.todoroo.astrid.data.Task; import com.todoroo.astrid.service.ThemeService; import com.todoroo.astrid.utility.AstridDefaultPreferenceSpec.PreferenceExtras; public class AstridLitePreferenceSpec extends AstridPreferenceSpec { @Override public void setIfUnset() { PreferenceExtras extras = new PreferenceExtras() { @Override public void setExtras(Context context, SharedPreferences prefs, Editor editor, Resources r, boolean ifUnset) { String dragDropTestInitialized = "android_drag_drop_initialized"; //$NON-NLS-1$ if (!Preferences.getBoolean(dragDropTestInitialized, false)) { SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context); if (publicPrefs != null) { Editor edit = publicPrefs.edit(); if (edit != null) { edit.putInt(SortHelper.PREF_SORT_FLAGS, SortHelper.FLAG_DRAG_DROP); edit.putInt(SortHelper.PREF_SORT_SORT, SortHelper.SORT_AUTO); edit.commit(); Preferences.setInt(AstridPreferences.P_SUBTASKS_HELP, 1); } } Preferences.setBoolean(dragDropTestInitialized, true); } BeastModePreferences.setDefaultLiteModeOrder(context, false); } }; setPrefs(extras, true); } @Override public void resetDefaults() { PreferenceExtras extras = new PreferenceExtras() { @Override public void setExtras(Context context, SharedPreferences prefs, Editor editor, Resources r, boolean ifUnset) { SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(context); if (publicPrefs != null) { Editor edit = publicPrefs.edit(); if (edit != null) { edit.putInt(SortHelper.PREF_SORT_FLAGS, SortHelper.FLAG_DRAG_DROP); edit.putInt(SortHelper.PREF_SORT_SORT, SortHelper.SORT_AUTO); edit.commit(); Preferences.setInt(AstridPreferences.P_SUBTASKS_HELP, 1); } } BeastModePreferences.setDefaultLiteModeOrder(context, true); } }; setPrefs(extras, false); } private static void setPrefs(PreferenceExtras extras, boolean ifUnset) { Context context = ContextManager.getContext(); SharedPreferences prefs = Preferences.getPrefs(context); Editor editor = prefs.edit(); Resources r = context.getResources(); setPreference(prefs, editor, r, R.string.p_default_urgency_key, 4, ifUnset); setPreference(prefs, editor, r, R.string.p_default_importance_key, 2, ifUnset); setPreference(prefs, editor, r, R.string.p_default_hideUntil_key, 0, ifUnset); setPreference(prefs, editor, r, R.string.p_default_reminders_key, Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE, ifUnset); setPreference(prefs, editor, r, R.string.p_default_reminders_mode_key, 16, ifUnset); setPreference(prefs, editor, r, R.string.p_rmd_default_random_hours, 0, ifUnset); setPreference(prefs, editor, r, R.string.p_fontSize, 20, ifUnset); setPreference(prefs, editor, r, R.string.p_showNotes, false, ifUnset); setPreference(prefs, editor, r, R.string.p_use_contact_picker, false, ifUnset); setPreference(prefs, editor, r, R.string.p_field_missed_calls, true, ifUnset); setPreference(prefs, editor, r, R.string.p_third_party_addons, false, ifUnset); setPreference(prefs, editor, r, R.string.p_end_at_deadline, true, ifUnset); setPreference(prefs, editor, r, R.string.p_rmd_persistent, true, ifUnset); setPreference(prefs, editor, r, R.string.p_ideas_tab_enabled, false, ifUnset); setPreference(prefs, editor, r, R.string.p_autoIdea, false, ifUnset); setPreference(prefs, editor, r, R.string.p_taskRowStyle, false, ifUnset); setPreference(prefs, editor, r, R.string.p_calendar_reminders, true, ifUnset); setPreference(prefs, editor, r, R.string.p_use_filters, false, ifUnset); setPreference(prefs, editor, r, R.string.p_simple_input_boxes, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_list_members, false, ifUnset); setPreference(prefs, editor, r, R.string.p_theme, ThemeService.THEME_WHITE_ALT, ifUnset); setPreference(prefs, editor, r, R.string.p_force_phone_layout, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_today_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_recently_modified_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_ive_assigned_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_not_in_list_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_search, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_friends, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_featured_lists, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_sync, false, ifUnset); - setPreference(prefs, editor, r, R.string.p_show_menu_sort, false, ifUnset); + setPreference(prefs, editor, r, R.string.p_show_menu_sort, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_addons, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_quickadd_controls, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_task_edit_comments, false, ifUnset); extras.setExtras(context, prefs, editor, r, ifUnset); editor.commit(); } }
true
true
private static void setPrefs(PreferenceExtras extras, boolean ifUnset) { Context context = ContextManager.getContext(); SharedPreferences prefs = Preferences.getPrefs(context); Editor editor = prefs.edit(); Resources r = context.getResources(); setPreference(prefs, editor, r, R.string.p_default_urgency_key, 4, ifUnset); setPreference(prefs, editor, r, R.string.p_default_importance_key, 2, ifUnset); setPreference(prefs, editor, r, R.string.p_default_hideUntil_key, 0, ifUnset); setPreference(prefs, editor, r, R.string.p_default_reminders_key, Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE, ifUnset); setPreference(prefs, editor, r, R.string.p_default_reminders_mode_key, 16, ifUnset); setPreference(prefs, editor, r, R.string.p_rmd_default_random_hours, 0, ifUnset); setPreference(prefs, editor, r, R.string.p_fontSize, 20, ifUnset); setPreference(prefs, editor, r, R.string.p_showNotes, false, ifUnset); setPreference(prefs, editor, r, R.string.p_use_contact_picker, false, ifUnset); setPreference(prefs, editor, r, R.string.p_field_missed_calls, true, ifUnset); setPreference(prefs, editor, r, R.string.p_third_party_addons, false, ifUnset); setPreference(prefs, editor, r, R.string.p_end_at_deadline, true, ifUnset); setPreference(prefs, editor, r, R.string.p_rmd_persistent, true, ifUnset); setPreference(prefs, editor, r, R.string.p_ideas_tab_enabled, false, ifUnset); setPreference(prefs, editor, r, R.string.p_autoIdea, false, ifUnset); setPreference(prefs, editor, r, R.string.p_taskRowStyle, false, ifUnset); setPreference(prefs, editor, r, R.string.p_calendar_reminders, true, ifUnset); setPreference(prefs, editor, r, R.string.p_use_filters, false, ifUnset); setPreference(prefs, editor, r, R.string.p_simple_input_boxes, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_list_members, false, ifUnset); setPreference(prefs, editor, r, R.string.p_theme, ThemeService.THEME_WHITE_ALT, ifUnset); setPreference(prefs, editor, r, R.string.p_force_phone_layout, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_today_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_recently_modified_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_ive_assigned_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_not_in_list_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_search, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_friends, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_featured_lists, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_sync, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_sort, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_addons, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_quickadd_controls, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_task_edit_comments, false, ifUnset); extras.setExtras(context, prefs, editor, r, ifUnset); editor.commit(); }
private static void setPrefs(PreferenceExtras extras, boolean ifUnset) { Context context = ContextManager.getContext(); SharedPreferences prefs = Preferences.getPrefs(context); Editor editor = prefs.edit(); Resources r = context.getResources(); setPreference(prefs, editor, r, R.string.p_default_urgency_key, 4, ifUnset); setPreference(prefs, editor, r, R.string.p_default_importance_key, 2, ifUnset); setPreference(prefs, editor, r, R.string.p_default_hideUntil_key, 0, ifUnset); setPreference(prefs, editor, r, R.string.p_default_reminders_key, Task.NOTIFY_AT_DEADLINE | Task.NOTIFY_AFTER_DEADLINE, ifUnset); setPreference(prefs, editor, r, R.string.p_default_reminders_mode_key, 16, ifUnset); setPreference(prefs, editor, r, R.string.p_rmd_default_random_hours, 0, ifUnset); setPreference(prefs, editor, r, R.string.p_fontSize, 20, ifUnset); setPreference(prefs, editor, r, R.string.p_showNotes, false, ifUnset); setPreference(prefs, editor, r, R.string.p_use_contact_picker, false, ifUnset); setPreference(prefs, editor, r, R.string.p_field_missed_calls, true, ifUnset); setPreference(prefs, editor, r, R.string.p_third_party_addons, false, ifUnset); setPreference(prefs, editor, r, R.string.p_end_at_deadline, true, ifUnset); setPreference(prefs, editor, r, R.string.p_rmd_persistent, true, ifUnset); setPreference(prefs, editor, r, R.string.p_ideas_tab_enabled, false, ifUnset); setPreference(prefs, editor, r, R.string.p_autoIdea, false, ifUnset); setPreference(prefs, editor, r, R.string.p_taskRowStyle, false, ifUnset); setPreference(prefs, editor, r, R.string.p_calendar_reminders, true, ifUnset); setPreference(prefs, editor, r, R.string.p_use_filters, false, ifUnset); setPreference(prefs, editor, r, R.string.p_simple_input_boxes, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_list_members, false, ifUnset); setPreference(prefs, editor, r, R.string.p_theme, ThemeService.THEME_WHITE_ALT, ifUnset); setPreference(prefs, editor, r, R.string.p_force_phone_layout, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_today_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_recently_modified_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_ive_assigned_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_not_in_list_filter, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_search, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_friends, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_featured_lists, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_sync, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_sort, true, ifUnset); setPreference(prefs, editor, r, R.string.p_show_menu_addons, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_quickadd_controls, false, ifUnset); setPreference(prefs, editor, r, R.string.p_show_task_edit_comments, false, ifUnset); extras.setExtras(context, prefs, editor, r, ifUnset); editor.commit(); }