Package org.ofbiz.base.container

Examples of org.ofbiz.base.container.ContainerException


    public boolean start() throws ContainerException {
        Debug.logInfo("Start birt container", module);

        // make sure the subclass sets the config name
        if (this.getContainerConfigName() == null) {
            throw new ContainerException("Unknown container config name");
        }
        // get the container config
        ContainerConfig.Container cc = ContainerConfig.getContainer(this.getContainerConfigName(), configFile);
        if (cc == null) {
            throw new ContainerException("No " + this.getContainerConfigName() + " configuration found in container config!");
        }

        config = new EngineConfig();

        // set osgi config
        Map<String, String> osgiConfig = FastMap.newInstance();
        osgiConfig.put("osgi.configuration.area", new File(System.getProperty("ofbiz.home"), "runtime" + File.separator + "tempfiles").getPath());
        config.setOSGiConfig(osgiConfig);

        HashMap<String, Object> context = UtilGenerics.cast(config.getAppContext());

        // set delegator, dispatcher and security objects to report

        delegatorGroupHelperName = ContainerConfig.getPropertyValue(cc, "delegator-group-helper-name", "org.ofbiz");

        // get the delegator
        delegatorName = ContainerConfig.getPropertyValue(cc, "delegator-name", "default");
        delegator = DelegatorFactory.getDelegator(delegatorName);

        // get the dispatcher
        dispatcherName = ContainerConfig.getPropertyValue(cc, "dispatcher-name", "birt-dispatcher");
        dispatcher = GenericDispatcher.getLocalDispatcher(dispatcherName, delegator);

        context.put("delegator", delegator);
        context.put("dispatcher", dispatcher);

        // set classloader for engine
        context.put(EngineConstants.APPCONTEXT_CLASSLOADER_KEY, BirtContainer.class.getClassLoader());
        context.put(EngineConstants.WEBAPP_CLASSPATH_KEY, BirtContainer.class.getClassLoader());

        // set log config to show all level in console
        config.setLogConfig(null, Level.ALL);

        // set engine home
        String reportEnginePath = FileUtil.getFile("component://birt/lib/platform").getPath();
        config.setEngineHome(reportEnginePath);
        config.setBIRTHome(reportEnginePath);

        // set OSGi arguments specific in properties
        String argumentsString = UtilProperties.getPropertyValue(BirtContainer.CONFIG_FILE, "birt.osgi.arguments");
        config.setOSGiArguments(argumentsString.split(","));

        // set platform file context
        config.setPlatformContext(new PlatformFileContext(config));
        config.setAppContext(context);

        // startup platform
        try {
            Debug.logInfo("Startup birt platform", module);
            Platform.startup( config );
        } catch ( BirtException e ) {
            throw new ContainerException(e);
        }

        // create report engine
        Debug.logInfo("Create factory object", module);
        IReportEngineFactory factory = (IReportEngineFactory) Platform
              .createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );
        if (factory == null) {
            throw new ContainerException("can not create birt engine factory");
        }
        Debug.logInfo("Create report engine", module);
        engine = factory.createReportEngine( config );
        String[] supportedFormats = engine.getSupportedFormats();
        String formatList = null;
View Full Code Here


    private void startGeronimo() throws ContainerException {
        // get the container config
        ContainerConfig.Container cc = ContainerConfig.getContainer("geronimo-container", configFile);
        if (cc == null) {
            throw new ContainerException("No geronimo-container configuration found in container config!");
        }

        //String carolPropName = ContainerConfig.getPropertyValue(cc, "jndi-config", "iiop.properties");

        // bind UserTransaction and TransactionManager to JNDI
        try {
            InitialContext ic = new InitialContext();
            // TODO: for some reason this is not working, throwing an error: java.lang.IllegalArgumentException: RegistryContext: object to bind must be Remote, Reference, or Referenceable
            ic.rebind("java:comp/UserTransaction", new GeronimoTransactionManager());
        } catch (Exception e) {
            throw new ContainerException("Unable to bind UserTransaction/TransactionManager to JNDI", e);
        }

        // check JNDI
        try {
            InitialContext ic = new InitialContext();
            Object o = ic.lookup("java:comp/UserTransaction");
            if (o == null) {
                throw new NamingException("Object came back null");
            }
        } catch (NamingException e) {
            throw new ContainerException("Unable to lookup bound objects", e);
        }
        Debug.logInfo("Geronimo is bound to JNDI - java:comp/UserTransaction", module);
    }
View Full Code Here

    private void generateFiles() throws ContainerException {
        if (isGeronimo) {
            if (geronimoHome == null) {
                Debug.logFatal("*** 'GERONIMO_HOME' was not found in your environment. Please set the location of Geronimo into a GERONIMO_HOME env var or as a geronimoHome property in appserver.properties file.", module);
                throw new ContainerException("Error in Geronimo deployment, please check the log");
            }
        }
        File files[] = getTemplates();
        Map<String, Object> dataMap = buildDataMap();

        String user = UtilProperties.getPropertyValue("appserver", "user", "system");
        String password = UtilProperties.getPropertyValue("appserver", "password", "manager");

        boolean offline = UtilProperties.propertyValueEqualsIgnoreCase("appserver", "offline", "true");
        boolean redeploy = UtilProperties.propertyValueEqualsIgnoreCase("appserver", "redeploy", "true");

        String geronimoHostHome = UtilProperties.getPropertyValue("appserver", "geronimoHostHome", null);
        String host = UtilProperties.getPropertyValue("appserver", "host", "");
        String port = UtilProperties.getPropertyValue("appserver", "port", "");
        boolean pauseInGeronimoScript = UtilProperties.propertyValueEqualsIgnoreCase("appserver", "pauseInGeronimoScript", "true");

        int instancesNumber = (int) UtilProperties.getPropertyNumber("appserver", "instancesNumber");
        String instanceNumber = "";

        if (isGeronimo) {
            File geronimoHomeDir = new File (geronimoHome);
            if (!(geronimoHomeDir.isDirectory())) {
                Debug.logFatal("*** " + geronimoHome + " does not exist or is not a directoy. Please set the location of Geronimo into a GERONIMO_HOME env var or as a geronimoHome property in appserver.properties file.", module);
                throw new ContainerException("Error in Geronimo deployment, please check the log");
            }

            if (UtilValidate.isNotEmpty(host) && UtilValidate.isNotEmpty(geronimoHostHome)) {
                geronimoHomeDir = new File ("//" + host + "/" + geronimoHostHome);
                if (!(geronimoHomeDir.isDirectory())) {
                    Debug.logFatal("*** " + geronimoHostHome + " does not exist or is not a directoy. Please set the location of Geronimo on host as a geronimoHostHome property in appserver.properties file.", module);
                    throw new ContainerException("Error in Geronimo deployment, please check the log");
                }
            } else {
                geronimoHostHome = geronimoHome;
            }

            if (redeploy && offline) {
                Debug.logFatal("*** You can't use redeploy with a server offline.", module);
                    throw new ContainerException("Error in Geronimo deployment, please check the log");
                }

            for(int inst = 0; inst <= instancesNumber; inst++) {
                instanceNumber = (inst == 0 ? "" : inst).toString();
                GenerateGeronimoDeployment geronimoDeployment = new GenerateGeronimoDeployment();
                List<String> classpathJars = geronimoDeployment.generate(args[0], geronimoHostHome, instanceNumber);
                if (classpathJars == null) {
                    throw new ContainerException("Error in Geronimo deployment, please check the log");
                }
                dataMap.put("classpathJars", classpathJars);
                dataMap.put("pathSeparatorChar", File.pathSeparatorChar);
                dataMap.put("instanceNumber", instanceNumber);
                //                if (UtilValidate.isNotEmpty(instanceNumber)) {
                //                    List webApps = (List) dataMap.get("webApps");
                //                    for (Object webAppObject: webApps) {
                //                        WebappInfo webAppInfo = (ComponentConfig.WebappInfo) webAppObject;
                //                        String webAppLocation = webAppInfo.getLocation();
                //                        String webXmlLocation = webAppLocation + "/WEB-INF/web.xml";
                //                        if (isFileExistsAndCanWrite(webXmlLocation)) {
                //                            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                //                            DocumentBuilder docBuilder = null;
                //                            try {
                //                                docBuilder = docFactory.newDocumentBuilder();
                //                            } catch (ParserConfigurationException e) {
                //                                throw new ContainerException(e);
                //                            }
                //                            Document doc = null;
                //                            try {
                //                                doc = docBuilder.parse(webXmlLocation);
                //                            } catch (SAXException e) {
                //                                throw new ContainerException(e);
                //                            } catch (IOException e) {
                //                                throw new ContainerException(e);
                //                            }
                //                            Node webApp = doc.getFirstChild();
                //                            Node contextParam = doc.createElement("context-param");
                //                            NamedNodeMap contextParamAttributes = contextParam.getAttributes();
                //
                //                            Attr paramName = doc.createAttribute("param-name");
                //                            paramName.setValue("instanceNumber");
                //                            contextParamAttributes.setNamedItem(paramName);
                //
                //                            Attr paramValue = doc.createAttribute("param-value");
                //                            paramValue.setValue(instanceNumber);
                //                            contextParamAttributes.setNamedItem(paramValue);
                //        //                    Node nodeToAppend = doc.importNode(contextParam, true); this should not be needed
                //        //                    webApp.appendChild(nodeToAppend);
                //
                //        //                    webApp.appendChild(contextParam); this is the line needed but commented for now
                //
                //                            Transformer transformer;
                //                            try {
                //                                transformer = TransformerFactory.newInstance().newTransformer();
                //                            } catch (TransformerConfigurationException e) {
                //                                throw new ContainerException(e);
                //                            } catch (TransformerFactoryConfigurationError e) {
                //                                throw new ContainerException(e);
                //                            }
                //                            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                //
                //                            StreamResult result = new StreamResult(new StringWriter());
                //                            DOMSource source = new DOMSource(doc);
                //                            try {
                //                                transformer.transform(source, result);
                //                            } catch (TransformerException e) {
                //                                throw new ContainerException(e);
                //                            }
                //                            String xmlString = result.getWriter().toString();
                //                            System.out.println(xmlString); //TODO write to file using writeToXmlFile
                //                            break; // Only the 1st web.xml file need to be modified
                //                        } else {
                //                            Debug.logInfo("Unable to change the deployment descriptor : " + webXmlLocation + ". Maybe it does not exist, or is in read only mode ?", module);
                //                        }
                //                    }
                //                }

                //Debug.log("Using Data : " + dataMap, module);
                for (int i = 0; i < files.length; i++) {
                    if (!(files[i].isDirectory() || files[i].isHidden() || files[i].getName().equalsIgnoreCase("geronimo-web.xml"))) {
                        parseTemplate(files[i], dataMap);
                    }
                }

                String ofbizName = "ofbiz" + instanceNumber;
                String separator = File.separator;
                File workingDir = new File(geronimoHome + separator + "bin");
                ProcessBuilder processBuilder = null;
                Process process = null;
                String command = null;
                String commandCommonPart = null;
                if ("\\".equals(separator)) {   //Windows
                    commandCommonPart = "deploy --user " + user +  " --password " +  password;
                } else {                        // Linux
                    commandCommonPart = workingDir + "/deploy.sh --user " + user +  " --password " +  password;
                }
                if (UtilValidate.isNotEmpty(host)) {
                    commandCommonPart += " --host " + host + (UtilValidate.isNotEmpty(port) ? " --port " + port : "");
                }

                if (!redeploy) {
                if ("\\".equals(separator)) { //Windows
                    if (offline) {
                        command = commandCommonPart + " --offline undeploy " + ofbizName;
                    } else {
                        command = commandCommonPart + " undeploy " + ofbizName;
                    }
                        processBuilder = new ProcessBuilder("cmd.exe", "/c", command);
                } else {                        // Linux
                    if (offline) {
                        command = commandCommonPart + " --offline undeploy " + ofbizName;
                    } else {
                        command = commandCommonPart + " undeploy " + ofbizName;
                    }
                        processBuilder = new ProcessBuilder("sh", "-c", command);
                }

                if (pauseInGeronimoScript) {
                        Map<String, String> env = processBuilder.environment();
                    env.put("GERONIMO_BATCH_PAUSE", "on");
                }
                    processBuilder.directory(workingDir);

                try {
                    System.out.println("Currently undeploying " + ofbizName + ", using : <<" + command + ">>, please wait ...");
                        processBuilder.redirectErrorStream(true);
                        process = processBuilder.start();
                        java.io.InputStream is = process.getInputStream();
                    byte[] buf = new byte[2024];
                    int readLen = 0;
                    while ((readLen = is.read(buf,0,buf.length)) != -1) {
                        if ("\\".equals(separator)) {   //Windows
                            System.out.print(new String(buf,0,readLen));
                        } else {
                            System.out.println(new String(buf,0,readLen));
                        }
                    }
                    is.close();
                        process.waitFor();
    //                    System.out.println(process.waitFor());
    //                    System.out.println("exit value" + process.exitValue());
                    Debug.logInfo(ofbizName + " undeployment ended" , module);
                } catch (IOException e) {
                    throw new ContainerException(e);
                } catch (InterruptedException e) {
                    throw new ContainerException(e);
                    } finally {
                        process.destroy();
                    }
                }

                if (redeploy) {
                    if ("\\".equals(separator)) { //Windows
                        command = commandCommonPart + " redeploy " + ofbizHome;
                        processBuilder = new ProcessBuilder("cmd.exe", "/c", command);
                    } else {                      // Linux
                        command = commandCommonPart + " redeploy " + ofbizHome;
                        processBuilder = new ProcessBuilder("sh", "-c", command);
                }

                } else {
                if ("\\".equals(separator)) { //Windows
                    if (offline) {
                            command = commandCommonPart + " --offline deploy --inPlace " + ofbizHome;
                    } else {
                            command = commandCommonPart + " deploy --inPlace " + ofbizHome;
                    }
                        processBuilder = new ProcessBuilder("cmd.exe", "/c", command);
                } else {                      // Linux
                    if (offline) {
                            command = commandCommonPart + " --offline deploy --inPlace " + ofbizHome;
                    } else {
                            command = commandCommonPart + " deploy --inPlace " + ofbizHome;
                        }
                        processBuilder = new ProcessBuilder("sh", "-c", command);
                    }
                }

                if (pauseInGeronimoScript) {
                    Map<String, String> env = processBuilder.environment();
                    env.put("GERONIMO_BATCH_PAUSE", "on");
                }
                processBuilder.directory(workingDir);

                try {
                    System.out.println("Currently deploying " + ofbizName + ", using : <<" + command + ">>, please wait ...");
                    processBuilder.redirectErrorStream(true);
                    process = processBuilder.start();
                    java.io.InputStream is = process.getInputStream();
                    byte[] buf = new byte[2024];
                    int readLen = 0;
                    while ((readLen = is.read(buf,0,buf.length)) != -1) {
                        if ("\\".equals(separator)) {   //Windows
                            System.out.print(new String(buf,0,readLen));
                        } else {
                            System.out.println(new String(buf,0,readLen));
                        }
                    }
                    is.close();
                    process.waitFor();
//                    System.out.println(process.waitFor());
//                    System.out.println("exit value" + process.exitValue());
                    Debug.logInfo(ofbizName + " deployment ended" , module);
                } catch (IOException e) {
                    throw new ContainerException(e);
                } catch (InterruptedException e) {
                    throw new ContainerException(e);
                } finally {
                    process.destroy();
                }
            }
        } else {
View Full Code Here

        }
    }

    private File[] getTemplates() throws ContainerException {
        if (args == null) {
            throw new ContainerException("Invalid application server type argument passed");
        }

        String templateLocation = args[0];
        if (templateLocation == null) {
            throw new ContainerException("Unable to locate Application Server template directory");
        }

        File parentDir = new File(ofbizHome + source + templateLocation);
        if (!parentDir.exists() || !parentDir.isDirectory()) {
            throw new ContainerException("Template location - " + templateLocation + " does not exist!");
        }

        return parentDir.listFiles();
    }
View Full Code Here

        }
        File targetDir = new File(targetDirectory);
        if (!targetDir.exists()) {
            boolean created = targetDir.mkdirs();
            if (!created) {
                throw new ContainerException("Unable to create target directory - " + targetDirectory);
            }
        }

        if (!targetDirectory.endsWith("/")) {
            targetDirectory = targetDirectory + "/";
View Full Code Here

        Debug.log("Parsing template : " + templateFile.getAbsolutePath(), module);
        Reader reader = null;
        try {
            reader = new InputStreamReader(new FileInputStream(templateFile));
        } catch (FileNotFoundException e) {
            throw new ContainerException(e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new ContainerException(e);
                }
            }
        }

        // create the target file/directory
        String targetDirectory = getTargetDirectory();

        // write the template to the target directory
        Writer writer = null;
        try {
            writer = new FileWriter(targetDirectory + templateFile.getName());
            try {
                FreeMarkerWorker.renderTemplate(UtilURL.fromFilename(templateFile.getAbsolutePath()).toExternalForm(), dataMap, writer);
            } catch (Exception e) {
                throw new ContainerException(e);
            }
        } catch (IOException e) {
            throw new ContainerException(e);
        } finally {
            try {
                if (writer != null) {
                    writer.flush();
                    writer.close();
                }
            } catch (IOException e) {
                throw new ContainerException(e);
            }
        }

    }
View Full Code Here

    }

    public boolean start() throws ContainerException {
        ContainerConfig.Container cc = ContainerConfig.getContainer("jpos.device-container", configFile);
        if (cc == null) {
            throw new ContainerException("No jpos.device-container configuration found in container config!");
        }

        // load the devices
        try {
            DeviceLoader.load(cc.properties);
        } catch (GeneralException e) {
            Debug.logInfo("******************************************************", module);
            Debug.logInfo("Please verify that your receipt printer is connected !", module);
            Debug.logInfo("******************************************************", module);
            throw new ContainerException(e);
        }

        return true;
    }
View Full Code Here

        GenericValue facility = null;

        // get the facility id
        String facilityId = ContainerConfig.getPropertyValue(cc, "facility-id", null);
        if (UtilValidate.isEmpty(facilityId)) {
            throw new ContainerException("No facility-id value set in pos-container!");
        } else {
            try {
                facility = session.getDelegator().findByPrimaryKey("Facility", UtilMisc.toMap("facilityId", facilityId));
            } catch (GenericEntityException e) {
                throw new ContainerException("Invalid facilityId : " + facilityId);
            }
        }

        // verify the facility exists
        if (facility == null) {
            throw new ContainerException("Invalid facility; facility ID not found [" + facilityId + "]");
        }
        session.setAttribute("facilityId", facilityId);
        session.setAttribute("facility", facility);

        // get the product store id
        String productStoreId = facility.getString("productStoreId");
        if (UtilValidate.isEmpty(productStoreId)) {
            throw new ContainerException("No productStoreId set on facility [" + facilityId + "]!");
        } else {
            productStore = ProductStoreWorker.getProductStore(productStoreId, session.getDelegator());
            if (productStore == null) {
                throw new ContainerException("Invalid productStoreId : " + productStoreId);
            }
        }
        session.setAttribute("productStoreId", productStoreId);
        session.setAttribute("productStore", productStore);

        // get the store locale
        String localeStr = ContainerConfig.getPropertyValue(cc, "locale", null);
        if (UtilValidate.isEmpty(localeStr)) {
            localeStr = productStore.getString("defaultLocaleString");
        }
        if (UtilValidate.isEmpty(localeStr)) {
            throw new ContainerException("Invalid Locale for POS!");
        }
        Locale locale = UtilMisc.parseLocale(localeStr);
        session.setAttribute("locale", locale);

        // get the store currency
        String currencyStr = ContainerConfig.getPropertyValue(cc, "currency", null);
        if (UtilValidate.isEmpty(currencyStr)) {
            currencyStr = productStore.getString("defaultCurrencyUomId");
        }
        if (UtilValidate.isEmpty(currencyStr)) {
            throw new ContainerException("Invalid Currency for POS!");
        }
        session.setAttribute("currency", currencyStr);
    }
View Full Code Here

        }

        // get the tests to run
        JunitSuiteWrapper jsWrapper = new JunitSuiteWrapper(component, suiteName, testCase);
        if (jsWrapper.getAllTestList().size() == 0) {
            throw new ContainerException("No tests found (" + component + " / " + suiteName + " / " + testCase + ")");
        }

        boolean failedRun = false;
        for (ModelTestSuite modelSuite: jsWrapper.getModelTestSuites()) {
            Delegator testDelegator = modelSuite.getDelegator();
            TestSuite suite = modelSuite.makeTestSuite();
            JUnitTest test = new JUnitTest();
            test.setName(suite.getName());

            // create the XML logger
            JunitXmlListener xml;
            try {
                xml = new JunitXmlListener(new FileOutputStream(logDir + suite.getName() + ".xml"));
            } catch (FileNotFoundException e) {
                throw new ContainerException(e);
            }

            // per-suite results
            TestResult results = new TestResult();
            results.addListener(new JunitListener());
            results.addListener(xml);

            // add the suite to the xml listener
            xml.startTestSuite(test);
            // run the tests
            suite.run(results);
            test.setCounts(results.runCount(), results.failureCount(), results.errorCount());
            // rollback all entity operations performed by the delegator
            testDelegator.rollback();
            xml.endTestSuite(test);

            if (!results.wasSuccessful()) {
                failedRun = true;
            }

            // display the results
            Debug.log("[JUNIT] Results for test suite: " + suite.getName());
            Debug.log("[JUNIT] Pass: " + results.wasSuccessful() + " | # Tests: " + results.runCount() + " | # Failed: " +
                    results.failureCount() + " # Errors: " + results.errorCount(), module);
            if (Debug.importantOn()) {
                Debug.log("[JUNIT] ----------------------------- ERRORS ----------------------------- [JUNIT]", module);
                Enumeration<?> err = results.errors();
                if (!err.hasMoreElements()) {
                    Debug.log("None");
                } else {
                    while (err.hasMoreElements()) {
                        Object error = err.nextElement();
                        Debug.log("--> " + error, module);
                        if (error instanceof TestFailure) {
                            Debug.log(((TestFailure) error).trace());
                        }
                    }
                }
                Debug.log("[JUNIT] ------------------------------------------------------------------ [JUNIT]", module);
                Debug.log("[JUNIT] ---------------------------- FAILURES ---------------------------- [JUNIT]", module);
                Enumeration<?> fail = results.failures();
                if (!fail.hasMoreElements()) {
                    Debug.log("None");
                } else {
                    while (fail.hasMoreElements()) {
                        Object failure = fail.nextElement();
                        Debug.log("--> " + failure, module);
                        if (failure instanceof TestFailure) {
                            Debug.log(((TestFailure) failure).trace());
                        }
                    }
                }
                Debug.log("[JUNIT] ------------------------------------------------------------------ [JUNIT]", module);
            }
        }

        if (failedRun) {
            throw new ContainerException("Test run was unsuccessful");
        }
        return true;
    }
View Full Code Here

                try {
                    server.start();
                    server.join();
                } catch (Exception e) {
                    Debug.logError(e, "Jetty Server Exception", module);
                    throw new ContainerException(e);
                }
            }
        }
        return true;
    }
View Full Code Here

TOP

Related Classes of org.ofbiz.base.container.ContainerException

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.