问:
java.lang.IllegalArgumentException: Property [password] is not a valid property of class com.wolf.User in Grails
I'm trying to "run-app" my Grails app, but when it starts to add User and Admin via BootStrap it gives me this error

```<code>    Creating admin user
Fresh Database. Creating ADMIN user.
2017-12-05 19:20:48.191 ERROR --- [           main] o.g.events.gorm.GormAnnotatedListener    : Error triggering event [org.grails.datastore.mapping.engine.event.PreInsertEvent[source=org.grails.orm.hibernate.HibernateDatastore@6491006]] for listener [public void com.wolf.UserPasswordEncoderListener.onPreInsertEvent(org.grails.datastore.mapping.engine.event.PreInsertEvent)]: Property [password] is not a valid property of class com.wolf.User

java.lang.IllegalArgumentException: Property [password] is not a valid property of class com.wolf.User
    at org.grails.datastore.mapping.reflect.FieldEntityAccess$FieldEntityReflector.getPropertyWriter(FieldEntityAccess.java:279)
    at org.grails.datastore.mapping.reflect.FieldEntityAccess.setProperty(FieldEntityAccess.java:90)
    at org.grails.datastore.mapping.engine.ModificationTrackingEntityAccess.setProperty(ModificationTrackingEntityAccess.groovy:41)
    at com.wolf.UserPasswordEncoderListener.encodePasswordForEvent(UserPasswordEncoderListener.groovy:31)
    at com.wolf.UserPasswordEncoderListener.onPreInsertEvent(UserPasswordEncoderListener.groovy:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)
    at org.grails.events.gorm.GormAnnotatedListener$Trait$Helper.dispatch(GormAnnotatedListener.groovy:39)
    at com.wolf.UserPasswordEncoderListener.dispatch(UserPasswordEncoderListener.groovy)
    at org.grails.events.gorm.GormEventDispatcher.onPersistenceEvent(GormEventDispatcher.groovy:52)
    at org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:51)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
    at org.grails.datastore.gorm.events.ConfigurableApplicationContextEventPublisher.publishEvent(ConfigurableApplicationContextEventPublisher.groovy:30)
    at org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.publishEvent(ClosureEventTriggeringInterceptor.java:258)
    at org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.onPreInsert(ClosureEventTriggeringInterceptor.java:166)
    at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:197)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:75)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:623)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:277)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:258)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:303)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.onSaveOrUpdate(ClosureEventTriggeringInterceptor.java:126)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:651)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:643)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:638)
    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi$_performSave_closure3.doCall(AbstractHibernateGormInstanceApi.groovy:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at groovy.lang.Closure.call(Closure.java:414)
    at org.codehaus.groovy.runtime.ConvertedClosure.invokeCustom(ConvertedClosure.java:54)
    at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:124)
    at com.sun.proxy.$Proxy123.doInHibernate(Unknown Source)
    at org.grails.orm.hibernate.GrailsHibernateTemplate.doExecute(GrailsHibernateTemplate.java:299)
    at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:243)
    at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:117)
    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi.performSave(AbstractHibernateGormInstanceApi.groovy:242)
    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi.save(AbstractHibernateGormInstanceApi.groovy:159)
    at org.grails.datastore.gorm.GormEntity$Trait$Helper.save(GormEntity.groovy:151)
    at org.grails.datastore.gorm.GormEntity$Trait$Helper$save$1.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at com.wolf.User.save(User.groovy)
    at com.wolf.User.save(User.groovy)
    at org.grails.datastore.gorm.GormEntity$save.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at hubbub.BootStrap.createAdminUserIfRequired(BootStrap.groovy:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:158)
    at hubbub.BootStrap$_closure1.doCall(BootStrap.groovy:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1087)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at groovy.lang.Closure.call(Closure.java:414)
    at groovy.lang.Closure.call(Closure.java:408)
    at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:535)
    at grails.util.Environment.executeForEnvironment(Environment.java:528)
    at grails.util.Environment.executeForCurrentEnvironment(Environment.java:504)
    at org.grails.web.servlet.boostrap.DefaultGrailsBootstrapClass.callInit(DefaultGrailsBootstrapClass.java:74)
    at org.grails.web.servlet.context.GrailsConfigUtils.executeGrailsBootstraps(GrailsConfigUtils.java:65)
    at org.grails.plugins.web.servlet.context.BootStrapClassRunner.onStartup(BootStrapClassRunner.groovy:53)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy:261)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:387)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:374)
    at grails.boot.GrailsApp$run.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at hubbub.Application.main(Application.groovy:8)
</code>```

This started to happen when I installed Spring Security Core Plugin and changed my domain "User" property "password" with "passwordHash".
    Here is the User domain:

```<code>    package com.wolf

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
import grails.compiler.GrailsCompileStatic

class User implements Serializable {

    String loginId
    String passwordHash
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    Date dateCreated

    static transients = ['springSecurityService']
    static hasOne = [ profile: Profile ]
    static hasMany = [ posts: Post, tags: Tag, following: User ]

    Set<Role> getAuthorities() {
        (UserRole.findAllByUser(this) as List<UserRole>)*.role as Set<Role>
    }

    static constraints = {
        loginId size: 3..20, unique: true, blank: false
        tags()
        posts()
        profile nullable: true
    }

    static mapping = {
        posts sort: "dateCreated", order: "desc"
    }

    String toString() { return "User $loginId (id: $id)" }
    String getDisplayString() { return loginId }
}
</code>```

And last, here is the BootStrap code:

```<code>import static java.util.Calendar.*
class BootStrap {
def springSecurityService

    def init = { servletContext ->
        environments {
            development {
                if (!Post.count()) createSampleData()
            }
            test {
                if (!Post.count()) createSampleData()
            }
        }

//         Admin user is required for all environments
        createAdminUserIfRequired()
    }

    private createSampleData() {
        println "Creating sample data"

        def now = new Date()
        def chuck = new User(
                loginId: "chuck_norris",
                passwordHash: springSecurityService.encodePassword("highkick"),
                profile: new Profile(fullName: "Chuck Norris", email: "chuck@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def glen = new User(
                loginId: "glen",
                passwordHash: springSecurityService.encodePassword("sheldon"),
                profile: new Profile(fullName: "Glen Smith", email: "glen@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def peter = new User(
                loginId: "peter",
                passwordHash: springSecurityService.encodePassword("mandible"),
                profile: new Profile(fullName: "Peter Ledbrook", email: "peter@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def frankie = new User(
                loginId: "frankie",
                passwordHash: springSecurityService.encodePassword("testing"),
                profile: new Profile(fullName: "Frankie Goes to Hollywood", email: "frankie@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def sara = new User(
                loginId: "sara",
                passwordHash: springSecurityService.encodePassword("crikey"),
                profile: new Profile(fullName: "Sara Miles", email: "sara@nowhere.net"),
                dateCreated: now - 2).save(failOnError: true)
        def phil = new User(
                loginId: "phil",
                passwordHash: springSecurityService.encodePassword("thomas"),
                profile: new Profile(fullName: "Phil Potts", email: "phil@nowhere.net"),
                dateCreated: now)
        def dillon = new User(loginId: "dillon",
                passwordHash: springSecurityService.encodePassword("crikey"),
                profile: new Profile(fullName: "Dillon Jessop", email: "dillon@nowhere.net"),
                dateCreated: now - 2).save(failOnError: true)

        chuck.addToFollowing(phil)
        chuck.addToPosts(content: "Been working my roundhouse kicks.")
        chuck.addToPosts(content: "Working on a few new moves. Bit sluggish today.")
        chuck.addToPosts(content: "Tinkering with the hubbub app.")
        chuck.save(failOnError: true)

        phil.addToFollowing(frankie)
        phil.addToFollowing(sara)
        phil.save(failOnError: true)

        phil.addToPosts(content: "Very first post")
        phil.addToPosts(content: "Second post")
        phil.addToPosts(content: "Time for a BBQ!")
        phil.addToPosts(content: "Writing a very very long book")
        phil.addToPosts(content: "Tap dancing")
        phil.addToPosts(content: "Pilates is killing me")
        phil.save(failOnError: true)

        sara.addToPosts(content: "My first post")
        sara.addToPosts(content: "Second post")
        sara.addToPosts(content: "Time for a BBQ!")
        sara.addToPosts(content: "Writing a very very long book")
        sara.addToPosts(content: "Tap dancing")
        sara.addToPosts(content: "Pilates is killing me")
        sara.save(failOnError: true)

        dillon.addToPosts(content: "Pilates is killing me as well")
        dillon.save(failOnError: true, flush: true)

        // We have to update the 'dateCreated' field after the initial save to
        // work around Grails' auto-timestamping feature. Note that this trick
        // won't work for the 'lastUpdated' field.
        def postsAsList = phil.posts as List
        postsAsList[0].addToTags(user: phil, name: "groovy")
        postsAsList[0].addToTags(user: phil, name: "grails")
        postsAsList[0].dateCreated = now.updated(year: 2004, month: MAY)

        postsAsList[1].addToTags(user: phil, name: "grails")
        postsAsList[1].addToTags(user: phil, name: "ramblings")
        postsAsList[1].addToTags(user: phil, name: "second")
        postsAsList[1].dateCreated = now.updated(year: 2007, month: FEBRUARY, date: 13)

        postsAsList[2].addToTags(user: phil, name: "groovy")
        postsAsList[2].addToTags(user: phil, name: "bbq")
        postsAsList[2].dateCreated = now.updated(year: 2009, month: OCTOBER)

        postsAsList[3].addToTags(user: phil, name: "groovy")
        postsAsList[3].dateCreated = now.updated(year: 2011, month: MAY, date: 1)

        postsAsList[4].dateCreated = now.updated(year: 2011, month: DECEMBER, date: 4)
        postsAsList[5].dateCreated = now.updated(year: 2012, date: 10)
        phil.save(failOnError: true)

        postsAsList = sara.posts as List
        postsAsList[0].dateCreated = now.updated(year: 2007, month: MAY)
        postsAsList[1].dateCreated = now.updated(year: 2008, month: APRIL, date: 13)
        postsAsList[2].dateCreated = now.updated(year: 2008, month: APRIL, date: 24)
        postsAsList[3].dateCreated = now.updated(year: 2011, month: NOVEMBER, date: 8)
        postsAsList[4].dateCreated = now.updated(year: 2011, month: DECEMBER, date: 4)
        postsAsList[5].dateCreated = now.updated(year: 2012, month: AUGUST, date: 1)

        sara.dateCreated = now - 2
        sara.save(failOnError: true)

        dillon.dateCreated = now - 2
        dillon.save(failOnError: true, flush: true)
    }

    private createAdminUserIfRequired() {
        println "Creating admin user"
        if (!User.findByLoginId("admin")) {
            println "Fresh Database. Creating ADMIN user."

            def profile = new Profile(email: "admin@yourhost.com", fullName: "Administrator")
            def adminRole = new Role(authority: "ROLE_ADMIN").save(failOnError: true)
            def adminUser = new User(
                    loginId: "admin",
                    passwordHash: springSecurityService.encodePassword("secret"),
                    profile: profile,
                    enabled: true).save(failOnError: true)
            UserRole.create adminUser, adminRole, true
        }
        else {
            println "Existing admin user, skipping creation"
        }
    }
}
</code>```

I don't know if it's related to Database Migration Plugin, but I checked every domain and no one has "password" as property.

答:
I found the solution... in "main/groovy/package/UserPasswordEncoderListener "encorePasswordForEvent" method had the old property "password" instead of "passwordHash".

Here's the method with old "password" property:

```<code>private void encodePasswordForEvent(AbstractPersistenceEvent event) {
    if (event.entityObject instanceof User) {
        User u = event.entityObject as User
        if (u.passwordHash && ((event instanceof  PreInsertEvent) || (event instanceof PreUpdateEvent && u.isDirty('password')))) {
            event.getEntityAccess().setProperty('password', encodePassword(u.passwordHash))
        }
    }
}
</code>```

Here's with the new "passwordHash" property:

```<code>private void encodePasswordForEvent(AbstractPersistenceEvent event) {
    if (event.entityObject instanceof User) {
        User u = event.entityObject as User
        if (u.passwordHash && ((event instanceof  PreInsertEvent) || (event instanceof PreUpdateEvent && u.isDirty('passwordHash')))) {
            event.getEntityAccess().setProperty('passwordHash', encodePassword(u.passwordHash))
        }
    }
}
</code>```

Body:
I'm trying to "run-app" my Grails app, but when it starts to add User and Admin via BootStrap it gives me this error

    Creating admin user
Fresh Database. Creating ADMIN user.
2017-12-05 19:20:48.191 ERROR --- [           main] o.g.events.gorm.GormAnnotatedListener    : Error triggering event [org.grails.datastore.mapping.engine.event.PreInsertEvent[source=org.grails.orm.hibernate.HibernateDatastore@6491006]] for listener [public void com.wolf.UserPasswordEncoderListener.onPreInsertEvent(org.grails.datastore.mapping.engine.event.PreInsertEvent)]: Property [password] is not a valid property of class com.wolf.User

java.lang.IllegalArgumentException: Property [password] is not a valid property of class com.wolf.User
    at org.grails.datastore.mapping.reflect.FieldEntityAccess$FieldEntityReflector.getPropertyWriter(FieldEntityAccess.java:279)
    at org.grails.datastore.mapping.reflect.FieldEntityAccess.setProperty(FieldEntityAccess.java:90)
    at org.grails.datastore.mapping.engine.ModificationTrackingEntityAccess.setProperty(ModificationTrackingEntityAccess.groovy:41)
    at com.wolf.UserPasswordEncoderListener.encodePasswordForEvent(UserPasswordEncoderListener.groovy:31)
    at com.wolf.UserPasswordEncoderListener.onPreInsertEvent(UserPasswordEncoderListener.groovy:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)
    at org.grails.events.gorm.GormAnnotatedListener$Trait$Helper.dispatch(GormAnnotatedListener.groovy:39)
    at com.wolf.UserPasswordEncoderListener.dispatch(UserPasswordEncoderListener.groovy)
    at org.grails.events.gorm.GormEventDispatcher.onPersistenceEvent(GormEventDispatcher.groovy:52)
    at org.grails.datastore.mapping.engine.event.AbstractPersistenceEventListener.onApplicationEvent(AbstractPersistenceEventListener.java:51)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
    at org.grails.datastore.gorm.events.ConfigurableApplicationContextEventPublisher.publishEvent(ConfigurableApplicationContextEventPublisher.groovy:30)
    at org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.publishEvent(ClosureEventTriggeringInterceptor.java:258)
    at org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.onPreInsert(ClosureEventTriggeringInterceptor.java:166)
    at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:197)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:75)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:623)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:277)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:258)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:303)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:318)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:275)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:97)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.grails.orm.hibernate.support.ClosureEventTriggeringInterceptor.onSaveOrUpdate(ClosureEventTriggeringInterceptor.java:126)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:651)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:643)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:638)
    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi$_performSave_closure3.doCall(AbstractHibernateGormInstanceApi.groovy:243)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at groovy.lang.Closure.call(Closure.java:414)
    at org.codehaus.groovy.runtime.ConvertedClosure.invokeCustom(ConvertedClosure.java:54)
    at org.codehaus.groovy.runtime.ConversionHandler.invoke(ConversionHandler.java:124)
    at com.sun.proxy.$Proxy123.doInHibernate(Unknown Source)
    at org.grails.orm.hibernate.GrailsHibernateTemplate.doExecute(GrailsHibernateTemplate.java:299)
    at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:243)
    at org.grails.orm.hibernate.GrailsHibernateTemplate.execute(GrailsHibernateTemplate.java:117)
    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi.performSave(AbstractHibernateGormInstanceApi.groovy:242)
    at org.grails.orm.hibernate.AbstractHibernateGormInstanceApi.save(AbstractHibernateGormInstanceApi.groovy:159)
    at org.grails.datastore.gorm.GormEntity$Trait$Helper.save(GormEntity.groovy:151)
    at org.grails.datastore.gorm.GormEntity$Trait$Helper$save$1.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at com.wolf.User.save(User.groovy)
    at com.wolf.User.save(User.groovy)
    at org.grails.datastore.gorm.GormEntity$save.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:125)
    at hubbub.BootStrap.createAdminUserIfRequired(BootStrap.groovy:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:158)
    at hubbub.BootStrap$_closure1.doCall(BootStrap.groovy:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1427)
    at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
    at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
    at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:294)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1087)
    at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
    at groovy.lang.Closure.call(Closure.java:414)
    at groovy.lang.Closure.call(Closure.java:408)
    at grails.util.Environment.evaluateEnvironmentSpecificBlock(Environment.java:535)
    at grails.util.Environment.executeForEnvironment(Environment.java:528)
    at grails.util.Environment.executeForCurrentEnvironment(Environment.java:504)
    at org.grails.web.servlet.boostrap.DefaultGrailsBootstrapClass.callInit(DefaultGrailsBootstrapClass.java:74)
    at org.grails.web.servlet.context.GrailsConfigUtils.executeGrailsBootstraps(GrailsConfigUtils.java:65)
    at org.grails.plugins.web.servlet.context.BootStrapClassRunner.onStartup(BootStrapClassRunner.groovy:53)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy:261)
    at grails.boot.config.GrailsApplicationPostProcessor.onApplicationEvent(GrailsApplicationPostProcessor.groovy)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:167)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:393)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:347)
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:883)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:144)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:83)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:387)
    at grails.boot.GrailsApp.run(GrailsApp.groovy:374)
    at grails.boot.GrailsApp$run.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
    at hubbub.Application.main(Application.groovy:8)

This started to happen when I installed Spring Security Core Plugin and changed my domain "User" property "password" with "passwordHash".
    Here is the User domain:

    package com.wolf

import groovy.transform.EqualsAndHashCode
import groovy.transform.ToString
import grails.compiler.GrailsCompileStatic

class User implements Serializable {

    String loginId
    String passwordHash
    boolean enabled = true
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    Date dateCreated

    static transients = ['springSecurityService']
    static hasOne = [ profile: Profile ]
    static hasMany = [ posts: Post, tags: Tag, following: User ]

    Set<Role> getAuthorities() {
        (UserRole.findAllByUser(this) as List<UserRole>)*.role as Set<Role>
    }

    static constraints = {
        loginId size: 3..20, unique: true, blank: false
        tags()
        posts()
        profile nullable: true
    }

    static mapping = {
        posts sort: "dateCreated", order: "desc"
    }

    String toString() { return "User $loginId (id: $id)" }
    String getDisplayString() { return loginId }
}

And last, here is the BootStrap code:

import static java.util.Calendar.*
class BootStrap {
def springSecurityService

    def init = { servletContext ->
        environments {
            development {
                if (!Post.count()) createSampleData()
            }
            test {
                if (!Post.count()) createSampleData()
            }
        }

//         Admin user is required for all environments
        createAdminUserIfRequired()
    }

    private createSampleData() {
        println "Creating sample data"

        def now = new Date()
        def chuck = new User(
                loginId: "chuck_norris",
                passwordHash: springSecurityService.encodePassword("highkick"),
                profile: new Profile(fullName: "Chuck Norris", email: "chuck@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def glen = new User(
                loginId: "glen",
                passwordHash: springSecurityService.encodePassword("sheldon"),
                profile: new Profile(fullName: "Glen Smith", email: "glen@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def peter = new User(
                loginId: "peter",
                passwordHash: springSecurityService.encodePassword("mandible"),
                profile: new Profile(fullName: "Peter Ledbrook", email: "peter@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def frankie = new User(
                loginId: "frankie",
                passwordHash: springSecurityService.encodePassword("testing"),
                profile: new Profile(fullName: "Frankie Goes to Hollywood", email: "frankie@nowhere.net"),
                dateCreated: now).save(failOnError: true)
        def sara = new User(
                loginId: "sara",
                passwordHash: springSecurityService.encodePassword("crikey"),
                profile: new Profile(fullName: "Sara Miles", email: "sara@nowhere.net"),
                dateCreated: now - 2).save(failOnError: true)
        def phil = new User(
                loginId: "phil",
                passwordHash: springSecurityService.encodePassword("thomas"),
                profile: new Profile(fullName: "Phil Potts", email: "phil@nowhere.net"),
                dateCreated: now)
        def dillon = new User(loginId: "dillon",
                passwordHash: springSecurityService.encodePassword("crikey"),
                profile: new Profile(fullName: "Dillon Jessop", email: "dillon@nowhere.net"),
                dateCreated: now - 2).save(failOnError: true)

        chuck.addToFollowing(phil)
        chuck.addToPosts(content: "Been working my roundhouse kicks.")
        chuck.addToPosts(content: "Working on a few new moves. Bit sluggish today.")
        chuck.addToPosts(content: "Tinkering with the hubbub app.")
        chuck.save(failOnError: true)

        phil.addToFollowing(frankie)
        phil.addToFollowing(sara)
        phil.save(failOnError: true)

        phil.addToPosts(content: "Very first post")
        phil.addToPosts(content: "Second post")
        phil.addToPosts(content: "Time for a BBQ!")
        phil.addToPosts(content: "Writing a very very long book")
        phil.addToPosts(content: "Tap dancing")
        phil.addToPosts(content: "Pilates is killing me")
        phil.save(failOnError: true)

        sara.addToPosts(content: "My first post")
        sara.addToPosts(content: "Second post")
        sara.addToPosts(content: "Time for a BBQ!")
        sara.addToPosts(content: "Writing a very very long book")
        sara.addToPosts(content: "Tap dancing")
        sara.addToPosts(content: "Pilates is killing me")
        sara.save(failOnError: true)

        dillon.addToPosts(content: "Pilates is killing me as well")
        dillon.save(failOnError: true, flush: true)

        // We have to update the 'dateCreated' field after the initial save to
        // work around Grails' auto-timestamping feature. Note that this trick
        // won't work for the 'lastUpdated' field.
        def postsAsList = phil.posts as List
        postsAsList[0].addToTags(user: phil, name: "groovy")
        postsAsList[0].addToTags(user: phil, name: "grails")
        postsAsList[0].dateCreated = now.updated(year: 2004, month: MAY)

        postsAsList[1].addToTags(user: phil, name: "grails")
        postsAsList[1].addToTags(user: phil, name: "ramblings")
        postsAsList[1].addToTags(user: phil, name: "second")
        postsAsList[1].dateCreated = now.updated(year: 2007, month: FEBRUARY, date: 13)

        postsAsList[2].addToTags(user: phil, name: "groovy")
        postsAsList[2].addToTags(user: phil, name: "bbq")
        postsAsList[2].dateCreated = now.updated(year: 2009, month: OCTOBER)

        postsAsList[3].addToTags(user: phil, name: "groovy")
        postsAsList[3].dateCreated = now.updated(year: 2011, month: MAY, date: 1)

        postsAsList[4].dateCreated = now.updated(year: 2011, month: DECEMBER, date: 4)
        postsAsList[5].dateCreated = now.updated(year: 2012, date: 10)
        phil.save(failOnError: true)

        postsAsList = sara.posts as List
        postsAsList[0].dateCreated = now.updated(year: 2007, month: MAY)
        postsAsList[1].dateCreated = now.updated(year: 2008, month: APRIL, date: 13)
        postsAsList[2].dateCreated = now.updated(year: 2008, month: APRIL, date: 24)
        postsAsList[3].dateCreated = now.updated(year: 2011, month: NOVEMBER, date: 8)
        postsAsList[4].dateCreated = now.updated(year: 2011, month: DECEMBER, date: 4)
        postsAsList[5].dateCreated = now.updated(year: 2012, month: AUGUST, date: 1)

        sara.dateCreated = now - 2
        sara.save(failOnError: true)

        dillon.dateCreated = now - 2
        dillon.save(failOnError: true, flush: true)
    }

    private createAdminUserIfRequired() {
        println "Creating admin user"
        if (!User.findByLoginId("admin")) {
            println "Fresh Database. Creating ADMIN user."

            def profile = new Profile(email: "admin@yourhost.com", fullName: "Administrator")
            def adminRole = new Role(authority: "ROLE_ADMIN").save(failOnError: true)
            def adminUser = new User(
                    loginId: "admin",
                    passwordHash: springSecurityService.encodePassword("secret"),
                    profile: profile,
                    enabled: true).save(failOnError: true)
            UserRole.create adminUser, adminRole, true
        }
        else {
            println "Existing admin user, skipping creation"
        }
    }
}

I don't know if it's related to Database Migration Plugin, but I checked every domain and no one has "password" as property.

Body:
I found the solution... in "main/groovy/package/UserPasswordEncoderListener "encorePasswordForEvent" method had the old property "password" instead of "passwordHash".

Here's the method with old "password" property:

private void encodePasswordForEvent(AbstractPersistenceEvent event) {
    if (event.entityObject instanceof User) {
        User u = event.entityObject as User
        if (u.passwordHash && ((event instanceof  PreInsertEvent) || (event instanceof PreUpdateEvent && u.isDirty('password')))) {
            event.getEntityAccess().setProperty('password', encodePassword(u.passwordHash))
        }
    }
}

Here's with the new "passwordHash" property:

private void encodePasswordForEvent(AbstractPersistenceEvent event) {
    if (event.entityObject instanceof User) {
        User u = event.entityObject as User
        if (u.passwordHash && ((event instanceof  PreInsertEvent) || (event instanceof PreUpdateEvent && u.isDirty('passwordHash')))) {
            event.getEntityAccess().setProperty('passwordHash', encodePassword(u.passwordHash))
        }
    }
}


来源: stackexchange

问:
How to add 3rd party gradle library in android.mk and build
Im working on building an android application to run in an AOSP project.Right now everything working as expected,Im able to load the android os in to the hardware and on launching the android application it opens and everything seems to be ok.

Android mk file used in the android application

```<code>LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional samples

LOCAL_PACKAGE_NAME := MyApp
LOCAL_CERTIFICATE := platform
LOCAL_DEX_PREOPT := false
LOCAL_PRIVILEGED_MODULE := true
LOCAL_AAPT_FLAGS := --auto-add-overlay
LOCAL_PROGUARD_ENABLED := disabled

LOCAL_PACKAGE_NAME := com.myapplication.myapp
LOCAL_MANIFEST_FILE := app/src/main/AndroidManifest.xml
LOCAL_RESOURCE_DIR += $(LOCAL_PATH)/app/src/main/res/
LOCAL_SRC_FILES := $(call all-java-files-under, app/src/main/)

LOCAL_CERTIFICATE := platform
LOCAL_PRIVILEGED_MODULE := true
LOCAL_DEX_PREOPT := false
LOCAL_ASSET_DIR := $(LOCAL_PATH)/app/src/main/assets/

LOCAL_AAPT_FLAGS := --auto-add-overlay\
LOCAL_PROGUARD_FLAG_FILES := app/proguard-rules.pro pylauncher/proguard-rules.pro

include $(BUILD_PACKAGE)
include $(call all-makefiles-under, $(LOCAL_PATH))
</code>```

Now i want to show an image in android application from a url.Im planing to use the library picasso. I have added the following in to the applications's build.gradle

```<code>compile 'com.squareup.picasso:picasso:2.5.2'
</code>```

I have tested the application in a mobile phone and it is working fine.But when i build the android application from AOSP project import files from the picasso library are not recognizing.

Can some one guide me to update the android.mk file to to mention the 3rd party library

PS: Im very new to this domain and please let me know if you want more input from my side

答: There is an alternate solution for this problem. You can add your pre-built apk into the build. here is the link on how to add apk into the build. How do I add APKs in an AOSP build?</p>

ContentLicense: CC BY-SA 3.0

Body:
Im working on building an android application to run in an AOSP project.Right now everything working as expected,Im able to load the android os in to the hardware and on launching the android application it opens and everything seems to be ok.

Android mk file used in the android application

LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)

LOCAL_MODULE_TAGS := optional samples

LOCAL_PACKAGE_NAME := MyApp
LOCAL_CERTIFICATE := platform
LOCAL_DEX_PREOPT := false
LOCAL_PRIVILEGED_MODULE := true
LOCAL_AAPT_FLAGS := --auto-add-overlay
LOCAL_PROGUARD_ENABLED := disabled

LOCAL_PACKAGE_NAME := com.myapplication.myapp
LOCAL_MANIFEST_FILE := app/src/main/AndroidManifest.xml
LOCAL_RESOURCE_DIR += $(LOCAL_PATH)/app/src/main/res/
LOCAL_SRC_FILES := $(call all-java-files-under, app/src/main/)

LOCAL_CERTIFICATE := platform
LOCAL_PRIVILEGED_MODULE := true
LOCAL_DEX_PREOPT := false
LOCAL_ASSET_DIR := $(LOCAL_PATH)/app/src/main/assets/

LOCAL_AAPT_FLAGS := --auto-add-overlay\
LOCAL_PROGUARD_FLAG_FILES := app/proguard-rules.pro pylauncher/proguard-rules.pro

include $(BUILD_PACKAGE)
include $(call all-makefiles-under, $(LOCAL_PATH))

Now i want to show an image in android application from a url.Im planing to use the library picasso. I have added the following in to the applications's build.gradle

compile 'com.squareup.picasso:picasso:2.5.2'

I have tested the application in a mobile phone and it is working fine.But when i build the android application from AOSP project import files from the picasso library are not recognizing.

Can some one guide me to update the android.mk file to to mention the 3rd party library

PS: Im very new to this domain and please let me know if you want more input from my side


问:
Getting null value when sending xml to web api controller from swagger UI
Developing Web API using Asp.net core with swagger. Posting XML to web API from swagger UI but it is giving null at controller side. follows following steps.

Here is the Startup.cs code where XML formatter added:

public void ConfigureServices(IServiceCollection services)
{
    //Adding XML Format Support
    services.AddMvc().AddXmlSerializerFormatters();

    // Register the Swagger generator, defining one or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v2", new Info { Title = "API", Version = "v2" });
        string xmlpath = System.AppDomain.CurrentDomain.BaseDirectory + @"SwaggerAPI.xml";
        c.IncludeXmlComments(xmlpath);
    });
}
```

<p>Here is Controller Code:</p>

<pre class="lang-cs prettyprint-override"><code>[Route("api/Employee")]
public class RuleController : Controller
{
    [HttpPost]
    [Route("add")]
    [Consumes("application/json", "application/xml")]
    public void Post([FromBody]Employee employee)
    {

    }
}

public class Employee
{
    public int Id;
    public string FirstName;
    public string LastName;
}
</code>```

From Swagger UI posting xml to web api:

Here is the debug window:

Please suggest anything I missed here. Any help on this would be appreciated.

答:
In the screen shots you have provided, the request casing does not match the casing used in your model.

XML is case sensitive, so you will need to change the casing of your request to match the casing that your POCO (Plain Old C# Object) is expecting.

In your example, you are sending:

```<code><?xml version="1.0>
  <Employee>
    <firstName>First</firstName>
    <lastName>Last</lastName>
  </Employee>
</xml>
</code>```

This doesn't match the POCO property names given in your subsequent screen shot. Presumably your POCO will look similar to this:

```<code>public class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}
</code>```

Which means that the XML tag <firstName> doesn't map to the POCO property FirstName because the XML tag doesn't have a leading upper case F.

Changing your XML to the following should parse correctly:

```<code><?xml version="1.0>
  <Employee>
    <FirstName>First</FirstName>
    <LastName>Last</LastName>
  </Employee>
</xml>
</code>```

Please note the difference, as it is a subtle but important one:

```<code><firstName>First</firstName>
</code>```

vs

```<code><FirstName>First</FirstName>
</code>```

Body:
Developing Web API using Asp.net core with swagger. Posting XML to web API from swagger UI but it is giving null at controller side. follows following steps.

Here is the Startup.cs code where XML formatter added:

public void ConfigureServices(IServiceCollection services)
{
    //Adding XML Format Support
    services.AddMvc().AddXmlSerializerFormatters();

    // Register the Swagger generator, defining one or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v2", new Info { Title = "API", Version = "v2" });
        string xmlpath = System.AppDomain.CurrentDomain.BaseDirectory + @"SwaggerAPI.xml";
        c.IncludeXmlComments(xmlpath);
    });
}

Here is Controller Code:

[Route("api/Employee")]
public class RuleController : Controller
{
    [HttpPost]
    [Route("add")]
    [Consumes("application/json", "application/xml")]
    public void Post([FromBody]Employee employee)
    {

    }
}

public class Employee
{
    public int Id;
    public string FirstName;
    public string LastName;
}

From Swagger UI posting xml to web api:

Here is the debug window:

Please suggest anything I missed here. Any help on this would be appreciated.

Body:
In the screen shots you have provided, the request casing does not match the casing used in your model.

XML is case sensitive, so you will need to change the casing of your request to match the casing that your POCO (Plain Old C# Object) is expecting.

In your example, you are sending:

<?xml version="1.0>
  <Employee>
    <firstName>First</firstName>
    <lastName>Last</lastName>
  </Employee>
</xml>

This doesn't match the POCO property names given in your subsequent screen shot. Presumably your POCO will look similar to this:

public class Employee
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
}

Which means that the XML tag <firstName> doesn't map to the POCO property FirstName because the XML tag doesn't have a leading upper case F.

Changing your XML to the following should parse correctly:

<?xml version="1.0>
  <Employee>
    <FirstName>First</FirstName>
    <LastName>Last</LastName>
  </Employee>
</xml>

Please note the difference, as it is a subtle but important one:

<firstName>First</firstName>

vs

<FirstName>First</FirstName>


问:
AngularJS - Trigger when radio button is selected
I searched and tried many ng-xxxx kind of options but couldn't find the one..
I just want to call some function in the controller when radio button is selected.

So it might be similar to following..(Of course, below code is not working)

```<code><input type="radio" ng-model="value" value="one" ng-click="checkStuff()"/>
</code>```

Is there any way to achieve what I want?

答:
```<code> <form name="myForm" ng-submit="submitForm()">
   <label data-ng-repeat="i in [1,2,3]"><input type="radio" name="test" ng-model="$parent.radioValue" value="{{i}}"/>{{i}}</label>
   <div>currently selected: {{radioValue}}</div>
   <button type="submit">Submit</button>
</form>
</code>```

Body:
I searched and tried many ng-xxxx kind of options but couldn't find the one..
I just want to call some function in the controller when radio button is selected.

So it might be similar to following..(Of course, below code is not working)

<input type="radio" ng-model="value" value="one" ng-click="checkStuff()"/>

Is there any way to achieve what I want?


问:
Working with Windows Phone 7, how do I create a global MediaElement?
I need to create a MediaElement that will keep playing when I navigate to different pages within my app. Any ideas on how to do this?</p>

答:
I don't think that is possible.

MediaElement is a UIElement which must be hosted inside a page to work.

Each time you navigate, a new page instance is loaded in WP7. A really ugly hack might work, but I don't recommend it.

What are you trying to do?

You could remember the position it was at and restart it when back on page.

ContentLicense: CC BY-SA 2.5


问:
Some records are reverted back to old value in SQL Server 2016 Bidirectional Replication
I have successfully setup bidirectional replication for 4 servers, says A, B, C, and D with the following configuration:
1. Server A acts as Distributor, Publisher for B, C, and D, also as a Subscriber for B, C, and D.
2. Server B, C and D acts as Publisher and Subscriber for server A.
3. they all are connected to a 1-2MB VPN.
and they are all works well until this week I found a weird behavior in two servers. Some of the records are reverted back to old value after couple seconds. I have checked the data was replicated, and then reverted back randomly. I have no idea what caused the problem, I have set @loopback_detection to true during the creation of all subscribers. Does anyone experienced the same or know how to solve it? Thank you. </p>

<p>Achmad Mulyadi </p>

答:
Well, it's not an answer to my own question rather a better solution to eliminate most of the problem in bi-directional replication, "MERGE REPLICATION".
With Merge Replication you can:

Do two way replication even in Standard Edition.

Offer the easiest way to resolve conflict between servers

Either remote snapshot or "local" snapshot is supported. "Local"
means, you can copy a big snapshot through FTP or even an external
HDD and copy the snapshot file to another server manually.

The most stable way to replicate database in multi-master
replication.

Body:
I have successfully setup bidirectional replication for 4 servers, says A, B, C, and D with the following configuration:
1. Server A acts as Distributor, Publisher for B, C, and D, also as a Subscriber for B, C, and D.
2. Server B, C and D acts as Publisher and Subscriber for server A.
3. they all are connected to a 1-2MB VPN.
and they are all works well until this week I found a weird behavior in two servers. Some of the records are reverted back to old value after couple seconds. I have checked the data was replicated, and then reverted back randomly. I have no idea what caused the problem, I have set @loopback_detection to true during the creation of all subscribers. Does anyone experienced the same or know how to solve it? Thank you.

Achmad Mulyadi


问:
How can I find a range in an array using user input?
```<code>package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}
</code>```

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

```<code>Arrays.asList(a).indexOf(index1)
</code>```

but that will give me -1 every time
And I don't know how to make it wors in the other method

答:
Something like this?</p>

```<code>public void DoubleSegsum(double[] a, int from, int to){
    double sum = 0.0;
    for(;from < to; from++){
      sum += a[from];
    }
    System.out.println(sum);
}
</code>```

Body:
package assignment;

import java.util.Arrays;
import java.util.Scanner;

public class assignment {

    public static void main(String[] args) {
        double[] a = new double[] {9.0, 8.0, 7.0, 6.0, 5.0, 4.0};

        int index1;
        Scanner user_input = new Scanner(System.in);
        System.out.println("index 1 invoeren");
        index1 = user_input.nextInt();

        int index2;
        System.out.println("index 2 invoeren");
        index2 = user_input.nextInt();

        //System.out.println(index1);
        //System.out.println(index2);

    }

    public void DoubleSegsum(double[] a, int from, int to){

    }

}

I need to write a method DoubleSegsum (as seen last) where I can get the sum of the elements of a, between position from and to.
For example (a, 2, 4) should return 13.
I was trying something with

Arrays.asList(a).indexOf(index1)

but that will give me -1 every time
And I don't know how to make it wors in the other method

Body:
Something like this?

public void DoubleSegsum(double[] a, int from, int to){
    double sum = 0.0;
    for(;from < to; from++){
      sum += a[from];
    }
    System.out.println(sum);
}


问:
writing xpath locator for a link element using xpath axes
I am trying to learn Selenium and am trying to write the xpath locator for the "About Us" link on the web page - www.hdfc.com

I can do it with link as:

link=About Us

I have tried the following and it works fine:

xpath=//a[text()='About Us']

but I wanted to write the locator using xpath axes so that its flexible enough. Can someone please point me in the right direction?

答:
Use the below xpaths to detect 'About Us'link in your web page

Below xpath was written by refering the immediate parent node
//li[@class='expanded']/child::span[text()='About Us']

This xpath was written by using the parent node of Menu bar(parent of whole menu items)
//ul[@class='menu hdfc-investor']/child::li[contains(.,'About Us')]


问:
Add production into development React Webpack config
I have a simplest possible React environment.
That is very efficient in development.

```<code>var webpack = require('webpack');

const config = {
  entry: "./index.js",
  output: { filename: "bundle.js" },
  devtool: 'eval',
module: {
   loaders: [
    {  test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'env'] }  }
   ]
  }
};

module.exports = config;
</code>```

What I want to do is to add a production build so as to run in console script like this: npm run build, which is defined in package.json:

"build": "webpack --config webpack.config.js"

How can I add production plugins and devtool: "cheap-module-source-map" so that they will work only in production and were not included into development. By production plugins I meant these:

```<code>new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
new webpack.optimize.UglifyJsPlugin()
</code>```

I failed to use

```<code>var debug = process.env.NODE_ENV !== "production";
</code>```

with devtool: debug ? "cheap-module-source-map" : "eval",
and

plugins: debug ? [] : [//production plugins here ]

答:
It's common practice to create a separate file for production config and to change properties there.

webpack.config.production.js:

```<code>var webpack = require('webpack');
var config = require('./webpack.config');

config.devtool = 'cheap-module-source-map';
config.plugins = (config.plugins || []).concat([
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin()
]);

module.exports = config;
</code>```

Body:
I have a simplest possible React environment.
That is very efficient in development.

var webpack = require('webpack');

const config = {
  entry: "./index.js",
  output: { filename: "bundle.js" },
  devtool: 'eval',
module: {
   loaders: [
    {  test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/, query: { presets: ['react', 'env'] }  }
   ]
  }
};

module.exports = config;

What I want to do is to add a production build so as to run in console script like this: npm run build, which is defined in package.json:

"build": "webpack --config webpack.config.js"

How can I add production plugins and devtool: "cheap-module-source-map" so that they will work only in production and were not included into development. By production plugins I meant these:

new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('production') }),
new webpack.optimize.UglifyJsPlugin()

I failed to use

var debug = process.env.NODE_ENV !== "production";

with devtool: debug ? "cheap-module-source-map" : "eval",
and

plugins: debug ? [] : [//production plugins here ]

Body:
It's common practice to create a separate file for production config and to change properties there.

webpack.config.production.js:

var webpack = require('webpack');
var config = require('./webpack.config');

config.devtool = 'cheap-module-source-map';
config.plugins = (config.plugins || []).concat([
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify('production')
    }),
    new webpack.optimize.UglifyJsPlugin()
]);

module.exports = config;


问:
Converting a Location to LatLng
I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:

```<code>LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());
</code>```

Then I recalled the addMarker method:

```<code> mMap.addMarker(new MarkerOptions()
    .title(getString(R.string.default_info_title))
    .position(mCurrentPlace)
    .snippet(getString(R.string.default_info_snippet)))
</code>```

But Launching the application by "Run", it arrested.

Where am I goning wrong?

Thanks.

答:
```<code>  public void moveMap(GoogleMap gMap, double latitude, double longitude) {
        Log.v(TAG, "mapMoved: " + gMap);
        LatLng latlng = new LatLng(latitude, longitude);
        CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
        gMap.addMarker(new MarkerOptions().position(latlng));
        gMap.moveCamera(cu);
    }
</code>```

Call this method where you want location and marker and in on mapasync callback method.

```<code>@Override
        public void onMapReady(GoogleMap googleMap) {

            MapsInitializer.initialize(context);
            gMap = googleMap;
            gMap.getUiSettings().setMapToolbarEnabled(false);
            gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            if(items.get(getLayoutPosition())!=null )
                moveMap(gMap,latitude, longitude);
        }
        public void initializeMapView() {
            if (mapView != null) {
                // Initialise the MapView
                mapView.onCreate(null);
                // Set the map ready callback to receive the GoogleMap object
                mapView.getMapAsync(this);

            }
        }
</code>```

Override onMapReadyCallback method and do this.

Call initializeMapView method in onCreate() or In adapter onBindViewHolder

Title: Converting a Location to LatLng

Body:
I'm trying to set the marker on my current location, so I tried to convert a Location to a LatLng class:

LatLng mCurrentPlace= new LatLng(location.getLatitude(),location.getLongitude());

Then I recalled the addMarker method:

 mMap.addMarker(new MarkerOptions()
    .title(getString(R.string.default_info_title))
    .position(mCurrentPlace)
    .snippet(getString(R.string.default_info_snippet)))

But Launching the application by "Run", it arrested.

Where am I goning wrong?

Thanks.

Body:
  public void moveMap(GoogleMap gMap, double latitude, double longitude) {
        Log.v(TAG, "mapMoved: " + gMap);
        LatLng latlng = new LatLng(latitude, longitude);
        CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(latlng, 6);
        gMap.addMarker(new MarkerOptions().position(latlng));
        gMap.moveCamera(cu);
    }

Call this method where you want location and marker and in on mapasync callback method.

@Override
        public void onMapReady(GoogleMap googleMap) {

            MapsInitializer.initialize(context);
            gMap = googleMap;
            gMap.getUiSettings().setMapToolbarEnabled(false);
            gMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            if(items.get(getLayoutPosition())!=null )
                moveMap(gMap,latitude, longitude);
        }
        public void initializeMapView() {
            if (mapView != null) {
                // Initialise the MapView
                mapView.onCreate(null);
                // Set the map ready callback to receive the GoogleMap object
                mapView.getMapAsync(this);

            }
        }

Override onMapReadyCallback method and do this.

Call initializeMapView method in onCreate() or In adapter onBindViewHolder


问:
Iterating through HashMap by values
I need to loop through a HashMap, but to give importance to the values' order.
For example, consider the following hash map of <String, Integer>:

```<code>{"dog" : 2, "bird": 3, "cat" : 1}
</code>```

Now, I need to loop through the hasp map in order of ascending values, so that

```<code>for () {
 System.out.println( currentKey );
}
</code>```

will always output

"cat", "dog", "bird"

答:
Maybe this will help:

Sort a Map<Key, Value> by values (Java)

Title: Iterating through HashMap by values

Body:
I need to loop through a HashMap, but to give importance to the values' order.
For example, consider the following hash map of <String, Integer>:

{"dog" : 2, "bird": 3, "cat" : 1}

Now, I need to loop through the hasp map in order of ascending values, so that

for () {
 System.out.println( currentKey );
}

will always output

"cat", "dog", "bird"


问:
Why doesn't the bind() work for a function inside another function which is inside the object?
I have a question about .bind() function.
I have this code and it outputs Window object and I don't understand why. Could you explain to me why bind(this) had no effect on the function?</p>

```<code>let vakho = {
    name: "salome",
    a: function () {

        let something = function () {
            return this;
        }
        something.bind(this)

        return {
            f: function () {
                return something();
            }
        }
    },
}

console.log(vakho.a().f())
</code>```

答:
.bind returns a new function with the attached context. You need to assign the result to the something again.

let vakho = {
    name: "salome",
    a: function () {

        let something = function () {
            return this;
        };

        something = something.bind(this); // Assign to the something

        return {
            f: function () {
                return something();
            }
        }
    },
}

console.log(vakho.a().f());
console.log(vakho.a().f().name);```

Body:
I have a question about .bind() function.
I have this code and it outputs Window object and I don't understand why. Could you explain to me why bind(this) had no effect on the function?

let vakho = {
    name: "salome",
    a: function () {

        let something = function () {
            return this;
        }
        something.bind(this)

        return {
            f: function () {
                return something();
            }
        }
    },
}

console.log(vakho.a().f())


问:
Remove every 3rd element in arraylist
I am trying to loop through an arraylist and gradually remove an element every 3 indices. Once it gets to the end of the arraylist I want to reset the index back to the beginning, and then loop through the arraylist again, again removing an element every 3 indices until there is only one element left in the arraylist.

The listOfWords is an array with a length of 3 that was previously filled.

```<code>int listIndex = 0;

do
{
    // just to display contents of arraylist
    System.out.println(listOfPlayers);

    for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
    {
        System.out.print("Player");
        System.out.print(listOfPlayers.get(wordIndex));
        System.out.println("");
        listIndex = wordIndex;
    }

    listOfPlayers.remove(listOfPlayers.get(listIndex));
}
while(listOfPlayers.size() > 1);
</code>```

I have tried to implement for several hours yet I am still having trouble. Here's what happens to the elements of the arraylist:

```<code>1, 2, 3, 4

1, 2, 4

1, 2
</code>```

Then it throws an 'index out of bounds error' exception when it checks for the third element (which no longer exists). Once it reaches the last element I want it to wrap around to the first element and continue through the array. I also want it to start where it left off and not from the beginning once it removes an element from the arraylist.

答:
Try the following code. It keeps on removing every nth element in List until one element is left.

```<code>    List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    int nth = 3;
    int step = nth - 1;
    int benchmark = 0;

    while (array.size() > 1) {
        benchmark += step;
        benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
        System.out.println(benchmark);
        array.remove(array.get(benchmark));
        System.out.println(array);
    }
</code>```

Title: Remove every 3rd element in arraylist

Body:
I am trying to loop through an arraylist and gradually remove an element every 3 indices. Once it gets to the end of the arraylist I want to reset the index back to the beginning, and then loop through the arraylist again, again removing an element every 3 indices until there is only one element left in the arraylist.

The listOfWords is an array with a length of 3 that was previously filled.

int listIndex = 0;

do
{
    // just to display contents of arraylist
    System.out.println(listOfPlayers);

    for(int wordIndex = 0; wordIndex < listOfWords.length; wordIndex++
    {
        System.out.print("Player");
        System.out.print(listOfPlayers.get(wordIndex));
        System.out.println("");
        listIndex = wordIndex;
    }

    listOfPlayers.remove(listOfPlayers.get(listIndex));
}
while(listOfPlayers.size() > 1);

I have tried to implement for several hours yet I am still having trouble. Here's what happens to the elements of the arraylist:

1, 2, 3, 4

1, 2, 4

1, 2

Then it throws an 'index out of bounds error' exception when it checks for the third element (which no longer exists). Once it reaches the last element I want it to wrap around to the first element and continue through the array. I also want it to start where it left off and not from the beginning once it removes an element from the arraylist.

Body:
Try the following code. It keeps on removing every nth element in List until one element is left.

    List<Integer> array = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
    int nth = 3;
    int step = nth - 1;
    int benchmark = 0;

    while (array.size() > 1) {
        benchmark += step;
        benchmark = benchmark > array.size() - 1 ? benchmark % array.size() : benchmark;
        System.out.println(benchmark);
        array.remove(array.get(benchmark));
        System.out.println(array);
    }


问:
How to change layout font of android studio software

so i change font style of android studio (Not font of code or font of android simulator)

答:
Press Ctrl+Alt+S: This will take you to Settings.

Inside very first option Appearance & Behavior > Appearance, there is a check-box to Override default fonts by(not recommended), you can change fonts from there or disable that option.

Don't forget to click Apply.


问:
Android WebDav library
I am looking for working WebDav library that I can use on Android. Sardine looked promising at first but I think that it is a no go on Android because it relies on apache http (this one can be resolved) but also on JAXB (which I am failing to resolve on Android). I have tried sardine-android but it is not working for me. When I try to connect to box.com using it I am getting valuerequiredexception on getetag. Any ideas on good library?

答: I've just released a fork of Sardine where I replaced JAXB (which is not included in Android platform) by SimpleXml and it seems to work well so far. Feel free to try it out and let me know if you have any issue: https://github.com/thegrizzlylabs/sardine-android</p>

Title: Android WebDav library


答:
```<code>public double DoubleSegsum(double[] a, int from, int to){
    double sum = 0;
    for (int i = from; i < to && i < a.length; i++) {
        sum += a[i];
    }

    return sum;
}
</code>```

Title: How can I find a range in an array using user input?


问:
Disable wrapping in Psql output
When using Psql in Linux, if the result of my SQL query contains many columns or long strings of data, it will wrap the initial view and only once I scroll to the side will it stop wrapping and show each row on a separate line.

I've tried various \pset options such as format unaligned, format aligned, format wrapped, columns 0, columns 1000, but none seemed to fully stop wrapping unless I generate static output to a file.

How can I set it to never wrap the output while still being scrollable and showing the result using the default ascii table format?

答:
probably you should use aligned format for output:

```<code>\pset format aligned
</code>```

You can check all available formats to fit your needs:

```<code>\pset format TAB
aligned          html             latex-longtable  unaligned
asciidoc         latex            troff-ms         wrapped
</code>```

Also you should check PAGER configured value in your environment

Title: Disable wrapping in Psql output

Body:
probably you should use aligned format for output:

\pset format aligned

You can check all available formats to fit your needs:

\pset format TAB
aligned          html             latex-longtable  unaligned
asciidoc         latex            troff-ms         wrapped

Also you should check PAGER configured value in your environment


问:
An error occurred uploading to the app store with no error code
Just updated to XCode 9. Trying to upload the build to iTunes Connect but getting an error:

No error code is displayed. Have anyone dealt with this?

答:
I had the same problem this morning, you can try to open the terminal and run these commands:

```<code>cd ~
mv .itmstransporter/ .old_itmstransporter/
</code>```

It worked for me.

Body:
I had the same problem this morning, you can try to open the terminal and run these commands:

cd ~
mv .itmstransporter/ .old_itmstransporter/

It worked for me.


问:
How to add an array to a cookie in PHP?
I am trying to store array to cookie. I am storing my array products item in cookie array, but it throws error.

```<code>    $products = array();
    $item = array($id => $name);
    print_r($item);
    $products[] = $item;
    setcookie('products',json_encode($products),strtotime( '+1 day' ));
    var_dump($_COOKIE['products']);
</code>```

The above code prints

Array (
      [4] => Rug Rat )
 Notice:  Undefined index: products in
  D:\xampp\htdocs\projects\includes\classes\products.php
  on line 43
 NULL

答:
Cookies are set when the response is sent to the client. This means that you won't be able to access them from PHP code until the next request. See the documentation for setcookie() function, section Common Pitfalls:

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

http://php.net/manual/en/function.setcookie.php

So, unless you echo anything, or do anything else that causes the response headers to be sent, you should see var_dumped cookie content after you refresh the page. In your code, there's print_r($item); before setcookie() is called, so you're probably getting a headers already sent warning, and the cookie is never set.

One way or another, it's rarely safe to assume that an array index is set, especially in a superglobal, like $_GET, $_POST, $_COOKIE, etc. You should always check with isset() or array_key_exists if the index is really set.

Title: How to add an array to a cookie in PHP?

Body:
I am trying to store array to cookie. I am storing my array products item in cookie array, but it throws error.

    $products = array();
    $item = array($id => $name);
    print_r($item);
    $products[] = $item;
    setcookie('products',json_encode($products),strtotime( '+1 day' ));
    var_dump($_COOKIE['products']);

The above code prints

Array (
      [4] => Rug Rat )
 Notice:  Undefined index: products in
  D:\xampp\htdocs\projects\includes\classes\products.php
  on line 43
 NULL


问:
Locking a SQL Server table for entire connection
I am reading a parameter from a table in a SQL Server database, increment it, do some other calculations based on it then writing some SQL queries with these new calculated values.

```<code>SELECT TOP 1 fruitId
FROM fruits WITH (TABLOCK, HOLDLOCK)
WHERE fruitId LIKE '1978%'
ORDER BY fruitId DESC
</code>```

After obtaining this fruit Id, some math is done and then data is written into a few tables.

I am writing in those 3 tables in a single transaction.

```<code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN TRANSACTION
    INSERT INTO Fruits (fruitId, fruitName, fruitColor)
    VALUES 197867, 'Apple', 'Red';

    INSERT INTO Salad (saladId, saladName)
    VALUES 1234, 'Apple Salad';

    INSERT INTO Ingredients(saladId, FruitId)
    VALUES 1234, 197867;

    INSERT INTO Ingredients(saladId, FruitId)
    VALUES 1234,197866;

    INSERT INTO Ingredients(saladId, FruitId)
    VALUES 1234, 197980;

    COMMIT TRANSACTION
</code>```

My lock works fine for the insertion part. But while the calculations are done if someone reads fruitId from fruits, the code for write fails for the transaction commit later as fruitId has to be unique.

Is it possible to hold a lock on the fruits table for the entire connection?

答:
No, data locks must be scoped by a transaction.

You need to lock the table in exclusive mode with (TABLOCKX). Your transaction must span both the read and the insert.

Performance will be abysmal.

Investigate optimistic locking strategies.

Body:
I am reading a parameter from a table in a SQL Server database, increment it, do some other calculations based on it then writing some SQL queries with these new calculated values.

SELECT TOP 1 fruitId
FROM fruits WITH (TABLOCK, HOLDLOCK)
WHERE fruitId LIKE '1978%'
ORDER BY fruitId DESC

After obtaining this fruit Id, some math is done and then data is written into a few tables.

I am writing in those 3 tables in a single transaction.

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

BEGIN TRANSACTION
    INSERT INTO Fruits (fruitId, fruitName, fruitColor)
    VALUES 197867, 'Apple', 'Red';

    INSERT INTO Salad (saladId, saladName)
    VALUES 1234, 'Apple Salad';

    INSERT INTO Ingredients(saladId, FruitId)
    VALUES 1234, 197867;

    INSERT INTO Ingredients(saladId, FruitId)
    VALUES 1234,197866;

    INSERT INTO Ingredients(saladId, FruitId)
    VALUES 1234, 197980;

    COMMIT TRANSACTION

My lock works fine for the insertion part. But while the calculations are done if someone reads fruitId from fruits, the code for write fails for the transaction commit later as fruitId has to be unique.

Is it possible to hold a lock on the fruits table for the entire connection?


问:
How I write a separate function in ajax for success method?
How I write a separate function in ajax for success method? </p>

```<code>$.ajax({
    url: 'devices.json',
    data: {},
    datatype: 'JSON',
    method: 'GET',
    success: function(data) {
        var devices = data;
        function print_dev() {
            var str = "";
            str += '<h3>Ajax, JSON Data</h3>';
            document.getElementById('wrapper').innerHTML = str;
        }
        print_dev();
    }
});
</code>```

<p>Can I define the function outside the ajax scope? </p>

答:
Yes, you can - you can interchangeably use anonymous and pre-defined functions:</p>

```<code>function onDevicesRead(data) {
    var devices = data;
    function print_dev() {
        var str = "";
        str += '<h3>Ajax, JSON Data</h3>';
        document.getElementById('wrapper').innerHTML = str;
    }
    print_dev();
}

$.ajax({
    url: 'devices.json',
    data: {},
    datatype: 'JSON',
    method: 'GET',
    success: onDevicesRead
});
</code>```

Body:
How I write a separate function in ajax for success method?

$.ajax({
    url: 'devices.json',
    data: {},
    datatype: 'JSON',
    method: 'GET',
    success: function(data) {
        var devices = data;
        function print_dev() {
            var str = "";
            str += '
Ajax, JSON Data
';
            document.getElementById('wrapper').innerHTML = str;
        }
        print_dev();
    }
});

Can I define the function outside the ajax scope?

Body:
Yes, you can - you can interchangeably use anonymous and pre-defined functions:

function onDevicesRead(data) {
    var devices = data;
    function print_dev() {
        var str = "";
        str += '<h3>Ajax, JSON Data</h3>';
        document.getElementById('wrapper').innerHTML = str;
    }
    print_dev();
}

$.ajax({
    url: 'devices.json',
    data: {},
    datatype: 'JSON',
    method: 'GET',
    success: onDevicesRead
});


问:
How to sort a NSArray which contains NSDictionary?
I have a plist like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>
</code>```

Now I want to sort this by the highscoreInSeconds.

```<code>   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];
</code>```

How can I sort this now?

Thank you very much!
:)

Have a nice day.

PS: It should look like this at the end:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>
</code>```

You don't need to say me how to write a plist i knew that.

答:
You can use

```<code>- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context
</code>```

Implement a function which say which of the 2 dictionary bigger in sorting value.

```<code>NSInteger intSort(id value1, id value2, void *context)
{
    id v1 = [value1 valueforkey:@""];//give required key
    id v2 = [value2 valueforkey:@""];//give required key
    if (v1 < v2) // do comparison based on the data type
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}
</code>```

Body:
I have a plist like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>

Now I want to sort this by the highscoreInSeconds.

   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *plistDirectory = [paths objectAtIndex:0];
 NSString* fullPath = [plistDirectory stringByAppendingPathComponent:@"data.plist"];

 NSMutableDictionary* pData = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
 NSMutableArray* highscores = [pData valueForKey:@"highscores"];

How can I sort this now?

Thank you very much!
:)

Have a nice day.

PS: It should look like this at the end:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>highscores</key>
 <array>
  <dict>
   <key>highscoreInSeconds</key>
   <string>12</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
  <dict>
   <key>highscoreInSeconds</key>
   <string>9</string>
   <key>levelName</key>
   <string>1</string>
   <key>name</key>
   <string>Black</string>
  </dict>
 </array>
</dict>
</plist>

You don't need to say me how to write a plist i knew that.

Body:
You can use

- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

Implement a function which say which of the 2 dictionary bigger in sorting value.

NSInteger intSort(id value1, id value2, void *context)
{
    id v1 = [value1 valueforkey:@""];//give required key
    id v2 = [value2 valueforkey:@""];//give required key
    if (v1 < v2) // do comparison based on the data type
        return NSOrderedAscending;
    else if (v1 > v2)
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}


问:
Java portlet: how to redirect (server side) to serveResource?
(disclaimer: I'm new to portlet development)

I created portlet (in liferay) to serve files. But user first need to fill small form (name, etc.) and then after clicking "save" I put data do database and should serve the file for download.

I do know how to serve file with:

```<code>@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
</code>```

and save data with action:

```<code>@ProcessAction(name = "save")
public void save(ActionRequest actionRequest, ActionResponse actionResponse)
</code>```

But don't know how to server.transfer from one to another. I can't just call:

```<code>serveResource(actionRequest, actionResponse);
</code>```

because parameters are not compatible.

Also on error I should do:

```<code>PortalUtil.copyRequestParameters(actionRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/myForm.jsp");
</code>```

which is not available for resourceRequest/resourceResponse...

What is proper/elegant way for this kind of redirections in portlets?

答:
For that you have to submit the form using ajax via resourceUrl.
Write below code in serveResource Method to download the file.</p>

```<code>PortletResponseUtil.sendFile(resourceRequest, resourceResponse,
fileName, bytes, contentType);
</code>```

Body:
(disclaimer: I'm new to portlet development)

I created portlet (in liferay) to serve files. But user first need to fill small form (name, etc.) and then after clicking "save" I put data do database and should serve the file for download.

I do know how to serve file with:

@Override
public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)

and save data with action:

@ProcessAction(name = "save")
public void save(ActionRequest actionRequest, ActionResponse actionResponse)

But don't know how to server.transfer from one to another. I can't just call:

serveResource(actionRequest, actionResponse);

because parameters are not compatible.

Also on error I should do:

PortalUtil.copyRequestParameters(actionRequest, actionResponse);
actionResponse.setRenderParameter("mvcPath", "/myForm.jsp");

which is not available for resourceRequest/resourceResponse...

What is proper/elegant way for this kind of redirections in portlets?

Body:
For that you have to submit the form using ajax via resourceUrl.
Write below code in serveResource Method to download the file.

PortletResponseUtil.sendFile(resourceRequest, resourceResponse,
fileName, bytes, contentType);