how to use validationResover - flow-framework

Like shown here I want to use the validationResolver to dynamically validate user inputs in my App. Therefore I want to proove, if a condition is true in my controller. If the condition is true, I want to validate with an own validator.
For that I tried that:
public function createAction(Object $newObject) {
$TS = $newObject->getSomeProperty();
$ABT = $newObject->getSomeOtherProperty();
if ($TS === 'specialvalue') {
$validatorResolver->createValidator('Your.Package:Foo'));
}
But I get (of course) an 500-exception:
#1: Notice: Undefined variable: validatorResolver in /var/www...
Please give me a hint how to use the $validatorResolver.

I did it now this way:
public function createAction(Object $newObject) {
$TS = $newObject->getSomeProperty();
$ABT = $newObject->getSomeOtherProperty();
if ($ABT === 'specialvalue') {
$validatorResolver = new \TYPO3\Flow\Validation\ValidatorResolver();
$customValidator = $validatorResolver->createValidator('Your.Package:Foo');
$result = $customValidator->validate($TS);
if ($result->hasErrors()) {
$this->flashMessageContainer->addMessage(new \TYPO3\Flow\Error\Error('Here you can type in the error message!'));
$this->errorAction()->forwardToReferringRequest();
}
}
....
....
}

Related

Why does authenticate directive lead to "Error: type mismatch"?

I'm getting this error in my spray project.
Error:(41, 28) type mismatch;
found : spray.routing.authentication.ContextAuthenticator[co.s4n.authentication.entities.Usuario]
(which expands to) spray.routing.RequestContext => scala.concurrent.Future[scala.util.Either[spray.routing.Rejection,co.s4n.authentication.entities.Usuario]]
required: spray.routing.directives.AuthMagnet[?]
authenticate(validateToken) {
^
This is my TokenValidator trait
trait TokenValidator {
def validateToken: ContextAuthenticator[Usuario] = {
ctx =>
val header = ctx.request.headers.find(_.name == "Access_Token")
if (header isDefined) {
doAuth(header.get)
}
else {
Future(Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsMissing, List())))
}
}
def doAuth(header: HttpHeader): Future[Authentication[Usuario]] = {
Dao.validateToken(header.value).map {
case Some(usuario) => Right(usuario)
case None => Left(AuthenticationFailedRejection(AuthenticationFailedRejection.CredentialsRejected, List()))
}
}
}
and this is the line where I¡m getting that error
//#DELETE
//localhost:9090/authenticacion/users/{{userEmail}}
val `users/{{email}}` =
pathPrefix(`path-prefix`) {
pathPrefix(`users-path-prefix` / Segment) {
emailRef => {
delete {
authenticate(validateToken) { **HERE!!!!**
usuario =>
.....
}
}
}
}
}
Does anyone know what am I doing wrong?
Thak you all in advance!
The only thing I was missing was to have ExecutionContext in scope and import ExecutionContext.Implicits.global worked fine.
It's to let Futures work as they declare an implicit ExecutionContext parameter.
I know it's a long time since the actual question came, but the way to go with this for Spray is to determine the execution context with the tools that Spray provides:
implicit def executionContext = actorRefFactory.dispatcher

Common way to execute a stored proc from both ColdFusion and Railo

I think I've gotten the most simplest scenario built. I just want to pass it by everyone for a sanity check. Here's the idea:
GetErrorCodes.cfm does the following:
<cfscript>
response = new ErrorCodes().WhereXXX(); // ACF or Railo, doesn't matter
</cfscript>
ErrorCodes.cfc:
function WhereXXX() {
return new sproc().exec('app.GetErrorCodes'); // All my functions will do this instead of executing the sproc themselves.
}
sproc.cfc:
component {
function exec(procedure) {
local.result = {};
if (server.ColdFusion.productname == 'Railo') {
return new Railo().exec(arguments.procedure); // Has to be outside of sproc.cfc because ColdFusion throws a syntax error otherwise.
}
local.svc = new storedProc();
local.svc.setProcedure(arguments.procedure);
local.svc.addProcResult(name='qry');
try {
local.obj = local.svc.execute();
local.result.Prefix = local.obj.getPrefix();
local.result.qry = local.obj.getProcResultSets().qry;
} catch(any Exception) {
request.msg = Exception.Detail;
}
return local.result;
}
Railo.cfc:
component {
function exec(procedure) {
local.result = {};
try {
storedproc procedure=arguments.procedure result="local.result.Prefix" returncode="yes" {
procresult name="local.result.qry";
}
} catch(any Exception) {
request.msg = Exception.Message;
}
return local.result;
}
}
So I've been working on this all day, but tell me, is this a sane way to keep the source code the same if it's to be run on either a ColdFusion server or a Railo server?
Um... just use <cfstoredproc> instead of trying to use two different CFScript approaches that are mutually exclusive to each other of the CFML platforms.

Why am I getting this error in a basic Rails+Ember app?

I am trying to do a simple CRUD app using Ember + Rails and I'm getting the following error when trying to go to the /workouts route.
Error while loading route: TypeError {} ember.js?body=1:415
Uncaught TypeError: Object function () {
if (!wasApplied) {
Class.proto(); // prepare prototype...
}
o_defineProperty(this, GUID_KEY, undefinedDescriptor);
o_defineProperty(this, '_super', undefinedDescriptor);
var m = meta(this), proto = m.proto;
m.proto = this;
if (initMixins) {
// capture locally so we can clear the closed over variable
var mixins = initMixins;
initMixins = null;
this.reopen.apply(this, mixins);
}
if (initProperties) {
// capture locally so we can clear the closed over variable
var props = initProperties;
initProperties = null;
var concatenatedProperties = this.concatenatedProperties;
for (var i = 0, l = props.length; i < l; i++) {
var properties = props[i];
Ember.assert("Ember.Object.create no longer supports mixing in other definitions, use createWithMixins instead.", !(properties instanceof Ember.Mixin));
for (var keyName in properties) {
if (!properties.hasOwnProperty(keyName)) { continue; }
var value = properties[keyName],
IS_BINDING = Ember.IS_BINDING;
if (IS_BINDING.test(keyName)) {
var bindings = m.bindings;
if (!bindings) {
bindings = m.bindings = {};
} else if (!m.hasOwnProperty('bindings')) {
bindings = m.bindings = o_create(m.bindings);
}
bindings[keyName] = value;
}
var desc = m.descs[keyName];
Ember.assert("Ember.Object.create no longer supports defining computed properties.", !(value instanceof Ember.ComputedProperty));
Ember.assert("Ember.Object.create no longer supports defining methods that call _super.", !(typeof value === 'function' && value.toString().indexOf('._super') !== -1));
Ember.assert("`actions` must be provided at extend time, not at create time, when Ember.ActionHandler is used (i.e. views, controllers & routes).", !((keyName === 'actions') && Ember.ActionHandler.detect(this)));
if (concatenatedProperties && indexOf(concatenatedProperties, keyName) >= 0) {
var baseValue = this[keyName];
if (baseValue) {
if ('function' === typeof baseValue.concat) {
value = baseValue.concat(value);
} else {
value = Ember.makeArray(baseValue).concat(value);
}
} else {
value = Ember.makeArray(value);
}
}
if (desc) {
desc.set(this, keyName, value);
} else {
if (typeof this.setUnknownProperty === 'function' && !(keyName in this)) {
this.setUnknownProperty(keyName, value);
} else if (MANDATORY_SETTER) {
Ember.defineProperty(this, keyName, null, value); // setup mandatory setter
} else {
this[keyName] = value;
}
}
}
}
}
finishPartial(this, m);
this.init.apply(this, arguments);
m.proto = proto;
finishChains(this);
sendEvent(this, "init");
} has no method 'find'
My code is located here: https://github.com/ecl1pse/ember-workouts
What am I doing wrong?
Edit: Upon further investigation I believe the culprit is
EmberWorkouts.WorkoutsRoute = Ember.Route.extend(
model: -> EmberWorkouts.Workout.find()
This doesn't actually return anything. How do I debug from there?
If I replace that with this
EmberWorkouts.WorkoutsRoute = Ember.Route.extend
model: -> [{title: 'hi'}, {title: 'damn'}]
The view actually renders content.
How do I get the model to collect from Rails properly?
Ember Data's interface has changed a little with the current release:
You can clear out the store.js file entirely. Ember Data will automatically set up a data store for you using the REST Adapter (unless you tell it otherwise).
Use model: -> #store.find('workout') instead.
I tested this with your app and it works.
If you haven't read through the Ember Data Guide in the last week or two (it's changed a lot), I would spend a few minutes on it.
The fix for this error (as of ember-data 1.0.0.beta.6) for me was to make sure that the JSON returned from the server included an "id" field for each model, BUT not to explicitly declare the id when setting up the Ember DS.Model.
jbuilder template:
json.scans do
json.array! #scans do |scan|
json.id scan.id # This prop has to be there
json.name scan.name
end
end
Ember model:
EmberApp.Scan = DS.Model.extend(
// Don't include the id prop here
name: DS.attr("string")
)

displaying errors in grails without refreshing the page

I have a page with dynamic list boxes(selecting value from the first list populates the values in the second list box).
The validation errors for the list boxes are working fine, but while displaying the error messages the page is getting refreshed and the selected values are been set to initial status(need to select the values again in the list boxes)
The page is designed to add any number of list boxes using ajax calls, so adding and selecting the values again is going to be a rework.
Could you help me in displaying the validation errors and keeping the selected values as they are(previously I faced a similar situation which was resolved by replacing local variables of preprocess and postprocess with a global variable, this time no luck with that approach)
Any hints/help would be great
static constraints = {
deviceMapping(
validator: {val, obj ->
Properties dm = (Properties) val;
def deviceCheck = [:];
if (obj.customErrorMessage == null) {
for (def device : dm) {
if (device.key == null || "null".equalsIgnoreCase(device.key)) {
return ["notSelected"];
}
deviceCheck.put(device.key, "");
}
if (deviceCheck.size() != obj.properties["numberOfDevices"]) {
return ["multipleDevicesError"];
}
}
}
)
customErrorMessage (
validator: {
if ("sameDeviceMultipleTimes".equals(it)) {
return ['sameDeviceMultipleTimes']
}
}
)
}
public LinkedHashMap<String, Object> preProcess(sessionObject, params, request) {
Submission submission = (Submission) sessionObject;
def selectedFileName = sessionObject.fileName;
logger.debug("submission.deviceMapping :"+submission.deviceMapping)
try {
Customer customer = Customer.get(submission.customerId);
OperatingSystem operatingSystem = OperatingSystem.get(submission.operatingSystemId)
def ftpClientService = new FtpClientService();
def files = ftpClientService.listFilesInZip(customer.ftpUser, customer.ftpPassword, customer.ftpHost, customer.ftpToPackageDirectory, selectedFileName, operatingSystem, customer.ftpCustomerTempDirectory);
def terminalService = new TerminalService();
OperatingSystem os = OperatingSystem.get(submission.getOperatingSystemId());
def manufacturers = terminalService.getAllDeviceManufacturersForType(os.getType());
logger.debug("manufacturers after os type :"+manufacturers)
logger.debug("files in preprocess :"+files)
def devicesForFiles = [:]
files.each { file ->
def devicesForThisFile = [];
submission.deviceMapping.each { device ->
if (device.value == file.fileName) {
String manufacturer = terminalService.getManufacturerFromDevice("${device.key}");
def devicesForManufacturer = terminalService.getDevicesForManufacturerAndType(manufacturer, os.getType());
devicesForThisFile.push([device:device.key, manufacturer: manufacturer, devicesForManufacturer: devicesForManufacturer]);
}
}
devicesForFiles.put(file.fileName,devicesForThisFile);
}
logger.debug("devicesForFiles :"+devicesForFiles)
return [command: this, devicesForFiles: devicesForFiles, files: files, manufacturers: manufacturers];
} catch (Exception e) {
logger.warn("FTP threw exception");
logger.error("Exception", e);
this.errors.reject("mapGameToDeviceCommand.ftp.connectionTimeOut","A temporary FTP error occurred");
return [command: this];
}
}
public LinkedHashMap<String, Object> postProcess(sessionObject, params, request) {
Submission submission = (Submission) sessionObject;
Properties devices = params.devices;
Properties files = params.files;
mapping = devices.inject( [:] ) { map, dev ->
// Get the first part of the version (up to the first dot)
def v = dev.key.split( /\./ )[ 0 ]
map << [ (dev.value): files[ v ] ]
}
deviceMapping = new Properties();
params.files.eachWithIndex { file, i ->
def device = devices["${file.key}"];
if (deviceMapping.containsKey("${device}")) {
this.errors.reject("You cannot use the same device more than once");
return [];
//customErrorMessage = "sameDeviceMultipleTimes";
}
deviceMapping.put("${device}", "${file.value}");
}
if (params.devices != null) {
this.numberOfDevices = params.devices.size(); //Used for the custom validator later on
} else {
this.numberOfDevices = 0;
}
//logger.debug("device mapping :"+deviceMapping);
submission.deviceMapping = mapping;
return [command: this, deviceMapping: mapping, devicesForFiles: devicesForFiles ];
}
}
The problem is in your gsp page. Be sure that all field are initialised with a value
<g:text value="${objectInstance.fieldname}" ... />
Also the way it is selecting values is through id, so be sure to set it as well:
<g:text value="${objectInstance.fieldname}" id=${device.manufacturer.id} ... />

removeFrom* not working and with no errors

I have what I think is a simple problem but have been unable to solve...
For some reason I have a controller that uses removeFrom*.save() which throws no errors but does not do anything.
Running
Grails 1.2
Linux/Ubuntu
The following application is stripped down to reproduce the problem...
I have two domain objects via create-domain-class
- Job (which has many notes)
- Note (which belongs to Job)
I have 3 controllers via create-controller
- JobController (running scaffold)
- NoteController (running scaffold)
- JSONNoteController
JSONNoteController has one primary method deleteItem which aims to remove/delete a note.
It does the following
some request validation
removes the note from the job - jobInstance.removeFromNotes(noteInstance).save()
deletes the note - noteInstance.delete()
return a status and remaining data set as a json response.
When I run this request - I get no errors but it appears that jobInstance.removeFromNotes(noteInstance).save() does nothing and does not throw any exception etc.
How can I track down why??
I've attached a sample application that adds some data via BootStrap.groovy.
Just run it - you can view the data via the default scaffold views.
If you run linux, from a command line you can run the following
GET "http://localhost:8080/gespm/JSONNote/deleteItem?job.id=1&note.id=2"
You can run it over and over again and nothing different happens. You could also paste the URL into your webbrowser if you're running windows.
Please help - I'm stuck!!!
Code is here link text
Note Domain
package beachit
class Note
{
Date dateCreated
Date lastUpdated
String note
static belongsTo = Job
static constraints =
{
}
String toString()
{
return note
}
}
Job Domain
package beachit
class Job
{
Date dateCreated
Date lastUpdated
Date createDate
Date startDate
Date completionDate
List notes
static hasMany = [notes : Note]
static constraints =
{
}
String toString()
{
return createDate.toString() + " " + startDate.toString();
}
}
JSONNoteController
package beachit
import grails.converters.*
import java.text.*
class JSONNoteController
{
def test = { render "foobar test" }
def index = { redirect(action:listAll,params:params) }
// the delete, save and update actions only accept POST requests
//static allowedMethods = [delete:'POST', save:'POST', update:'POST']
def getListService =
{
def message
def status
def all = Note.list()
return all
}
def getListByJobService(jobId)
{
def message
def status
def jobInstance = Job.get(jobId)
def all
if(jobInstance)
{
all = jobInstance.notes
}
else
{
log.debug("getListByJobService job not found for jobId " + jobId)
}
return all
}
def listAll =
{
def message
def status
def listView
listView = getListService()
message = "Done"
status = 0
def response = ['message': message, 'status':status, 'list': listView]
render response as JSON
}
def deleteItem =
{
def jobInstance
def noteInstance
def message
def status
def jobId = 0
def noteId = 0
def instance
def listView
def response
try
{
jobId = Integer.parseInt(params.job?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in jobId " + params.job?.id)
log.debug(ex.getMessage())
}
if (jobId && jobId > 0 )
{
jobInstance = Job.get(jobId)
if(jobInstance)
{
if (jobInstance.notes)
{
try
{
noteId = Integer.parseInt(params.note?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in noteId " + params.note?.id)
log.debug(ex.getMessage())
}
log.debug("note id =" + params.note.id)
if (noteId && noteId > 0 )
{
noteInstance = Note.get(noteId)
if (noteInstance)
{
try
{
jobInstance.removeFromNotes(noteInstance).save()
noteInstance.delete()
message = "note ${noteId} deleted"
status = 0
}
catch(org.springframework.dao.DataIntegrityViolationException e)
{
message = "Note ${noteId} could not be deleted - references to it exist"
status = 1
}
/*
catch(Exception e)
{
message = "Some New Error!!!"
status = 10
}
*/
}
else
{
message = "Note not found with id ${noteId}"
status = 2
}
}
else
{
message = "Couldn't recognise Note id : ${params.note?.id}"
status = 3
}
}
else
{
message = "No Notes found for Job : ${jobId}"
status = 4
}
}
else
{
message = "Job not found with id ${jobId}"
status = 5
}
listView = getListByJobService(jobId)
} // if (jobId)
else
{
message = "Couldn't recognise Job id : ${params.job?.id}"
status = 6
}
response = ['message': message, 'status':status, 'list' : listView]
render response as JSON
} // deleteNote
}
I got it working... though I cannot explain why.
I replaced the following line in deleteItem
noteInstance = Note.get(noteId)
with the following
noteInstance = jobInstance.notes.find { it.id == noteId }
For some reason the jobInstance.removeFromNotes works with the object returned by that method instead of .get
What makes it stranger is that all other gorm functions (not sure about the dynamic ones actually) work against the noteInstance.get(noteId) method.
At least it's working though!!
See this thread: http://grails.1312388.n4.nabble.com/GORM-doesn-t-inject-hashCode-and-equals-td1370512.html
I would recommend using a base class for your domain objects like this:
abstract class BaseDomain {
#Override
boolean equals(o) {
if(this.is(o)) return true
if(o == null) return false
// hibernate creates dynamic subclasses, so
// checking o.class == class would fail most of the time
if(!o.getClass().isAssignableFrom(getClass()) &&
!getClass().isAssignableFrom(o.getClass())) return false
if(ident() != null) {
ident() == o.ident()
} else {
false
}
}
#Override
int hashCode() {
ident()?.hashCode() ?: 0
}
}
That way, any two objects with the same non-null database id will be considered equal.
I just had this same issue come up. The removeFrom function succeeded, the save succeeded but the physical record in the database wasn't deleted. Here's what worked for me:
class BasicProfile {
static hasMany = [
post:Post
]
}
class Post {
static belongsTo = [basicProfile:BasicProfile]
}
class BasicProfileController {
...
def someFunction
...
BasicProfile profile = BasicProfile.findByUser(user)
Post post = profile.post?.find{it.postType == command.postType && it.postStatus == command.postStatus}
if (post) {
profile.removeFromPost(post)
post.delete()
}
profile.save()
}
So it was the combination of the removeFrom, followed by a delete on the associated domain, and then a save on the domain object.

Resources