Search in sources :

Example 1 with ModuleException

use of org.openmrs.module.ModuleException in project openmrs-core by openmrs.

the class ModuleFilterMapping method retrieveFilterMappings.

/**
 * Static method to parse through a Module's configuration file and return a List of
 * ModuleFilterMapping objects for which there are configuration elements. Expected XML Format:
 *
 * <pre>
 * 	&lt;filter-mapping&gt;
 * 		&lt;filter-name&gt;MyFilterName&lt;/filter-name&gt;
 * 		&lt;url-pattern&gt;The pattern of URLs to match&lt;/filter-class&gt;
 * 	&lt;/filter-mapping&gt;
 * or
 * 	&lt;filter-mapping&gt;
 * 		&lt;filter-name&gt;MyFilterName&lt;/filter-name&gt;
 * 		&lt;servlet-name&gt;The servlet name to match&lt;/servlet-name&gt;
 * 	&lt;/filter-mapping&gt;
 * </pre>
 *
 * @param module - The {@link Module} for which you want to retrieve the defined
 *            {@link ModuleFilterMapping}s
 * @return - a List of {@link ModuleFilterMapping}s that are defined for the passed
 *         {@link Module}
 */
public static List<ModuleFilterMapping> retrieveFilterMappings(Module module) {
    List<ModuleFilterMapping> mappings = new ArrayList<>();
    try {
        Element rootNode = module.getConfig().getDocumentElement();
        NodeList mappingNodes = rootNode.getElementsByTagName("filter-mapping");
        if (mappingNodes.getLength() > 0) {
            for (int i = 0; i < mappingNodes.getLength(); i++) {
                ModuleFilterMapping mapping = new ModuleFilterMapping(module);
                Node node = mappingNodes.item(i);
                NodeList configNodes = node.getChildNodes();
                for (int j = 0; j < configNodes.getLength(); j++) {
                    Node configNode = configNodes.item(j);
                    if ("filter-name".equals(configNode.getNodeName())) {
                        mapping.setFilterName(configNode.getTextContent());
                    } else if ("url-pattern".equals(configNode.getNodeName())) {
                        mapping.addUrlPattern(configNode.getTextContent());
                    } else if ("servlet-name".equals(configNode.getNodeName())) {
                        mapping.addServletName(configNode.getTextContent());
                    }
                }
                mappings.add(mapping);
            }
        }
    } catch (Exception e) {
        throw new ModuleException("Unable to parse filters in module configuration.", e);
    }
    log.debug("Retrieved " + mappings.size() + " filter-mappings for " + module.getModuleId() + ": " + mappings);
    return mappings;
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) ModuleException(org.openmrs.module.ModuleException) ModuleException(org.openmrs.module.ModuleException)

Example 2 with ModuleException

use of org.openmrs.module.ModuleException in project openmrs-core by openmrs.

the class WebModuleUtil method stopModule.

/**
 * Reverses all visible activities done by startModule(org.openmrs.module.Module)
 *
 * @param mod
 * @param servletContext
 * @param skipRefresh
 */
public static void stopModule(Module mod, ServletContext servletContext, boolean skipRefresh) {
    String moduleId = mod.getModuleId();
    String modulePackage = mod.getPackageName();
    // stop all dependent modules
    for (Module dependentModule : ModuleFactory.getStartedModules()) {
        if (!dependentModule.equals(mod) && dependentModule.getRequiredModules().contains(modulePackage)) {
            stopModule(dependentModule, servletContext, skipRefresh);
        }
    }
    String realPath = getRealPath(servletContext);
    // delete the web files from the webapp
    String absPath = realPath + "/WEB-INF/view/module/" + moduleId;
    File moduleWebFolder = new File(absPath.replace("/", File.separator));
    if (moduleWebFolder.exists()) {
        try {
            OpenmrsUtil.deleteDirectory(moduleWebFolder);
        } catch (IOException io) {
            log.warn("Couldn't delete: " + moduleWebFolder.getAbsolutePath(), io);
        }
    }
    // (not) deleting module message properties
    // remove the module's servlets
    unloadServlets(mod);
    // remove the module's filters and filter mappings
    unloadFilters(mod);
    // stop all tasks associated with mod
    stopTasks(mod);
    // remove this module's entries in the dwr xml file
    InputStream inputStream = null;
    try {
        Document config = mod.getConfig();
        Element root = config.getDocumentElement();
        // if they defined any xml element
        if (root.getElementsByTagName("dwr").getLength() > 0) {
            // get the dwr-module.xml file that we're appending our code to
            File f = new File(realPath + "/WEB-INF/dwr-modules.xml".replace("/", File.separator));
            // testing if file exists
            if (!f.exists()) {
                // if it does not -> needs to be created
                createDwrModulesXml(realPath);
            }
            inputStream = new FileInputStream(f);
            Document dwrmodulexml = getDWRModuleXML(inputStream, realPath);
            Element outputRoot = dwrmodulexml.getDocumentElement();
            // loop over all of the children of the "dwr" tag
            // and remove all "allow" and "signature" tags that have the
            // same moduleId attr as the module being stopped
            NodeList nodeList = outputRoot.getChildNodes();
            int i = 0;
            while (i < nodeList.getLength()) {
                Node current = nodeList.item(i);
                if ("allow".equals(current.getNodeName()) || "signatures".equals(current.getNodeName())) {
                    NamedNodeMap attrs = current.getAttributes();
                    Node attr = attrs.getNamedItem("moduleId");
                    if (attr != null && moduleId.equals(attr.getNodeValue())) {
                        outputRoot.removeChild(current);
                    } else {
                        i++;
                    }
                } else {
                    i++;
                }
            }
            // save the dwr-modules.xml file.
            OpenmrsUtil.saveDocument(dwrmodulexml, f);
        }
    } catch (FileNotFoundException e) {
        throw new ModuleException(realPath + "/WEB-INF/dwr-modules.xml file doesn't exist.", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException io) {
                log.error("Error while closing input stream", io);
            }
        }
    }
    if (!skipRefresh) {
        refreshWAC(servletContext, false, null);
    }
}
Also used : NamedNodeMap(org.w3c.dom.NamedNodeMap) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) Document(org.w3c.dom.Document) FileInputStream(java.io.FileInputStream) Module(org.openmrs.module.Module) ModuleException(org.openmrs.module.ModuleException) JarFile(java.util.jar.JarFile) File(java.io.File)

Example 3 with ModuleException

use of org.openmrs.module.ModuleException in project openmrs-core by openmrs.

the class WebModuleUtil method loadServlets.

/**
 * This method will find and cache this module's servlets (so that it doesn't have to look them
 * up every time)
 *
 * @param mod
 * @param servletContext the servlet context
 */
public static void loadServlets(Module mod, ServletContext servletContext) {
    Element rootNode = mod.getConfig().getDocumentElement();
    NodeList servletTags = rootNode.getElementsByTagName("servlet");
    for (int i = 0; i < servletTags.getLength(); i++) {
        Node node = servletTags.item(i);
        NodeList childNodes = node.getChildNodes();
        String name = "", className = "";
        for (int j = 0; j < childNodes.getLength(); j++) {
            Node childNode = childNodes.item(j);
            if ("servlet-name".equals(childNode.getNodeName())) {
                if (childNode.getTextContent() != null) {
                    name = childNode.getTextContent().trim();
                }
            } else if ("servlet-class".equals(childNode.getNodeName()) && childNode.getTextContent() != null) {
                className = childNode.getTextContent().trim();
            }
        }
        if (name.length() == 0 || className.length() == 0) {
            log.warn("both 'servlet-name' and 'servlet-class' are required for the 'servlet' tag. Given '" + name + "' and '" + className + "' for module " + mod.getName());
            continue;
        }
        HttpServlet httpServlet;
        try {
            httpServlet = (HttpServlet) ModuleFactory.getModuleClassLoader(mod).loadClass(className).newInstance();
        } catch (ClassNotFoundException e) {
            log.warn("Class not found for servlet " + name + " for module " + mod.getName(), e);
            continue;
        } catch (IllegalAccessException e) {
            log.warn("Class cannot be accessed for servlet " + name + " for module " + mod.getName(), e);
            continue;
        } catch (InstantiationException e) {
            log.warn("Class cannot be instantiated for servlet " + name + " for module " + mod.getName(), e);
            continue;
        }
        try {
            log.debug("Initializing " + name + " servlet. - " + httpServlet + ".");
            ServletConfig servletConfig = new ModuleServlet.SimpleServletConfig(name, servletContext);
            httpServlet.init(servletConfig);
        } catch (Exception e) {
            log.warn("Unable to initialize servlet: ", e);
            throw new ModuleException("Unable to initialize servlet: " + httpServlet, mod.getModuleId(), e);
        }
        // don't allow modules to overwrite servlets of other modules.
        HttpServlet otherServletUsingSameName = moduleServlets.get(name);
        if (otherServletUsingSameName != null) {
            String otherServletName = otherServletUsingSameName.getClass().getPackage() + "." + otherServletUsingSameName.getClass().getName();
            throw new ModuleException("A servlet mapping with name " + name + " is already in use and pointing at: " + otherServletName + " from another installed module and this module is trying" + " to use that same name.  Either the module attempting to be installed (" + mod.getModuleId() + ") will not work or the other one will not.  Please consult the developers of these two" + " modules to sort this out.");
        }
        log.debug("Caching the " + name + " servlet.");
        moduleServlets.put(name, httpServlet);
    }
}
Also used : HttpServlet(javax.servlet.http.HttpServlet) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ServletConfig(javax.servlet.ServletConfig) ServletException(javax.servlet.ServletException) ModuleException(org.openmrs.module.ModuleException) SchedulerException(org.openmrs.scheduler.SchedulerException) FileNotFoundException(java.io.FileNotFoundException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ModuleException(org.openmrs.module.ModuleException)

Example 4 with ModuleException

use of org.openmrs.module.ModuleException in project openmrs-core by openmrs.

the class WebModuleUtil method loadFilters.

/**
 * This method will initialize and store this module's filters
 *
 * @param module - The Module to load and register Filters
 * @param servletContext - The servletContext within which this method is called
 */
public static void loadFilters(Module module, ServletContext servletContext) {
    // Load Filters
    Map<String, Filter> filters = new HashMap<>();
    try {
        for (ModuleFilterDefinition def : ModuleFilterDefinition.retrieveFilterDefinitions(module)) {
            if (moduleFiltersByName.containsKey(def.getFilterName())) {
                throw new ModuleException("A filter with name <" + def.getFilterName() + "> has already been registered.");
            }
            ModuleFilterConfig config = ModuleFilterConfig.getInstance(def, servletContext);
            Filter f = (Filter) ModuleFactory.getModuleClassLoader(module).loadClass(def.getFilterClass()).newInstance();
            f.init(config);
            filters.put(def.getFilterName(), f);
        }
    } catch (ModuleException e) {
        throw e;
    } catch (Exception e) {
        throw new ModuleException("An error occurred initializing Filters for module: " + module.getModuleId(), e);
    }
    moduleFilters.put(module, filters.values());
    moduleFiltersByName.putAll(filters);
    log.debug("Module: " + module.getModuleId() + " successfully loaded " + filters.size() + " filters.");
    // Load Filter Mappings
    List<ModuleFilterMapping> modMappings = ModuleFilterMapping.retrieveFilterMappings(module);
    moduleFilterMappings.addAll(modMappings);
    log.debug("Module: " + module.getModuleId() + " successfully loaded " + modMappings.size() + " filter mappings.");
}
Also used : Filter(javax.servlet.Filter) HashMap(java.util.HashMap) ModuleFilterDefinition(org.openmrs.module.web.filter.ModuleFilterDefinition) ModuleFilterConfig(org.openmrs.module.web.filter.ModuleFilterConfig) ModuleException(org.openmrs.module.ModuleException) ServletException(javax.servlet.ServletException) ModuleException(org.openmrs.module.ModuleException) SchedulerException(org.openmrs.scheduler.SchedulerException) FileNotFoundException(java.io.FileNotFoundException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ModuleFilterMapping(org.openmrs.module.web.filter.ModuleFilterMapping)

Example 5 with ModuleException

use of org.openmrs.module.ModuleException in project openmrs-core by openmrs.

the class ModuleFilterDefinition method retrieveFilterDefinitions.

// Static methods
/**
 * Static method to parse through a Module's configuration file and return a List of
 * ModuleFilterDefinition objects for which there are configuration elements. Expected XML
 * Format:
 *
 * <pre>
 * 	&lt;filter&gt;
 * 		&lt;filter-name&gt;MyFilterName&lt;/filter-name&gt;
 * 		&lt;filter-class&gt;Fully qualified classname of the Filter class&lt;/filter-class&gt;
 * 		&lt;init-param&gt;
 * 			&lt;param-name&gt;filterParameterName1&lt;/param-name&gt;
 * 			&lt;param-value&gt;filterParameterValue1&lt;/param-value&gt;
 * 		&lt;/init-param&gt;
 * 	&lt;/filter&gt;
 * </pre>
 *
 * @param module - The {@link Module} for which to retrieve filter the defined
 *            {@link ModuleFilterDefinition}s
 * @return List of {@link ModuleFilterDefinition}s that have been defined for the passed
 *         {@link Module}
 */
public static List<ModuleFilterDefinition> retrieveFilterDefinitions(Module module) {
    List<ModuleFilterDefinition> filters = new ArrayList<>();
    try {
        Element rootNode = module.getConfig().getDocumentElement();
        NodeList filterNodes = rootNode.getElementsByTagName("filter");
        if (filterNodes.getLength() > 0) {
            for (int i = 0; i < filterNodes.getLength(); i++) {
                ModuleFilterDefinition filter = new ModuleFilterDefinition(module);
                Node node = filterNodes.item(i);
                NodeList configNodes = node.getChildNodes();
                for (int j = 0; j < configNodes.getLength(); j++) {
                    Node configNode = configNodes.item(j);
                    if ("filter-name".equals(configNode.getNodeName())) {
                        filter.setFilterName(configNode.getTextContent().trim());
                    } else if ("filter-class".equals(configNode.getNodeName())) {
                        filter.setFilterClass(configNode.getTextContent().trim());
                    } else if ("init-param".equals(configNode.getNodeName())) {
                        NodeList paramNodes = configNode.getChildNodes();
                        String paramName = "";
                        String paramValue = "";
                        for (int k = 0; k < paramNodes.getLength(); k++) {
                            Node paramNode = paramNodes.item(k);
                            if ("param-name".equals(paramNode.getNodeName())) {
                                paramName = paramNode.getTextContent().trim();
                            } else if ("param-value".equals(paramNode.getNodeName())) {
                                paramValue = paramNode.getTextContent().trim();
                            }
                        }
                        filter.addInitParameter(paramName, paramValue);
                    }
                }
                filters.add(filter);
            }
        }
    } catch (Exception e) {
        throw new ModuleException("Unable to parse filters in module configuration.", e);
    }
    log.debug("Retrieved " + filters.size() + " filters for " + module + ": " + filters);
    return filters;
}
Also used : Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) ModuleException(org.openmrs.module.ModuleException) ModuleException(org.openmrs.module.ModuleException)

Aggregations

ModuleException (org.openmrs.module.ModuleException)8 FileNotFoundException (java.io.FileNotFoundException)6 IOException (java.io.IOException)6 TransformerException (javax.xml.transform.TransformerException)5 Element (org.w3c.dom.Element)5 Node (org.w3c.dom.Node)5 ServletException (javax.servlet.ServletException)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 SchedulerException (org.openmrs.scheduler.SchedulerException)4 NodeList (org.w3c.dom.NodeList)4 Document (org.w3c.dom.Document)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 FileOutputStream (java.io.FileOutputStream)2 InputStream (java.io.InputStream)2 OutputStream (java.io.OutputStream)2 ArrayList (java.util.ArrayList)2 JarFile (java.util.jar.JarFile)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 StringReader (java.io.StringReader)1