How to run a cli script in pimcore - pimcore

till Now I have been placing all my code within pimcore\cli\startup.php and it's run fine but when I'am trying in another way I getting error like
Class 'Website\ObjectExporter' not found in C:\xampp\htdocs\pimcore\website\var\cli\export-objects.php on line 7
How to run code in this way
For example create an ObjectExporter.php under /website/lib/Website folder with this content:
<?php
namespace Website;
class ObjectExporter
{
public function exportObjects()
{
// Your code
}
}
Then you can either instantiate this class in your controller action or in a CLI script. Controller actions are within /website/controllers folder and they need to be called through http: http://localhost?controller=default&action=default
Example: /website/controllers/DefaultController.php
<?php
class DefaultController extends Website_Controller_Action {
public function defaultAction () {
$this->disableViewAutoRender();
$objectExporter = new Website\ObjectExporter();
$objectExporter->exportObjects();
}
}
(You could also add your whole code directly into action, but that would be a bit ugly solution, it of course depends)
But better and quickest way to approach such tasks is with the CLI scripts.
I like to use the /website/var/cli folder (you need to create it manually, but the /website/var folder is excluded in .htaccess by default which makes it practical for such use cases).
Example: /website/var/cli/export-objects.php
<?php
$workingDirectory = getcwd();
chdir(__DIR__);
include_once("../../../pimcore/cli/startup.php");
chdir($workingDirectory);
$objectExporter = new Website\ObjectExporter();
$objectExporter->exportObjects();
Then just run it by issuing this command in your command line:
php website/var/cli/export-objects.php

This is the standard way of creating CLI scripts in pimcore:
https://www.pimcore.org/wiki/pages/viewpage.action?pageId=16854341
Basically it's just Symfony/Console, which is documented in here detail:
http://symfony.com/doc/current/components/console/introduction.html

Related

Can't pass GET parameter while unit testing Zend Framework 2

I'm having hard time trying to unit test (phpUnit) one of my modules in ZF2. What I'm trying to do is determine whether a classname is present on one of the elements on page when a GET parameter is passed to the controller.
It all works from the browser, however I can't get the GET parameter to be recognized at all when trying to unit test.
This is my code for unit testing:
<?php
namespace ComponentManager\Controller;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class ComponentManagerControllerTest extends AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(
include 'config/application.config.php'
);
parent::setUp();
}
public function testAdminComponentCodeCanBeAccessed()
{
$this->dispatch('/ComponentManager/requestComponent/product/details-1/details-1', 'GET', array('admin' => 1));
// I also tried: $this->dispatch('/ComponentManager/requestComponent/product/details-1/details-1?admin=1');
$this->assertResponseStatusCode(200);
$this->assertMatchedRouteName('ComponentManager/path');
$this->assertControllerName('ComponentManager\Controller\ComponentManager');
$this->assertControllerClass('ComponentManagerController');
$this->assertActionName('requestComponent');
$this->assertModuleName('ComponentManager');
// test will fail here
$this->assertQuery('div.config-active-wrapper');
}
}
The "div.config-active-wrapper" selector works fine when I remove the check for admin parameter presence in GET but when I re-add it, the GET parameter doesn't get recognised at all. Any ideas?
The problem here was that unit testing is a CLI operation and no superglobals are being populated while in CLI. Simple and stupid :P
A solution is to not use superglobals like $_GET here but to pass this "admin" parameter via some ACL and a controller instead.

Jenkins Groovy Postbuild use static file instead of script

Is it possible to load an external groovy script into the groovy post build plugin instead of pasting the script content into each job? We have approximately 200 jobs so updating them all is rather time consuming. I know that I could write a script to update the config files directly (as in this post: Add Jenkins Groovy Postbuild step to all jobs), but these jobs run 24x7 so finding a window when I can restart Jenkins or reload the config is problematic.
Thanks!
Just put the following in the "Groovy script:" field:
evaluate(new File("... groovy script file name ..."));
Also, you might want to go even further.
What if script name or path changes?
Using Template plugin you can create a single "template" job, define call to groovy script (above line) in there, and in all jobs that need it add post-build action called "Use publishers from another project" referencing this template project.
Update: This is what really solved it for me: https://issues.jenkins-ci.org/browse/JENKINS-21480
"I am able to do just that by doing the following. Enter these lines in lieu of the script in the "Groovy script" box:"
// Delegate to an external script
// The filename must match the class name
import JenkinsPostBuild
def postBuild = new JenkinsPostBuild(manager)
postBuild.run()
"Then in the "Additional groovy classpath" box enter the path to that file."
We do it in the following fashion.
We have a file c:\somepath\MyScriptLibClass.groovy (accessible for Jenkins) which contains code of a groovy class MyScriptLibClass. The class contains a number of functions designed to act like static methods (to be mixed in later).
We include this functions writing the following statement in the beginning of sytem groovy and postbuild groovy steps:
[ // include lib scripts
'MyScriptLibClass'
].each{ this.metaClass.mixin(new GroovyScriptEngine('c:\\somepath').loadScriptByName(it+'.groovy')) }
This could look a bit ugly but you need to write it only once for script. You could include more than one script and also use inheritance between library classes.
Here you see that all methods from the library class are mixed in the current script. So if your class looks like:
class MyScriptLibClass {
def setBuildName( String str ){
binding?.variables['manager'].build.displayName = str
}
}
in Groovy Postbuild you could write just:
[ // include lib scripts
'MyScriptLibClass'
].each{ this.metaClass.mixin(new GroovyScriptEngine('c:\\somepath').loadScriptByName(it+'.groovy')) }
setBuildName( 'My Greatest Build' )
and it will change your current build's name.
There are also other ways to load external groovy classes and it is not necessary to use mixing in. For instance you can take a look here Compiling and using Groovy classes from Java at runtime?
How did I solve this:
Create file $JENKINS_HOME/scripts/PostbuildActions.groovy with following content:
public class PostbuildActions {
void setBuildName(Object manager, String str ){
binding?.variables['manager'].build.displayName = str
}
}
In this case in Groovy Postbuild you could write:
File script = new File("${manager.envVars['JENKINS_HOME']}/scripts/PostbuildActions.groovy")
Object actions = new GroovyClassLoader(getClass().getClassLoader()).parseClass(script).newInstance();
actions.setBuildName(manager, 'My Greatest Build');
If you wish to have the Groovy script in your Code Repository, and loaded onto the Build / Test Slave in the workspace, then you need to be aware that Groovy Postbuild runs on the Master.
For us, the master is a Unix Server, while the Build/Test Slaves are Windows PCs on the local network. As a result, prior to using the script, we must open a channel from the master to the Slave, and use a FilePath to the file.
The following worked for us:
// Get an Instance of the Build object, and from there
// the channel from the Master to the Workspace
build = Thread.currentThread().executable
channel = build.workspace.channel;
// Open a FilePath to the script
fp = new FilePath(channel, build.workspace.toString() + "<relative path to the script in Unix notation>")
// Some have suggested that the "Not NULL" check is redundant
// I've kept it for completeness
if(fp != null)
{
// 'Evaluate' requires a string, so read the file contents to a String
script = fp.readToString();
// Execute the script
evaluate(script);
}
I've just faced with the same task and tried to use #Blaskovicz approach.
Unfortunately it does not work for me, but I find upgraded code here (Zach Auclair)
Publish here with minor changes:
postbuild task
//imports
import hudson.model.*
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import java.io.File;
// define git file
def postBuildFile = manager.build.getEnvVars()["WORKSPACE"] + "/Jenkins/SimpleTaskPostBuildReporter.GROOVY"
def file = new File(postBuildFile)
// load custom class from file
Class groovy = this.class.classLoader.parseClass(file);
// create custom object
GroovyObject groovyObj = (GroovyObject) groovy.newInstance(manager);
// do report
groovyObj.report();
postbuild class file in git repo (SimpleTaskPostBuildReporter.GROOVY)
class SimpleTaskPostBuildReporter {
def manager
public SimpleTaskPostBuildReporter(Object manager){
if(manager == null) {
throw new RuntimeException("Manager object can't be null")
}
this.manager = manager
}
public def report() {
// do work with manager object
}
}
I haven't tried this exactly.
You could try the Jenkins Job DSL plugin which allows you to rebuild jobs from within jenkins using a Groovy DSL and supports post build groovy steps directly from the wiki
Groovy Postbuild
Executes Groovy scripts after a build.
groovyPostBuild(String script, Behavior behavior = Behavior.DoNothing)
Arguments:
script The Groovy script to execute after the build. See the plugin's
page for details on what can be done. behavior optional. If the script
fails, allows you to set mark the build as failed, unstable, or do
nothing. The behavior argument uses an enum, which currently has three
values: DoNothing, MarkUnstable, and MarkFailed.
Examples:
This example will run a groovy script that prints hello, world and if
that fails, it won't affect the build's status:
groovyPostBuild('println "hello, world"') This example will run a
groovy script, and if that fails will mark the build as failed:
groovyPostBuild('// some groovy script', Behavior.MarkFailed) This example
will run a groovy script, and if that fails will mark the
build as unstable:
groovyPostBuild('// some groovy script', Behavior.MarkUnstable) (Since 1.19)
There is a facility to use a template job (this is the bit I haven't tried) which could be the job itself so you only need to add the post build step. If you don't use a template you need to recode the whole project.
My approach is to have a script to regenerate or create all jobs from scratch just so I don't have to apply the same upgrade multiple times. Regenerated jobs keep their build history
I was able to get the following to work (I also posted on this jira issue).
in my postbuild task
this.class.classLoader.parseClass("/home/jenkins/GitlabPostbuildReporter.groovy")
GitlabPostbuildReporter.newInstance(manager).report()
in my file on disk at /home/jenkins/GitlabPostbuildReporter.groovy
class GitlabPostbuildReporter {
def manager
public GitlabPostbuildReporter(manager){
if(manager == null) {
throw new RuntimeException("Manager object musn't be null")
}
this.manager = manager
}
public def report() {
// do work with manager object
}
}

using components in Cakephp 2+ Shell

I am trying to implement a task using the cakephp shell for my application. The task involves running a long running process (hence the need to use the shell).
The function requires me to use a function inside a Component called CommonComponent
Unfortunately whenever i try to include the component i get the following error
PHP Fatal error: Class 'Component' not found in /var/www/nginx-test/app/Controller/Component/CommonComponent.php
Here is the CronShell Class which is being called
class CronShell extends AppShell {
public function main() {
$this->out('Hello world.');
// $this->out(phpinfo());
}
public function test()
{
$this->out('Before Import');
App::import('Component', 'Common');
$this->out('Import complete');
// $this->Common=ClassRegistry::init('CommonComponent');
$this->Common =new CommonComponent();
$this->out('Initialization complete');
$this->Common->testCron();
$this->out('FunctionCall complete');
//$this->Common->saveCacheEntry("name","value");
}
}
The CommonComponent class is stored as app/Controller/Component/CommonComponent.php and is as follows
class CommonComponent extends Component
{
function testCron()
{
$this->out('Hello world from Component.');
}
}
Any ideas?
I had to do this recently with MTurk component I wrote. My final solution was using a lib instead of a component. Then I had the component access the lib so I could use the methods from both a component and from shell.
However, here is code that WILL allow you to load a component from a shell.
<?php
App::uses('AppShell', 'Console/Command');
App::uses('ComponentCollection', 'Controller');
App::uses('Controller', 'Controller');
App::uses('MTurkComponent', 'Controller/Component');
class ProcessCompletedTask extends Shell {
public function execute() {
$this->out("Processing...\n");
$collection = new ComponentCollection();
$this->MTurk = new MTurkComponent($collection);
$controller = new Controller();
$this->MTurk->initialize($controller);
$this->MTurk->processHITs();
$this->out("Complete\n");
}
}
What you import into the Shell should be code from within your Apps Lib
the component can also make use of the Lib code - but you'll not need to do a load of tedious stuff
if you set it up right you'll make you app cleaner
if you import the component you'll need to pass it a component collection and so you'd have to make that from witin shell not that your use it (or if you do you must be doing it wrong)
Have you tried App::uses('Component', 'Controller'); at the top of your file, ev. before import of CommonComponent? Then I guess you need to do what sam says, or you could use the $this->Controller->Components->load('CommonComponent') but for that you need to construct the Controller class.
I believe that it is semantically wrong to share functionality between controllers and shells.
If you require common functionality, it is clearer and neater to put it in a separate class, place this class in your vendors folder and then import the code into both the controller and the shell.
In addition, this approach does not prevent you from creating components and tasks that use the core functionality and then share these components and tasks between your controllers and shells.

Jmeter BSF using Groovy, Import one script's function to another

I use groovy in my Jmeter BSF, and sometimes I have functions that are used frequently enough to be moved to some script which I than can use as a library.
My approach was to create a file, say "library.groovy", and add there some function
public void function()
{
println("hello!");
}
and then use the following code in my BSF script
import library.groovy;
function();
Both files lie in the same dir, but script refuses to locate library. I also tried to explicitly wrap this function into class but I took no effect as well.
Can anyone suggest a solution for this?
Update:
I tried almost all possible solutions described in the internet. And everything that works in groovy console or Eclipse does not in Jmeter. Probably that is because of BSF. Anyone knows some workarounds?
I just had this problem, and solved it in a way that seems, to me, nicer-looking. It is basically winstaan74's answer, but with the extra bits needed to make it work.
You have your function's groovy file, named say: MyJmeterFunctions.groovy:
package My.JmeterFunctions
public class MyHelloClass {
public void hello() {
println("Hello!");
}
}
Then you compile this from the terminal:
$groovyc -d myJmeterFunctions myJmeterFunctions.groovy
and turn it into a .jar inside the /lib folder of your jmeter install, with all the other .jar files that came with jmeter
$jar cvf /<>/apache-jmeter-2.8/lib/myJmeterFunctions.jar -C myJmeterFunctions .
Now, restart jmeter. It won't know about your new .jar until you do.
Lastly you have the script that you want to run the hello() function from, which your jmeter BSF assertion/listener/ whatever points to:
import My.JmeterFunctions.*
def my_hello_class_instance = new MyHelloClass();
my_hello_class_instance.hello();
And this is what worked for me. If you'd rather organize you .jar into a different folder than jmeter's /lib, I believe you can run jmeter using (from here):
$jmeter -Jsearch_paths=/path/to/yourfunction.jar
But I haven't tried that myself.
I ended up having 2 files like below:
"MyHelloClass.groovy"
public class MyHelloClass {
public void hello() {
println("Hello!");
}
}
And "HelloScript.groovy"
try {
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("../GroovyScripts/MyHelloClass.groovy"));
GroovyObject helloClass = (GroovyObject) groovyClass.newInstance();
helloClass.hello();
}
catch (Throwable e) {
println(e.toString());
}
Then I can run "HelloScript.groovy" in BSF from Jmeter.
I think you'll need to wrap your helper methods in a class, and then import that class. So, your helper methods file should contain..
package library
class UsefulFunctions {
static function() {
println 'hello'
}
}
And then in your test script, say
import static library.UsefulFunctions.*
function()
Now, this is just scratching the surface, but I hope it'd be enough to get you started.

What is the best way to import constants into a groovy script?

I have been setting up a scripting envrionment using Groovy. I have a groovy script called FrameworkiDatabase.groovy which contains a class of the same name. This works fine. I also have another file called connections.groovy which contains maps like the following:
SUPPORT2=[
host:"host.name",
port:"1521",
db:"support2",
username:"username",
password:"password",
dbType:"oracle"
]
This holds a collection of database bookmarks, a bit like an oracle tnsnames file, so I don't need to remember all the parameters when connecting to databases.
When using groovysh, I can import this using the load command, and it is available in current scope. How can I load it as part of a script the same way? It has no class definition around it - does it need one? I have tried doing that, and adding a static import, but that didn't work...
I tried something like this, but no luck:
testFrameworkiDatabase.groovy:
import static connections
def db = new FrameworkiDatabase(SUPPORT2)
db.listInvalidObjects()
db.getDBSchemaVersion()
db.getFWiVersion()
db.getSPVersion()
db.getFileloaderVersion()
db.getAdminToolVersion()
db.getReportsVersion()
So I want to load those connections as constants - is there any way I can do this easily?
Not sure if it's the best way, but one way would be to write this into Connections.groovy
class Connections {
static SUPPORT2 = [
host:"host.name",
port:"1521",
db:"support2",
username:"username",
password:"password",
dbType:"oracle"
]
}
Then, compile this with groovyc Connections.groovy to generate a class file
Then, in your test script or on the groovysh prompt, you can do:
import static Connections.*
println SUPPORT2
To get the output:
[host:host.name, port:1521, db:support2, username:username, password:password, dbType:oracle]
If compiling the Connections.groovy class isn't good enough, I think you're going to be looking at loading the source into a Binding object by using one of the Groovy embedding techniques

Resources