I am trying to send email to all users with admin role when list() action has been called.
Inside my list method I put the following code:
def admins = User.findAllByRole("ROLE_ADMIN")
//def approverEmails = User.findByRole("ROLE_APPROVER").collect { it.email }
notifierService.sendApproverRequestEmail(admins)
flash.message = message(code: 'default.created.message', args: [message(code: 'project.label', default: 'Project'), projectInstance.id])
redirect(action: "show", id: projectInstance.id)
But Grails doesn't recognize findAllByRole() method. What am I doing wrong? Is there any other way to send message from service when certain actions in controller are called.
Here is also my service code:
def sendApprovalRequestEmail( def users ) {
users.each { -> user
mailService.sendMail{
to user.email
from "padre#everyonecounts.com"
subject "New project needs approval."
body "Hi ${user.username}! " +
"New project has been requested and needs your approval."
}
}
}
Here is the error:
URI
/PaDRe/project/list
Class
org.codehaus.groovy.grails.exceptions.InvalidPropertyException
Message
No property found for name [role] for class [class com.everyonecounts.padre.User]
Around line 21 of grails-app\controllers\com\everyonecounts\padre\ProjectController.groovy
18: params.max = Math.min(params.max ? params.int('max') : 10, 100)
19: [projectInstanceList: Project.list(params), projectInstanceTotal: Project.count()]
20:
21: def admins = User.findAllByRole("ROLE_ADMIN")
22: //def approverEmails = User.findByRole("ROLE_APPROVER").collect { it.email }
23: notifierService.sendApproverRequestEmail(admins)
24:
Trace
Line | Method
->> 108 | methodMissing in org.grails.datastore.gorm.GormStaticApi
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 21 | list in ProjectController.groovy
| 895 | runTask . . . in java.util.concurrent.ThreadPoolExecutor$Worker
| 918 | run in ''
^ 662 | run . . . . . in java.lang.Thread
Here is my User class
package com.everyonecounts.padre
class User{
transient springSecurityService
String username
String password
String email
boolean enabled
boolean accountExpired
boolean accountLocked
boolean passwordExpired
static constraints = {
username blank: false, unique: true
password size: 5..80, blank: false
}
static mapping = {
password column: '`password`'
}
Set<Role> getAuthorities() {
UserRole.findAllByUser(this).collect { it.role } as Set
}
def beforeInsert() {
encodePassword()
}
def beforeUpdate() {
if (isDirty('password')) {
encodePassword()
}
}
protected void encodePassword() {
password = springSecurityService.encodePassword(password)
}
}
The problem you are having is because you don't understand the default spring security implementation. To get a list of users with a given role:
UserRole.findAllByRole(Role.findByAuthority("ROLE_ADMIN"))*.user
Your problem probably is that User.findAllByRole() is expecting a Role as the argument, not a String.
There is a relevant example in 'Querying Associations' subsection of http://grails.org/doc/2.2.x/guide/single.html#finders (shown below)
def author = Author.findByName("Stephen King")
def books = author ? Book.findAllByAuthor(author) : []
Related
Using these parameters:
canada {
hosts = ["dd.weather.gc.ca"]
username = "anonymous"
password = "anonymous"
port = 5671
exchange = "xpublic"
queue = "q_anonymous_gsk"
routingKey = "v02.post.observations.swob-ml.#"
requestedHeartbeat = 300
ssl = true
}
I can connect to a weather service in Canada using NewMotion/Akka, but when I try op-rabbit, I get:
ACCESS_REFUSED - access to exchange 'xpublic' in vhost '/' refused for user 'anonymous'
[INFO] [foo-akka.actor.default-dispatcher-7] [akka://foo/user/$a/connection] akka://foo/user/$a/connection connected to amqp://anonymous#{dd.weather.gc.ca:5671}:5671//
[INFO] [foo-op-rabbit.default-channel-dispatcher-6] [akka://foo/user/$a/connection/$a] akka://foo/user/$a/connection/$a connected
[INFO] [foo-akka.actor.default-dispatcher-4] [akka://foo/user/$a/connection/confirmed-publisher-channel] akka://foo/user/$a/connection/confirmed-publisher-channel connected
[INFO] [foo-akka.actor.default-dispatcher-4] [akka://foo/user/$a/connection/$b] akka://foo/user/$a/connection/$b connected
[ERROR] [foo-akka.actor.default-dispatcher-3] [akka://foo/user/$a/subscription-q_anonymous_gsk-1] Connection related error while trying to re-bind a consumer to q_anonymous_gsk. Waiting in anticipating of a new channel.
...
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=403, reply-text=ACCESS_REFUSED - access to exchange 'xpublic' in vhost '/' refused for user 'anonymous', class-id=40, method-id=10)
The following works in NewMotion/Akka:
val inQueue = "q_anonymous_gsk"
val inExchange = "xpublic"
val canadaQueue = canadaChannel.queueDeclare(inQueue, false, true, false, null).getQueue
canadaChannel.queueBind(canadaQueue, inExchange, inQueue)
val consumer = new DefaultConsumer(canadaChannel) {
override def handleDelivery(consumerTag: String, envelope: Envelope, properties: BasicProperties, body: Array[Byte]) {
val s = fromBytes(body)
if (republishElsewhere) {
// ...
}
}
}
canadaChannel.basicConsume(canadaQueue, true, consumer)
but using op-rabbit like this:
val inQueue = "q_anonymous_gsk"
val inExchange = "xpublic"
val inRoutingKey = "v02.post.observations.swob-ml.#""
val rabbitCanada: ActorRef = actorSystem.actorOf(Props(classOf[RabbitControl], connParamsCanada))
def runSubscription(): SubscriptionRef = Subscription.run(rabbitCanada) {
channel(qos = 3) {
consume(topic(queue(inQueue), List(inRoutingKey))) {
(body(as[String]) & routingKey) { (msg, key) =>
ack
}
}
}
}
I get the ACCESS_REFUSED error near the top of this post. Why? How do I fix this if I want to use op-rabbit?
Have you tried to use the correct vhost with permission to anonymous user
I'm using Spring Security Facebook plugin in my grails app. It shows the below error messege when returning from facebook page after authentication. The facebook user details are not saved in database. Kindly help to solve this error and to authenticate facebook users successfully. Thanks in advance.
FacebookUser.groovy Domain Class
class FacebookUser {
long uid
String accessToken
Date accessTokenExpires
static belongsTo = [user: User]
static constraints = {
uid unique: true
}
}
Config.groovy settings for spring-security-facebook app
grails.plugins.springsecurity.facebook.domain.classname='com.awnsys.gcx.FacebookUser'
grails.plugins.springsecurity.facebook.domain.appUserConnectionPropertyName = 'user'
grails.plugins.springsecurity.facebook.appId='APPID'
grails.plugins.springsecurity.facebook.secret='secretID'
grails.plugins.springsecurity.facebook.autoCreate.enabled=true
grails.plugins.springsecurity.facebook.autoCreate.roles=['ROLE_USER', 'ROLE_FACEBOOK',]
Below is the error Message shown in browser when redirects from facebook after the user accepts app in facebook
Error 500: Internal Server Error
URI : /myapp/j_spring_security_facebook_check
Class : grails.validation.ValidationException
Message : Validation Error(s) occurred during save(): - Field error in object 'com.mydomain.myapp.User' on field 'username': rejected value [facebook_100005487962357]; codes [com.mydomain.myapp.User.username.email.error.com.mydomain.myapp.User.username,com.mydomain.myapp.User.username.email.error.username,com.mydomain.myapp.User.username.email.error.java.lang.String,com.mydomain.myapp.User.username.email.error,user.username.email.error.com.mydomain.myapp.User.username,user.username.email.error.username,user.username.email.error.java.lang.String,user.username.email.error,com.mydomain.myapp.User.username.email.invalid.com.mydomain.myapp.User.username,com.mydomain.myapp.User.username.email.invalid.username,com.mydomain.myapp.User.username.email.invalid.java.lang.String,com.mydomain.myapp.User.username.email.invalid,user.username.email.invalid.com.mydomain.myapp.User.username,user.username.email.invalid.username,user.username.email.invalid.java.lang.String,user.username.email.invalid,email.invalid.com.mydomain.myapp.User.username,email.invalid.username,email.invalid.java.lang.String,email.invalid]; arguments [username,class com.mydomain.myapp.User,facebook_100005487962357]; default message [Property [{0}] of class [{1}] with value [{2}] is not a valid e-mail address]
Around line 149 of DefaultFacebookAuthDao.groovy
146: appUser.setProperty(securityConf.userLookup.passwordExpiredPropertyName, false)
147: }
148: AppUserDomainClazz.withTransaction {
149: appUser.save(flush: true, failOnError: true)
150: }
151: }
152: user[appUserConnectionPropertyName] = appUser
Around line 148 of DefaultFacebookAuthDao.groovy
145: appUser.setProperty(securityConf.userLookup.accountLockedPropertyName, false)
146: appUser.setProperty(securityConf.userLookup.passwordExpiredPropertyName, false)
147: }
148: AppUserDomainClazz.withTransaction {
149: appUser.save(flush: true, failOnError: true)
150: }
151: }
Around line 67 of FacebookAuthProvider.groovy
64: log.error("Can't create user w/o access_token")
65: throw new CredentialsExpiredException("Can't receive access_token from Facebook")
66: }
67: user = facebookAuthDao.create(token)
68: justCreated = true
69: } else {
70: log.error "User $token.uid doesn't exist, and creation of a new user is disabled."
Around line 67 of FacebookAuthProvider.groovy
64: log.error("Can't create user w/o access_token")
65: throw new CredentialsExpiredException("Can't receive access_token from Facebook")
66: }
67: user = facebookAuthDao.create(token)
68: justCreated = true69: } else {
70: log.error "User $token.uid doesn't exist, and creation of a new user is disabled."
Trace
Line | Method
->> 149 | doCall in DefaultFacebookAuthDao.groovy
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 687 | withTransaction in org.grails.datastore.gorm.GormStaticApi
| 148 | create . . . . . . . in DefaultFacebookAuthDao.groovy
| 67 | authenticate in FacebookAuthProvider.groovy
| 40 | attemptAuthentication in FacebookAuthRedirectFilter.groovy
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run . . . . . . . . . in java.util.concurrent.ThreadPoolExecutor$Worker
^ 724 | run in java.lang.Thread
By default plugin generates username like facebook_%UID% (facebook_100005487962357 from your stacktrace). Seems that your User domain requires an email for .username field (and have such constraint), so it cannot be saved.
At this case I suggest you to implement own logic for filling User object, by implementing FacebookAuthService.createAppUser method. See docs: http://splix.github.io/grails-spring-security-facebook/guide/5%20Customization.html#5.1%20Using%20FacebookAuthService
And also, Facebook Authentication plugin don't know user email (it's not provided by Facebook Login by default), you have to fetch it from Facebook API, see example: https://github.com/splix/grails-facebook-authentication-example/blob/master/grails-app/services/FacebookAuthService.groovy#L51
For those who are implementing FacebookAuthService and having problems with Facebook and FacebookProfile classes being marked with error, make sure you added to your BuildConfig.groovy file the two plugins
compile ":spring-social-core:0.1.31"
compile ":spring-social-facebook:0.1.32"
NOTE: Spring Social Facebook is not the same plugin as Spring Security Facebook.
So if you have the lines above, you will still have to compile the Spring Social plugins.
compile ':spring-security-core:2.0-RC2'
compile ':spring-security-facebook:0.15.2-CORE2'
I want to create a User in SalesForce programmatically by using SOAP API Partner WSDL. This is my code:
import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.SaveResult;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import com.sforce.soap.partner.sobject.*;
import com.sforce.soap.partner.*;
import com.sforce.soap.*;
import com.sforce.*;
public class PartnerAPICreateUser {
/**
* #param args
*/
public static void main(String[] args) {
ConnectorConfig config = new ConnectorConfig();
config.setUsername("waprau#waprau.com");
config.setPassword("dhskjhkjgfkjsdhkfjg");
PartnerConnection connection = null;
try {
SObject user = new SObject();
user.setType("user");
user.setField("Alias", "abcd");
user.setField("DefaultGroupNotificationFrequency", "P");
user.setField("DigestFrequency", "D");
user.setField("Email", "abcd#pqrs.com");
user.setField("EmailEncodingKey", "ISO-8859-1");
user.setField("LanguageLocaleKey", "English");
user.setField("LastName", "Rau");
user.setField("LocaleSidKey", "En");
user.setField("TimeZoneSidKey", "America/Los_Angeles");
user.setField("Username", "abcd#pqrs.com");
user.setField("UserPermissionsCallCenterAutoLogin", "true");
user.setField("UserPermissionsMarketingUser", "true");
user.setField("UserPermissionsOfflineUser", "true");
connection = Connector.newConnection(config);
SaveResult[] results = connection.create(new SObject[] { user });
System.out.println("Created user: " + results[0].getId());
QueryResult queryResults = connection
.query("SELECT Id, Name from User "
+ "ORDER BY CreatedDate DESC LIMIT 5");
if (queryResults.getSize() > 0) {
for (SObject s : queryResults.getRecords()) {
System.out.println("Id: " + s.getField("Id") + " - Name: "
+ s.getField("Name"));
}
}
} catch (ConnectionException ce) {
ce.printStackTrace();
}
}
}
However, when I execute this Java program it gives following output which shows 'Created user: null' :-(
Created user: null
Id: 005E0000001fb3vIAA - Name: Rau
Id: 005E0000001fVTTIA2 - Name: Chatter Expert
Id: 005E0000001fVU1IAM - Name: Wap Rau
Administrative Permissions when I go to MyName > Setup > Manage Users (in Administration Setup) > Profiles
Can you tell me whats wrong?
Thanks,
Wap Rau
The create call is returning an error, but you don't check for it, the returned SaveResult will tell you why it didn't create the user, you want something like
SaveResult[] results = connection.create(new SObject[] { user });
if (results[0].isSuccess())
System.out.println("Created user: " + results[0].getId());
else
System.out.println("Error: " + results[0].getErrors()[0].getStatusCode() +
":" + results[0].getErrors()[0].getMessage());
import stdlib.web.mail
from = {name="name" address={local="username" domain="gmail.com"}}
to = {name="name" address={local="username" domain="gmail.com"}}
r = Email.try_send(from, to, "Subject", {text = "This is Great!"})
server = Server.one_page_server("Mail", [], [], r)
the following error I'm getting
Error
File "mail.opa", line 6, characters 4-66, (6:4-6:66 | 166-228)
Function was found of type
Email.email, Email.email, string, Email.content -> Email.send_status but
application expects it to be of type
{ address: { domain: string; local: string } / 'c.b; name: string } / 'c.a,
{ address: { domain: string; local: string } / 'c.d; name: string } / 'c.c,
string, { text: string } / 'c.e -> 'a.
Types string and { none } / { some: string } are not compatible
Hint:
Error occurred through field name.
Can anyone help me with Mail functionality in Opa?
There is a number of problems with this code:
Notice that in Email.email type the name field is optional; so if you want to include it you should provide some("name"), not just "name"
Server.one_page_server contains 2 arguments not 4.
The last argument to one_page_server should be the xhtml of the page, whereas your r is the result of sending an email.
After those fixes your code could look something like this:
import stdlib.web.mail
from = {name=some("name") address={local="username" domain="gmail.com"}} : Email.email
to = {name=some("name") address={local="username" domain="gmail.com"}} : Email.email
page() =
status = Email.try_send(from, to, "Subject", {text = "This is Great!"})
<>Email sent</>
server = Server.one_page_server("Mail", page)
I am trying to connect Symfony 2 with MongoDB in such way:
Register DoctrineMongoDBBundle in AppKernel::registerBundles
method
Set 'doctrine_mongo_db' configuration (see below config.yml)
Get 'doctrine.odm.mongodb.document_manager' from container in
HelloController action
And when I am trying to run the application MongoConnectionException is thrown.
Can anyone help me to solve this problem?
AppKernel.php
public function registerBundles()
{
$bundles = array(
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle(),
new Sensio\HelloBundle\HelloBundle()
);
return $bundles;
}
config.yml
framework:
charset: UTF-8
router: { resource: "%kernel.root_dir%/config/routing.yml" }
templating: { engines: ['twig'] }
## Doctrine Configuration
doctrine_mongo_db:
server: mongodb://root:root#192.168.0.111:27017
default_database: test
options: { connect: true }
mappings:
HelloBundle: { type: annotation, dir: Document }
# Twig Configuration
twig:
debug: %kernel.debug%
strict_variables: %kernel.debug%
HelloController.php
/* #var $dm \Doctrine\ODM\MongoDB\DocumentManager */
$dm = $this->get('doctrine.odm.mongodb.document_manager');
Exception (line 96)
connecting to failed: Transport endpoint is not connected
in ~/vendor/doctrine-mongodb/lib/Doctrine/MongoDB/Connection.php line 96 ยป
93. if ($this->server) {
94. $this->mongo = new \Mongo($this->server, $this->options);
95. } else {
96. $this->mongo = new \Mongo();
97. }
The problem is in DoctrineMongoDBBundle configuration loading. The fix (https://github.com/fabpot/symfony/pull/740) should be merged soon.
For now you can use fixed method below.
public function load(array $configs, ContainerBuilder $container)
{
$mergedConfig = array();
foreach ($configs as $config) {
$mergedConfig = array_merge_recursive($mergedConfig, $config);
}
$this->doMongodbLoad($mergedConfig, $container);
}