How to create query builder was failed in CakePHP 3.7 - cakephp-3.7

I'm setting up query builder in CakePHP 3.7 to get value in single row, inside UsersTable. I want to get row value "where Name = 'Budi'"
I'm tried to solved it by browsing in https://book.cakephp.org/3.0/en/orm/query-builder.html but doesn't work
<?php
//UsersController.php
namespace App\Controller;
use App\Controller\AppController;
use App\Model\Table\UsersTable;
use Cake\Event\event;
use Cake\I18n\Time;
use Cake\ORM\TableRegistry;
class UsersController extends AppController
{
public function index
{
$query = $users->find()
->select(['ID', 'Nama'])
->where(['Nama =' => 'Budi']);
foreach ($query as $users) {
debug($users->Nama);
}
$this->set(compact('users'));
}
//code from cake bake all
}
?>
the messages error shown here
Notice (8): Undefined variable: users [APP/Controller\UsersController.php, line 20]
Notice (1024): Undefined property: ErrorController::$Auth in C:\xampp\htdocs\klinikucing\src\Controller\AppController.php on line 57 [CORE\src\Controller\Controller.php, line 388]
Warning (512): Unable to emit headers. Headers sent in file=C:\xampp\htdocs\klinikucing\vendor\cakephp\cakephp\src\Error\Debugger.php line=853 [CORE\src\Http\ResponseEmitter.php, line 48]
Warning (2): Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\klinikucing\vendor\cakephp\cakephp\src\Error\Debugger.php:853) [CORE\src\Http\ResponseEmitter.php, line 148]
Warning (2): Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\klinikucing\vendor\cakephp\cakephp\src\Error\Debugger.php:853) [CORE\src\Http\ResponseEmitter.php, line 181]
Warning (2): Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\klinikucing\vendor\cakephp\cakephp\src\Error\Debugger.php:853) [CORE\src\Http\ResponseEmitter.php, line 181]
An Internal Server Error Occurred
I expect the output is
-------------------------------------------------
| Nama | Role | Dibuat | Diubah |
-------------------------------------------------
| Budi | Visitor | 10/04/2019 | 12/04/2019 |
-------------------------------------------------

You need to reference the model of the controller as well
Use
$query = $this->Users->find()
->select(['ID', 'Nama'])
->where(['Nama =' => 'Budi']);

on first line of index function, i think you must define $users variable
$users = TableRegistry::get('Users');

Related

Execute command line in attribute

I want to generate MAC address and UUID in attribute and then pass the values to template.
something like this :
Attribute/default.rb:
default['libvirt']['xml_mac_Adrr'] = 'openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//''
default['libvirt']['xml_uuid'] = 'uuidgen virbr0'
Template/network.erb:
<uuid><%= node['libvirt']['xml_uuid'] %></uuid>
  <mac address='<%= node['libvirt']['xml_mac_Adrr']%>'/>
How can I do that?
UPDATE
I want to modify the default.xml network for the virtual network. Basically, we have to do it by virsh-net command
Now I want to use a template to pass UUID & MAC address values to XML file and modify it in guest machine.
this is my recipe:
template '/etc/libvirt/qemu/network/default.xml' do
source 'qemu-network.erb'
owner "root"
group "root"
mode "0644"
end
Yo can use backquotes to execute shell commands inside ruby and capture the response:
default['libvirt']['xml_mac_Adrr'] = `openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//'`
default['libvirt']['xml_uuid'] = `uuidgen virbr0`
EDIT:
The second problem I see is that you have to use instance variables in the controller to share information with the view. So the best way would be:
#mac = `openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//'`
#uuid = `uuidgen virbr0`
Then at view level you can use:
<uuid><%=#uuid %></uuid>
<mac address='<%=#mac %>'/>
Within chef relying on system commands should go through the shell_out method (which is included in the recipe dsl) to avoid some quirks when the DSL interpreter is run and getting methosd to clean up the ouput.
I'd go this way:
default['libvirt']['xml_mac_Adrr'] = Chef::ShellOut.new("openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//'").stdout.chomp
default['libvirt']['xml_uuid'] = Chef::ShellOut.new('uuidgen virbr0').stdout.chomp
But this has a problem, at each run, a new mac address will be generated, so you should use normal and avoid redefining it, this is easiest moved into the recipe, following in recipe file before your template code should do:
node.normal['libvirt']['xml_mac_Adrr'] = shell_out("openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//'").stdout.chomp unless node['libvirt'].includes?('xml_mac_Adrr')

Can't enable phar writing

I am actually using wamp 2.5 with PHP 5.5.12 and when I try to create a phar file it returns me the following message :
Uncaught exception 'UnexpectedValueException' with message 'creating archive "..." disabled by the php.ini setting phar.readonly'
even if I turn to off the phar.readonly option in php.ini.
So how can I enable the creation of phar files ?
I had this same problem and pieced together from info on this thread, here's what I did in over-simplified explanation:
in my PHP code that's generating this error, I added echo phpinfo(); (which displays a large table with all sort of PHP info) and in the first few rows verify the path of the php.ini file to make sure you're editing the correct php.ini.
locate on the phpinfo() table where it says phar.readonly and note that it is On.
open the php.ini file from step 1 and search for phar.readonly. Mine is on line 995 and reads ;phar.readonly = On
Change this line to phar.readonly = Off. Be sure that there is no semi-colon at the beginning of the line.
Restart your server
Confirm that you're phar project is now working as expected, and/or search on the phpinfo()table again to see that the phar.readonly setting has changed.
phar.readonly can only be disabled in php.ini due to security reasons.
If you want to check that it's is really not done using other method than php.ini then in terminal type this:-
$ php -r "ini_set('phar.readonly',0);print(ini_get('phar.readonly'));"
If it will give you 1 means phar.readonly is On.
More on phar.configuration
Need to disable in php.ini file
Type which php
Gives a different output depending on machine e.g.
/c/Apps/php/php-7.2.11/php
Then open the path given not the php file.
E.g. /c/Apps/php/php-7.2.11
Edit the php.ini file
could do
vi C:\Apps\php\php-7.2.11\php.ini
code C:\Apps\php\php-7.2.11\php.ini
[Phar]
; http://php.net/phar.readonly
phar.readonly = Off
; http://php.net/phar.require-hash
phar.require_hash = Off
Save
Using php-cli and a hashbang, we can set it on the fly without messing with the ini file.
testphar.php
#!/usr/bin/php -d phar.readonly=0
<?php
print(ini_get('phar.readonly')); // Must return 0
// make sure it doesn't exist
#unlink('brandnewphar.phar');
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
} catch (Exception $e) {
echo 'Could not create phar:', $e;
}
echo 'The new phar has ' . $p->count() . " entries\n";
$p->startBuffering();
$p['file.txt'] = 'hi';
$p['file2.txt'] = 'there';
$p['file2.txt']->compress(Phar::GZ);
$p['file3.txt'] = 'babyface';
$p['file3.txt']->setMetadata(42);
$p->setStub('<?php
function __autoload($class)
{
include "phar://myphar.phar/" . str_replace("_", "/", $class) . ".php";
}
Phar::mapPhar("myphar.phar");
include "phar://myphar.phar/startup.php";
__HALT_COMPILER();');
$p->stopBuffering();
// Test
$m = file_get_contents("phar://brandnewphar.phar/file2.txt");
$m = explode("\n",$m);
var_dump($m);
/* Output:
* there
**/
✓ Must be set executable:
chmod +x testphar.php
✓ Must be called like this:
./testphar.php
// OUTPUT there
⚠️ Must not be called like this:
php testphar.php
// Exception, phar is read only...
⚠️ Won't work called from a CGI web server
php -S localhost:8785 testphar.php
// Exception, phar is read only...
For anyone who has changed the php.ini file, but just doesn't see any changes. Try to use the CLI version of the file. For me, it was in /etc/php/7.4/cli/php.ini
Quick Solution!
Check:
cat /etc/php/7.4/apache2/php.ini | grep phar.readonly
Fix:
sed -i 's/;phar.readonly = On/;phar.readonly = Off/g' /etc/php/7.4/apache2/php.ini

Grails possible race condition in database session?

I'm learning grails and read Grails In Action book. Try perform some tests from it, but got strange behaviour for me. I have next simple integration test:
#Test
public void testProjections() throws Exception {
User user1 = new User(mail: 'test1#test.tld', password: 'password1').save(flush: true)
User user2 = new User(mail: 'test2#test.tld', password: 'password2').save(flush: true)
assertNotNull(user1)
assertNotNull(user2)
// Chain add Tag to Post
user1.addToPosts(new Post(content: 'First').addToTags(new Tag(name: 'tag-0')))
// Separate add tag to post
Post post = user1.posts.iterator().next()
Tag tag1 = new Tag(name: 'tag-1')
post.addToTags(tag1)
// http://stackoverflow.com/questions/6288991/do-i-ever-need-to-explicitly-flush-gorm-save-calls-in-grails
// Have tried with and without next line without success:
//sessionFactory.getCurrentSession().flush()
assertEquals(['tag-0', 'tag-1'], user1.posts.iterator().next().tags*.name.sort()) // line 154
…
}
Then I run it twice subsequently:
grails>
grails> test-app -rerun -integration
| Running 5 integration tests... 2 of 5
| Failure: testProjections(com.tariffus.QueryIntegrationTests)
| java.lang.AssertionError: expected:<[tag-0, tag-1]> but was:<[tag-1]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.tariffus.QueryIntegrationTests.testProjections(QueryIntegrationTests.groovy:154)
| Completed 5 integration tests, 1 failed in 0m 0s
| Tests FAILED - view reports in /home/pasha/Projects/grails/com.tariffus/target/test-reports
grails>
grails> test-app -rerun -integration
| Running 5 integration tests... 2 of 5
| Failure: testProjections(com.tariffus.QueryIntegrationTests)
| java.lang.AssertionError: expected:<[3, 1, 2]> but was:<[[tag-1, tag-2, tag-0, tag-5, tag-3, tag-4], [tag-6]]>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:743)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.tariffus.QueryIntegrationTests.testProjections(QueryIntegrationTests.groovy:164)
| Completed 5 integration tests, 1 failed in 0m 0s
| Tests FAILED - view reports in /home/pasha/Projects/grails/com.tariffus/target/test-reports
grails>
As you can see first fails on line 157 and second, runned just after that in second without any modification goes further.
I use Postgres database and environment test configured dataSource in mode dbCreate = 'update'.
What I do incorrect and why it works sometimes?
I would say that a source of problem is this line:
user1.addToPosts(new Post(content: 'First').addToTags(new Tag(name: 'tag-0')))
These dynamic addTo* methods does not propagate save to the associated instances until save() is called on the parent instance. So calling save() on user1 after should fix it:
user1.addToPosts(new Post(content: 'First').addToTags(new Tag(name: 'tag-0')))
user1.save()
This should propagate save() to Post instance at first and then to Tag instance transitively.

CloudFoundry - Application 'controlealunos' does not exist

I think that i'm suffering a bug problem. I created a application on Cloud Foundry with the name "controle*A*lunos" with the upper case letter A.
When i execute the command
cf-apps
i get this result:
+----------------+----+---------+---------------------------------+---------------+
| Application | # | Health | URLs | Services |
+----------------+----+---------+---------------------------------+---------------+
| controleAlunos | 1 | RUNNING | controlealunos.cloudfoundry.com | mysql-86d568b |
+----------------+----+---------+---------------------------------+---------------+
But when i try to update my project whit the command :
prod cf-update controleAlunos controleAlunos-0.1.war
i receive an error
Error Application 'controlealunos' does not exist.
I think that it should be the name of my application. I put it with one Upper Case letter controle*A*lunos and i'm receving the error with no upper case letter controlealunos.
I tried to rename it, but i still get the error.
Any Sugests ?
I guess the project name you created is "controlealunos" which resulted in the app.name property in application.properties is a lower case name, while the name used to push onto CF is "controleAlunos". You can try change the value in the properties file and update again.

Grails: Unable to resolve class groovyx.net.http.HTTPBuilder

I have developped some web services that I would like tu use in my grails application.
These services can be called using Get or POST protocols.
I have seen that I need to use the HTTP builder object to do that.
This is my code:
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.ContentType
import groovyx.net.http.Method
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
def http = new HTTPBuilder( 'http://localhost:8086' )
http.request( GET, JSON ) {
uri.path = '/RegistrationService/webresources/users/isRegistered'
uri.query = [ login:'aa', password: 'bb' ]
response.success = { resp, xml ->
def xmlResult = xml
}
}
The problem I have is that in Netbeans I have an error for each import:
Unable to resolve class groovyx.net.http.HTTPBuilder
Unable to resolve class groovyx.net.http.ContentType
...
However I tried to run the application and this is the error when I run my code:
| Error 2013-02-25 23:33:32,596 [http-bio-8080-exec-3] ERROR errors.GrailsExceptionResolver - MissingPropertyException occurred when processing request: [POST] /WordGame/user/authenticate
No such property: uriPath for class: groovyx.net.http.HTTPBuilder$RequestConfigDelegate. Stacktrace follows:
Message: No such property: uriPath for class: groovyx.net.http.HTTPBuilder$RequestConfigDelegate
Line | Method
->> 21 | doCall in wordgame.UserController$_closure2_closure4
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 425 | doRequest in groovyx.net.http.HTTPBuilder
| 359 | request . in ''
| 19 | doCall in wordgame.UserController$_closure2
| 195 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter
| 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter
| 1110 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 603 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 722 | run . . . in java.lang.Thread
I have installed the rest plugin using the command: grails install-plugin rest
And I have already tried to install it with the netbeans interface and it tells me that it is correctly instaled.
I have seen on some forums that I need to had dependencies in the file BuildConfig.groovy like that:
dependencies {
runtime('org.codehaus.groovy.modules.http-builder:http-builder:0.5.1') {
excludes 'xalan'
excludes 'xml-apis'
excludes 'groovy'
}
}
But this is not resolving the problem.
For information I am using netbeans 7.2.1 and Grails 2.2.0.
Is there something wrong with my code or is there a simplier way to request a web service?
Thanks in advance.
so, I read through the Exception you posted and your code snippet again and it seems that you have omitted the req variable within the http.request(){} closure. also you have not imported the GET method and TEXT content type. try:
import groovyx.net.http.HTTPBuilder
//import groovyx.net.http.ContentType // this doesn't import ContentType
//import groovyx.net.http.Method // this doesn't import Method
import groovyx.net.http.RESTClient
import groovyx.net.http.HttpResponseDecorator
// ContentType static import
import static groovyx.net.http.ContentType.*
// Method static import
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://localhost:8086' )
http.request( GET, JSON ) { req -> // 'req ->' is not present in your code snippet!
uri.path = '/RegistrationService/webresources/users/isRegistered'
uri.query = [ login:'aa', password: 'bb' ]
response.success = { resp, xml ->
def xmlResult = xml
}
}
also I would recommend to read through the documentation of HTTPBuilder at this location: http://groovy.codehaus.org/modules/http-builder/doc/index.html as the code is well explained and some howtos and tutorials are also listed ;)
i just solved my problem.
Download this: http://repository.codehaus.org/org/codehaus/groovy/modules/http-builder/http-builder/0.5.2/
Copy the httpBuilder.jar and all the jars from dependencies directory in your groovy_installed_directory/lib. Then restart console and try again.
Hope it helps.
BR