Example usage for javax.servlet ServletContext setAttribute

List of usage examples for javax.servlet ServletContext setAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext setAttribute.

Prototype

public void setAttribute(String name, Object object);

Source Link

Document

Binds an object to a given attribute name in this ServletContext.

Usage

From source file:com.jsmartframework.web.manager.BeanHandler.java

private Object instantiateBean(String name, Map<String, String> expressions) throws Exception {
    Object bean = null;/*w  w  w.  j av  a  2s. c  o m*/
    ServletContext context = WebContext.getApplication();
    HttpSession session = WebContext.getSession();
    HttpServletRequest request = WebContext.getRequest();

    if (request.getAttribute(name) != null) {
        bean = request.getAttribute(name);
        executeInjection(bean);
        return bean;
    }

    synchronized (session) {
        if (session.getAttribute(name) != null) {
            bean = session.getAttribute(name);
            executeInjection(bean);
            return bean;
        }
    }

    if (context.getAttribute(name) != null) {
        bean = context.getAttribute(name);
        executeInjection(bean);
        return bean;
    }

    if (webBeans.containsKey(name)) {
        Class<?> clazz = webBeans.get(name);
        bean = clazz.newInstance();

        WebBean webBean = clazz.getAnnotation(WebBean.class);
        if (webBean.scope().equals(ScopeType.REQUEST)) {
            request.setAttribute(name, bean);

        } else if (webBean.scope().equals(ScopeType.SESSION)) {
            synchronized (session) {
                session.setAttribute(name, bean);
            }
        } else if (webBean.scope().equals(ScopeType.APPLICATION)) {
            context.setAttribute(name, bean);

        } else {
            return null;
        }

        executeInjection(bean);
        executePreSet(name, bean, expressions);
        executePostConstruct(bean);
    }
    return bean;
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadFormAdapters(ServletContext servletContext) throws Exception {

    int adapterCount = 0;

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> formConstructors = new HashMap<String, Constructor>();

    // create a JSON Array object which will hold json for all of the available security adapters
    JSONArray jsonAdapters = new JSONArray();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/forms/"));

    // create a filter for finding .formadapter.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".formadapter.xml");
        }//from w  w  w  . ja  v a 2  s.c  om
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/formAdapter.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // read the xml into a string
        String xml = Strings.getString(xmlFile);

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonFormAdapter = org.json.XML.toJSONObject(xml).getJSONObject("formAdapter");

        // get the type from the json
        String type = jsonFormAdapter.getString("type");
        // get the class name from the json
        String className = jsonFormAdapter.getString("class");
        // get the class 
        Class classClass = Class.forName(className);
        // check the class extends com.rapid.security.SecurityAdapter
        if (!Classes.extendsClass(classClass, com.rapid.forms.FormAdapter.class))
            throw new Exception(type + " form adapter class " + classClass.getCanonicalName()
                    + " must extend com.rapid.forms.FormsAdapter");
        // check this type is unique
        if (formConstructors.get(type) != null)
            throw new Exception(type + " form adapter already loaded. Type names must be unique.");
        // add to constructors hashmap referenced by type
        formConstructors.put(type, classClass.getConstructor(ServletContext.class, Application.class));

        // add to our collection
        jsonAdapters.put(jsonFormAdapter);

        // increment the count
        adapterCount++;

    }

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonFormAdapters", jsonAdapters);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("formConstructors", formConstructors);

    _logger.info(adapterCount + " form adapters loaded in .formAdapter.xml files");

    return adapterCount;

}

From source file:org.wso2.carbon.ui.internal.CarbonUIServiceComponent.java

/**
 * reads product.xml contained within styles bundle of a product.
 * product.xml contains properties like userforum, mailing list,etc.. which are
 * specific to the product./*  w  w w. j a v  a  2  s  . c o  m*/
 *
 * @param jspServletContext
 * @throws IOException
 * @throws XMLStreamException
 * @throws FactoryConfigurationError
 */
private void readProductXML(ServletContext jspServletContext, UIBundleDeployer uiBundleDeployer)
        throws IOException, XMLStreamException {
    Enumeration<URL> e = bundleContext.getBundle().findEntries("META-INF", PRODUCT_XML, true);
    // it is possible to make the styles bundle a UIBundle. But in that case we have to get the
    // product.xml file using BundleBasedUIResourceFinder. However product.xml file is not a UI
    // resource. rather it is  a config file. Hence I'm making this a fragment bundle.
    // actually styles bundle should be a fragment of carbon UI. -- Pradeep
    /*Bundle stylesBundle = ((BundleBasedUIResourceProvider) uiBundleDeployer.getBundleBasedUIResourcePrvider()).getBundle(CarbonConstants.PRODUCT_STYLES_CONTEXT);
    if (stylesBundle != null) {
    e = stylesBundle.findEntries("META-INF", PRODUCT_XML, true);
    }*/
    if (e != null) {
        URL url = (URL) e.nextElement();
        InputStream inputStream = url.openStream();
        XMLStreamReader streamReader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        StAXOMBuilder builder = new StAXOMBuilder(streamReader);
        OMElement document = builder.getDocumentElement();
        OMElement propsEle = document.getFirstChildWithName(new QName(WSO2CARBON_NS, PRODUCT_XML_PROPERTIES));
        if (propsEle != null) {
            Iterator<OMElement> properties = propsEle
                    .getChildrenWithName(new QName(WSO2CARBON_NS, PRODUCT_XML_PROPERTY));
            while (properties.hasNext()) {
                OMElement property = properties.next();
                String propertyName = property.getAttributeValue(new QName("name"));
                String value = property.getText();
                if (log.isDebugEnabled()) {
                    log.debug(PRODUCT_XML + ": " + propertyName + "=" + value);
                }
                //process collapsed menus in a different manner than other properties
                if ("collapsedmenus".equals(propertyName)) {
                    ArrayList<String> collapsedMenuItems = new ArrayList<String>();
                    if (value != null && value.indexOf(',') > -1) {
                        //multiple menu items provided.Tokenize & add iteratively
                        StringTokenizer st = new StringTokenizer(value, ",");
                        while (st.hasMoreTokens()) {
                            collapsedMenuItems.add(st.nextToken());
                        }
                    } else {
                        //single menu item specified.add this
                        collapsedMenuItems.add(value);
                    }
                    jspServletContext.setAttribute(PRODUCT_XML_WSO2CARBON + propertyName, collapsedMenuItems);

                    /*
                    Sometimes the values loaded to the jspServletContext is not available.
                    i.e. when the request is sent to /carbon
                    it works only if teh request takes the patern such as /carbon/admin/index.jsp
                    in the case of /carbon the params are read from utils hashmap which is saved at this point.
                     */
                    CarbonUIUtil.setProductParam(PRODUCT_XML_WSO2CARBON + propertyName, collapsedMenuItems);
                } else {
                    jspServletContext.setAttribute(PRODUCT_XML_WSO2CARBON + propertyName, value);
                    CarbonUIUtil.setProductParam(PRODUCT_XML_WSO2CARBON + propertyName, value);
                }
            }
        }
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadSecurityAdapters(ServletContext servletContext) throws Exception {

    int adapterCount = 0;

    // retain our class constructors in a hashtable - this speeds up initialisation
    HashMap<String, Constructor> securityConstructors = new HashMap<String, Constructor>();

    // create a JSON Array object which will hold json for all of the available security adapters
    JSONArray jsonSecurityAdapters = new JSONArray();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/security/"));

    // create a filter for finding .securityadapter.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".securityadapter.xml");
        }/*from  ww w .j  a va  2s .c  o  m*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/securityAdapter.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // read the xml into a string
        String xml = Strings.getString(xmlFile);

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // convert the string into JSON
        JSONObject jsonSecurityAdapter = org.json.XML.toJSONObject(xml).getJSONObject("securityAdapter");

        // get the type from the json
        String type = jsonSecurityAdapter.getString("type");
        // get the class name from the json
        String className = jsonSecurityAdapter.getString("class");
        // get the class 
        Class classClass = Class.forName(className);
        // check the class extends com.rapid.security.SecurityAdapter
        if (!Classes.extendsClass(classClass, com.rapid.security.SecurityAdapter.class))
            throw new Exception(type + " security adapter class " + classClass.getCanonicalName()
                    + " must extend com.rapid.security.SecurityAdapter");
        // check this type is unique
        if (securityConstructors.get(type) != null)
            throw new Exception(type + " security adapter already loaded. Type names must be unique.");
        // add to constructors hashmap referenced by type
        securityConstructors.put(type, classClass.getConstructor(ServletContext.class, Application.class));

        // add to our collection
        jsonSecurityAdapters.put(jsonSecurityAdapter);

        // increment the count
        adapterCount++;

    }

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonSecurityAdapters", jsonSecurityAdapters);

    // put the constructors hashmapin a context attribute (this is available via the getContructor method in RapidHttpServlet)
    servletContext.setAttribute("securityConstructors", securityConstructors);

    _logger.info(adapterCount + " security adapters loaded in .securityAdapter.xml files");

    return adapterCount;

}

From source file:org.red5.server.tomcat.TomcatVHostLoader.java

/**
 * Starts a web application and its red5 (spring) component. This is basically a stripped down
 * version of init().//from ww  w .  ja  va2 s .c  om
 * 
 * @return true on success
 */
@SuppressWarnings("cast")
public boolean startWebApplication(String applicationName) {
    boolean result = false;
    log.info("Starting Tomcat virtual host - Web application");

    log.info("Virtual host root: {}", webappRoot);

    log.info("Virtual host context id: {}", defaultApplicationContextId);

    // application directory
    String contextName = '/' + applicationName;

    Container cont = null;

    //check if the context already exists for the host
    if ((cont = host.findChild(contextName)) == null) {
        log.debug("Context did not exist in host");
        String webappContextDir = FileUtil.formatPath(webappRoot, applicationName);
        //prepend slash
        Context ctx = addContext(contextName, webappContextDir);
        //set the newly created context as the current container
        cont = ctx;
    } else {
        log.debug("Context already exists in host");
    }

    try {
        ServletContext servletContext = ((Context) cont).getServletContext();
        log.debug("Context initialized: {}", servletContext.getContextPath());

        String prefix = servletContext.getRealPath("/");
        log.debug("Path: {}", prefix);

        Loader cldr = cont.getLoader();
        log.debug("Loader type: {}", cldr.getClass().getName());
        ClassLoader webClassLoader = cldr.getClassLoader();
        log.debug("Webapp classloader: {}", webClassLoader);
        //create a spring web application context
        XmlWebApplicationContext appctx = new XmlWebApplicationContext();
        appctx.setClassLoader(webClassLoader);
        appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" });
        //check for red5 context bean
        if (applicationContext.containsBean(defaultApplicationContextId)) {
            appctx.setParent((ApplicationContext) applicationContext.getBean(defaultApplicationContextId));
        } else {
            log.warn("{} bean was not found in context: {}", defaultApplicationContextId,
                    applicationContext.getDisplayName());
            //lookup context loader and attempt to get what we need from it
            if (applicationContext.containsBean("context.loader")) {
                ContextLoader contextLoader = (ContextLoader) applicationContext.getBean("context.loader");
                appctx.setParent(contextLoader.getContext(defaultApplicationContextId));
            } else {
                log.debug("Context loader was not found, trying JMX");
                MBeanServer mbs = JMXFactory.getMBeanServer();
                //get the ContextLoader from jmx
                ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader");
                ContextLoaderMBean proxy = null;
                if (mbs.isRegistered(oName)) {
                    proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName,
                            ContextLoaderMBean.class, true);
                    log.debug("Context loader was found");
                    appctx.setParent(proxy.getContext(defaultApplicationContextId));
                } else {
                    log.warn("Context loader was not found");
                }
            }
        }
        if (log.isDebugEnabled()) {
            if (appctx.getParent() != null) {
                log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
            }
        }
        //
        appctx.setServletContext(servletContext);
        //set the root webapp ctx attr on the each servlet context so spring can find it later               
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
        appctx.refresh();

        result = true;
    } catch (Throwable t) {
        log.error("Error setting up context: {}", applicationName, t);
        if (log.isDebugEnabled()) {
            t.printStackTrace();
        }
    }

    return result;
}

From source file:hudson.model.Hudson.java

/**
 * Reloads the configuration.//from w ww .  j  av a 2  s  .  c o m
 */
public synchronized void doReload(StaplerRequest req, StaplerResponse rsp) throws IOException {
    checkPermission(ADMINISTER);

    // engage "loading ..." UI and then run the actual task in a separate thread
    final ServletContext context = req.getServletContext();
    context.setAttribute("app", new HudsonIsLoading());

    rsp.sendRedirect2(req.getContextPath() + "/");

    new Thread("Hudson config reload thread") {
        public void run() {
            try {
                load();
                User.reload();
                context.setAttribute("app", Hudson.this);
            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, "Failed to reload Hudson config", e);
            }
        }
    }.start();
}

From source file:org.entando.entando.plugins.jpcomponentinstaller.aps.system.services.installer.DefaultComponentInstaller.java

private void installPlugin(AvailableArtifact availableArtifact, String version, InputStream is)
        throws Exception {
    ServletContext servletContext = ((ConfigurableWebApplicationContext) this._applicationContext)
            .getServletContext();/*  w ww . j a  va 2s .co  m*/
    String filename = availableArtifact.getGroupId() + "_" + availableArtifact.getArtifactId() + "_" + version
            + ".war";
    String artifactName = availableArtifact.getArtifactId();
    String appRootPath = servletContext.getRealPath("/");
    File destDir = new File(appRootPath);
    String tempDirPath = appRootPath + "componentinstaller" + File.separator + artifactName;
    File artifactFile = new File(appRootPath + "componentinstaller" + File.separator + filename);

    FileUtils.copyInputStreamToFile(is, artifactFile);
    this.extractArchiveFile(artifactFile, tempDirPath);
    File artifactFileRootDir = new File(
            artifactFile.getParentFile().getAbsolutePath() + File.separator + artifactName);

    List<File> tilesFiles = (List<File>) FileUtils.listFiles(artifactFileRootDir,
            FileFilterUtils.suffixFileFilter("-tiles.xml"), FileFilterUtils.trueFileFilter());
    if (tilesFiles == null) {
        tilesFiles = new ArrayList<File>();
    }

    File tempArtifactRootDir = this.extractAllJars(destDir, artifactName);
    List<File> pluginSqlFiles = (List<File>) FileUtils.listFiles(tempArtifactRootDir, new String[] { "sql" },
            true);
    List<File> pluginXmlFiles = (List<File>) FileUtils.listFiles(tempArtifactRootDir, new String[] { "xml" },
            true);

    List<File> mainAppJarLibraries = (List<File>) FileUtils.listFiles(
            new File(destDir.getAbsolutePath() + File.separator + "WEB-INF" + File.separator + "lib"),
            new String[] { "jar" }, true);
    List<File> pluginJarLibraries = (List<File>) FileUtils.listFiles(artifactFileRootDir,
            new String[] { "jar" }, true);
    pluginJarLibraries = filterOutDuplicateLibraries(mainAppJarLibraries, pluginJarLibraries);

    FileUtils.copyDirectory(artifactFileRootDir, destDir);

    List<File> allFiles = new ArrayList<File>();
    File systemParamsFile = FileUtils.getFile(destDir + File.separator + "WEB-INF" + File.separator + "conf",
            "systemParams.properties");
    allFiles.add(systemParamsFile);
    allFiles.addAll(pluginJarLibraries);
    allFiles.addAll(pluginSqlFiles);
    allFiles.addAll(pluginXmlFiles);
    //The classloader's content is stored in servlet context and 
    //updated every time so the classloader will eventually contain 
    //the classes and resources of all the installed plugins
    List<URL> urlList = (List<URL>) servletContext.getAttribute("pluginInstallerURLList");
    if (urlList == null) {
        urlList = new ArrayList<URL>();
        servletContext.setAttribute("pluginInstallerURLList", urlList);
    }
    Set<File> jarSet = (Set<File>) servletContext.getAttribute("pluginInstallerJarSet");
    if (jarSet == null) {
        jarSet = new HashSet<File>();
        servletContext.setAttribute("pluginInstallerJarSet", jarSet);
    }
    jarSet.addAll(pluginJarLibraries);
    URLClassLoader cl = getURLClassLoader(urlList, allFiles.toArray(new File[0]), servletContext);
    loadClasses(jarSet.toArray(new File[0]), cl);
    servletContext.setAttribute("componentInstallerClassLoader", cl);
    ComponentManager.setComponentInstallerClassLoader(cl);

    //load plugin and dependencies contexts 
    File componentFile = this.getFileFromArtifactJar(tempArtifactRootDir, "component.xml");
    String componentToInstallName = this.getComponentName(componentFile);

    InitializerManager initializerManager = (InitializerManager) this._applicationContext
            .getBean("InitializerManager");
    initializerManager.reloadCurrentReport();
    SystemInstallationReport currentReport = initializerManager.getCurrentReport();
    if (null != currentReport.getComponentReport(componentToInstallName, false)) {
        currentReport.removeComponentReport(componentToInstallName);
        this.saveReport(currentReport);
        initializerManager.reloadCurrentReport();
    }

    List<String> components = this.getAllComponents(artifactFileRootDir);

    Properties properties = new Properties();
    properties.load(new FileInputStream(systemParamsFile));

    for (String componentName : components) {
        List<String> configLocs = new ArrayList<String>();
        InitializerManager currenInitializerManager = (InitializerManager) _applicationContext
                .getBean("InitializerManager");
        currentReport = currenInitializerManager.getCurrentReport();
        ComponentInstallationReport cir = currentReport.getComponentReport(componentName, false);
        if (null != cir && cir.getStatus().equals(SystemInstallationReport.Status.UNINSTALLED)) {
            currentReport.removeComponentReport(componentName);
            this.saveReport(currentReport);
            currenInitializerManager.reloadCurrentReport();
        }

        configLocs = this.getConfigPaths(artifactFileRootDir, componentName);
        if (configLocs.isEmpty()) {
            continue;
        }

        ClassPathXmlApplicationContext newContext = (ClassPathXmlApplicationContext) loadContext(
                (String[]) configLocs.toArray(new String[0]), cl, componentName, properties);

        this.reloadActionsDefinitions(newContext);
        this.reloadResourcsBundles(newContext, servletContext);
        TilesContainer container = TilesAccess.getContainer(servletContext);
        this.reloadTilesDefinitions(tilesFiles, container);

        currenInitializerManager.reloadCurrentReport();
        ComponentManager componentManager = (ComponentManager) _applicationContext.getBean("ComponentManager");
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            Thread.currentThread().setContextClassLoader(newContext.getClassLoader());
            componentManager.refresh();
        } catch (Exception e) {
            throw e;
        } finally {
            Thread.currentThread().setContextClassLoader(currentClassLoader);
        }
    }
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadDatabaseDrivers(ServletContext servletContext) throws Exception {

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/databaseDrivers.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // read the xml into a string
    String xml = Strings//from   www .j  a  v a2  s. c o  m
            .getString(new File(servletContext.getRealPath("/WEB-INF/database/") + "/databaseDrivers.xml"));

    // validate the control xml file against the schema
    validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

    // convert the xml string into JSON
    JSONObject jsonDatabaseDriverCollection = org.json.XML.toJSONObject(xml).getJSONObject("databaseDrivers");

    // prepare the array we are going to popoulate
    JSONArray jsonDatabaseDrivers = new JSONArray();

    JSONObject jsonDatabaseDriver;
    int index = 0;
    int count = 0;

    if (jsonDatabaseDriverCollection.optJSONArray("databaseDriver") == null) {
        jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONObject("databaseDriver");
    } else {
        jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONArray("databaseDriver").getJSONObject(index);
        count = jsonDatabaseDriverCollection.getJSONArray("databaseDriver").length();
    }

    do {

        _logger.info("Registering database driver " + jsonDatabaseDriver.getString("name") + " using "
                + jsonDatabaseDriver.getString("class"));

        try {

            // check this type does not already exist
            for (int i = 0; i < jsonDatabaseDrivers.length(); i++) {
                if (jsonDatabaseDriver.getString("name")
                        .equals(jsonDatabaseDrivers.getJSONObject(i).getString("name")))
                    throw new Exception(" database driver type is loaded already. Type names must be unique");
            }

            // get  the class name
            String className = jsonDatabaseDriver.getString("class");
            // get the current thread class loader (this should log better if there are any issues)
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            // check we got a class loader
            if (classLoader == null) {
                // register the class the old fashioned way so the DriverManager can find it
                Class.forName(className);
            } else {
                // register the class on this thread so we can catch any errors
                Class.forName(className, true, classLoader);
            }

            // add the jsonControl to our array
            jsonDatabaseDrivers.put(jsonDatabaseDriver);

        } catch (Exception ex) {

            _logger.error("Error registering database driver : " + ex.getMessage(), ex);

        }

        // inc the count of controls in this file
        index++;

        // get the next one
        if (index < count)
            jsonDatabaseDriver = jsonDatabaseDriverCollection.getJSONArray("databaseDriver")
                    .getJSONObject(index);

    } while (index < count);

    // put the jsonControls in a context attribute (this is available via the getJsonActions method in RapidHttpServlet)
    servletContext.setAttribute("jsonDatabaseDrivers", jsonDatabaseDrivers);

    _logger.info(index + " database drivers loaded from databaseDrivers.xml file");

    return index;

}

From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java

/**
 * Execute metadata query/*w ww.  java  2s . c  o  m*/
 */
private void executeMetadata(Session session, String qs, boolean showSql, ServletContext sc,
        HttpServletRequest request, HttpServletResponse response)
        throws DatabaseException, ServletException, IOException, HibernateException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    StringTokenizer st = new StringTokenizer(qs, "\n\r");
    List<DbQueryGlobalResult> globalResults = new ArrayList<DbQueryGlobalResult>();

    // For each query line
    while (st.hasMoreTokens()) {
        String mds = st.nextToken();
        String[] parts = mds.split("\\|");

        if (parts.length > 1) {
            String hql = null;

            if (parts[0].toUpperCase().equals("SENTENCE")) {
                if (parts.length > 2) {
                    List<String> tables = Arrays.asList(parts[1].split(","));
                    hql = DatabaseMetadataUtils.replaceVirtual(tables, parts[2]);
                    log.debug("Metadata SENTENCE: {}", hql);
                    globalResults.add(executeHQL(session, hql, showSql, tables));
                }
            } else if (parts[0].toUpperCase().equals("SELECT")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], null);
                }

                log.debug("Metadata SELECT: {}", hql);
                globalResults.add(executeHQL(session, hql, showSql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("UPDATE")) {
                if (parts.length > 3) {
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], parts[3]);
                } else if (parts.length > 2) {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], null);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], null, null);
                }

                log.debug("Metadata UPDATE: {}", hql);
                globalResults.add(executeHQL(session, hql, showSql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("DELETE")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], null);
                }

                log.debug("Metadata DELETE: {}", hql);
                globalResults.add(executeHQL(session, hql, showSql, Arrays.asList(parts[1])));
            } else {
                throw new DatabaseException("Error in metadata action");
            }
        } else {
            throw new DatabaseException("Error in metadata sentence parameters");
        }
    }

    sc.setAttribute("exception", null);
    sc.setAttribute("showSql", showSql);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}

From source file:com.ikon.servlet.admin.DatabaseQueryServlet.java

/**
 * Execute metadata query//from  www .j ava2  s  . com
 */
private void executeMetadata(Session session, String qs, ServletContext sc, HttpServletRequest request,
        HttpServletResponse response) throws DatabaseException, ServletException, IOException,
        HibernateException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    StringTokenizer st = new StringTokenizer(qs, "\n\r");
    List<GlobalResult> globalResults = new ArrayList<DatabaseQueryServlet.GlobalResult>();

    // For each query line
    while (st.hasMoreTokens()) {
        String mds = st.nextToken();
        String[] parts = mds.split("\\|");

        if (parts.length > 1) {
            String hql = null;

            if (parts[0].toUpperCase().equals("SENTENCE")) {
                if (parts.length > 2) {
                    List<String> tables = Arrays.asList(parts[1].split(","));
                    hql = DatabaseMetadataUtils.replaceVirtual(tables, parts[2]);
                    log.debug("Metadata SENTENCE: {}", hql);
                    globalResults.add(executeHQL(session, hql, tables));
                }
            } else if (parts[0].toUpperCase().equals("SELECT")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildQuery(parts[1], null);
                }

                log.debug("Metadata SELECT: {}", hql);
                globalResults.add(executeHQL(session, hql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("UPDATE")) {
                if (parts.length > 3) {
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], parts[3]);
                } else if (parts.length > 2) {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], parts[2], null);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildUpdate(parts[1], null, null);
                }

                log.debug("Metadata UPDATE: {}", hql);
                globalResults.add(executeHQL(session, hql, Arrays.asList(parts[1])));
            } else if (parts[0].toUpperCase().equals("DELETE")) {
                if (parts.length > 2) {
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], parts[2]);
                } else {
                    // Filter parameter is optional
                    hql = DatabaseMetadataUtils.buildDelete(parts[1], null);
                }

                log.debug("Metadata DELETE: {}", hql);
                globalResults.add(executeHQL(session, hql, Arrays.asList(parts[1])));
            } else {
                throw new DatabaseException("Error in metadata action");
            }
        } else {
            throw new DatabaseException("Error in metadata sentence parameters");
        }
    }

    //sc.setAttribute("sql", HibernateUtil.toSql(qs));
    sc.setAttribute("exception", null);
    sc.setAttribute("globalResults", globalResults);
    sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response);
}