The definitive guide to grails second edition - phần 10 potx

50 512 0
The definitive guide to grails second edition - phần 10 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

568 APPENDIX ■ THE GROOVY LANGUAGE ■Note Groovy doesn’t support true named arguments but allows the method to specify a map as the only argument, hence mimicking this capability. This limitation is mainly down to Java byte code itself, which does not associate names (only types) with method parameters. Groovy ships with a number of builders (excuse the pun) built-in, including but not lim- ited to the following: •The MarkupBuilder for constructing, typically XML, markup •The DOMBuilder for constructing W3C DOM trees •The AntBuilder to provide scripting for Apache Ant •The SwingBuilder for constructing Swing GUI interfaces As an example, take a look at the usage of the MarkupBuilder, shown in Listing A-23, which allows construction of markup documents such as XML or HTML. Listing A-23. MarkupBuilder in Action // construct builder that outputs to standard out def mkp = new groovy.xml.MarkupBuilder() // write markup mkp.authors { author(name:'Stephen King') { book( title:'The Shining') book( title:'The Stand') } author(name: 'James Patterson') { book( title:'Along Came a Spider' ) } } This example demonstrates the construction of a groovy.xml.MarkupBuilder instance using standard out and the usage of closures and named arguments to represent the markup. Listing A-24 shows the result. APPENDIX ■ THE GROOVY LANGUAGE 569 Listing A-24. Result of MarkupBuilder <authors> <author name="Stephen King"> <book title="The Shining" /> <book title="The Stand" /> </author> <author name="James Patterson"> <book title="Along Came a Spider" /> </author> </authors> It is interesting at this point to take a closer look at Listing A-23. In this example, we passed an “anonymous” closure to the authors() method of the MarkupBuilder instance, but consider the possibility of assigning this closure to a variable and then passing as an argument the same closure to different builders, one that renders XML and another that outputs the same data as a PDF document or renders it in a GUI. Unlike the XML produced in Listing A-24, the builder code in Listing A-23 is pure Groovy code and can therefore leverage the full power of the language: conditionals, looping, referenc- ing, inheritance, and so on. Builders are an extremely powerful concept, and if you’re willing to delve into some Groovy development by extending the BuilderSupport class to create your own builders, you can create some pretty amazing constructs that could end up as domain-specific languages within your application. Grails utilizes builders all over the place, from constructing Hibernate criteria to rendering markup to the HTTP response. Builders are a key element in the conciseness and power that Grails brings to web application development. Summary That completes this dash through the Groovy language. As we have already admitted, it was by no means comprehensive. Groovy has many more fantastic features; it is really worth investing the time to learn more about it. But this quick overview should give you an idea of why some of Groovy‘s features are so important to Grails and how they make life easier developing today’s web applications. You saw that Groovy looks pretty much like Java at first glance, allowing a smooth transi- tion into the new world of dynamic programming. Since Groovy is fully integrated with the Java platform and works directly on JDK objects, your investment in learning Java and your experi- ence with the platform are fully protected. What’s new is that Groovy gives you more immediate control over types such as lists and maps. New concepts such as closures and ranges complete the picture. The combination of syntax enhancements, new types, improvements to JDK classes, and metaprogramming leads to an idiomatic Groovy style that is both simple and powerful. 571 Index ■Symbols _album.gsp template adding album art to, 192 buy action, 211 implementing, 180 with permissions working, 440 _albumList.gsp template, 181 * (asterisk) as spread operator, 259 as wildcard, 150, 197, 417 <cache:text> tag, 382 ${ } syntax, 111 ?: (Elvis operator), 165 <extend-classpath> element, 326 <g:applyLayout> tag, 215 <g:createLink> tag, 475 <g:formRemote> tag, 175–176 <g:link> tag, 154 <g:message> tag, 263 <g:paginate> tag, 263 <g:remoteField> tag, 193–194, 197 <g:remoteLink> tag, 173–174, 179, 193 <g:uploadForm> tag, 87 <jsec:hasAllRoles> tag, 432 <jsec:hasPermission> tag, 439 <jsec:hasRole> tag, 432 <jsec:isLoggedIn> tag, 431 <jsec:isNotLoggedIn> tag, 431 <jsec:lacksPermission> tag, 439 <jsec:principal /> tag, 432 <media:player> tag, 442 <music:albumArt> tag, 191 <% %> syntax, 109 <%= %> statement, 110 _post.gsp template for blog plugin, 401 _recommendations.gsp template, 230 ?. (safe deference operator), 112 _searchResults.gsp template, 196–197 *. (spread dot) operator (Groovy), 385 <sysprops> element, passing system properties with, 327 _welcomeMessage.gsp template, 177 ■Numerics 404 response codes, custom mapping for, 154 500 response code, mapping for, 153 ■A abstract beans, 495–496 abstract property, bean argument, 496 ACCEPT header content negotiation with, 452–457 reliability of, 456–457 access, restricting based on roles, 432 through URL mappings, 446–448 with <jsec:lacksPermission> tag, 439 accessControl method, 428 accessing business logic within application, 298–304 request attributes, 68–70 request parameters, 73 Acegi plugin, 416 ACID properties of databases, 295 action names, removing from URL mapping, 145 572 ■INDEX action states (flows) checking login details with, 203, 212–216 gTunes, 222–227 overview of, 202 reusing with closures, 227–231 ActiveMQ (Apache) configuring with BeanBuilder, 500–502 installation directory, 499 JAR files, 501 overview of, 498–499 Queues section, 503 setting up, 499–500 web console, 500 ActiveRecord (Rails), GORM compared to, 266 addJob method, 355 Address class applying constraints to, 542 code for, 537, 539–540 column annotation, 538 creating, 536–537 entities fields, 537 id property, 538 version property, 538 Address domain class, defining, 210–211 AddressConstraints.groovy script, 542 addTo* method, 253 after advice (AOP), 90, 91 after attribute (Ajax), 177–178 afterView filter, 418 Ajax asynchronous form submission, 175–177 effects and animation, adding, 193 enabling on form fields, 193–197 event handling, 178–179 executing code before and after calls, 177–178 flow of request, 172 HTML anchor tag, creating, 173–174 login request, handling, 176 overview of, 171 performance and, 197–198 provider, changing, 174–175 remote linking, 179–193 XMLHttpRequest object and, 171–173 album art, displaying, 182–193 Album Controller, display action, 213 Album domain class creating, 23 price property, 209 album-art plugin example adding method to all controllers, 395–396 creating, 391 dependencies, 392 getArt() method and, 396 providing metadata to, 393 structure of, 392 updating to use simple-cache plugin, 394 AlbumArtKey cache key class, 188 AlbumArtService template creating, 183 enabling caching, 188 full code for, 188–190 AlbumController create action, 31 creating, 24 delete action, 29 display action, 181 edit action, 29 index action, 28 list action, 28 save action, 31, 77 show action, 28 update action, 30 _album.gsp template adding album art to, 192 buy action, 211 implementing, 180 with permissions working, 440 573 ■INDEX Find it faster at http://superindex.apress.com albumList template, rendering, 132 _albumList.gsp template, 181 AlbumPayment class, 210, 433 AlbumPermission class, 437–438 AlbumService class, 480 all format content negotiation with ACCEPT header and, 456 marshaling objects to JSON, 463 allowedMethods property, 85–86 Amazon web services creating, 183–185 setting up, 182–183 testing, 185–187 animation, adding with Ajax, 193 anonymous code blocks, 552 Ant (Apache) Gant compared to, 310 integration with, 325–327 overview of, 313 AntBuilder (Groovy), 568 AOP (Aspect-Oriented Programming) after advice, 91 before advice, 90–91 security and, 417 Apache See also ActiveMQ; Ant Commons HttpClient project, 473 Ivy, dependency resolution with, 327–330 Appear effect (Scriptaculous library), 193 appender configuring, 308 using, 309 appending, 554 application layer caching, 373 application reload events, plugins and, 385–387 ApplicationContext, 379 ApplicationContextAware instance, 489 application-layer security filters, 417–418 JSecurity plugin authentication realms, 419–420 authentication, implementing with, 422–427 filters, 427–429 overview of, 416 permission-based security, implementing, 433, 446 role-based security, implementing, 429–430 roles and permissions, 421 subjects and principals, 420 view, securing, 431–432 working with, 421 applications See also gTunes application controller, creating, 8–10 creating, 7 deploying, 41 modularizing with plugins, 397–406 object-oriented, and domain model, 45 ren-war command, 41 running, 13 running tests, 12–13 steps in creating, 7 structure of, 7 testing code, 10–11 with WAR file, 41–42 applying constraints to URL mappings, 149–150 arguments paginate tag, 129 redirect method, 74 around advice (AOP), 90 artefact types, 376–379 ArtefactHandler interface, 377–378 artefacts, supplying with plugins, 373–374 Artist class, unit test for, 61 574 ■INDEX ArtistSubscription class, 505–506 Aspect-Oriented Programming (AOP) after advice, 91 before advice, 90–91 security and, 417 assertions overview of, 548–549 verifying flow state with, 236–244 assigned generator, 530–531 association mapping, changing, 521–524 associations data binding and, 81–82 GORM, overview of, 252–253 one-to-many, 24, 54–56, 521, 522–523 one-to-one, 53–54 many-to-many, 523–524 many-to-one, 81, 521 performance tuning and, 278–281 querying with criteria, 260 relationship management methods, 253–254 SortedSet, 252 transitive persistence, 254 asterisk (*) as spread operator, 259 as wildcard, 150, 197, 417 asynchronous e-mail notifications, 511–513 asynchronous form submission, 175–177 Asynchronous JavaScript Technology and XML. See Ajax Atom standard creating feeds, 473–476 link discovery, 476–477 attach() method, 276 attacks, securing against batch data binding, 413–414 cross-site scripting, 409–412 DoS, 412 Groovy injection, 409 SQL or HQL injection, 407–409 attributes GSP, 108 request Java servlets compared to Grails controllers, 69 redirects and, 71 standard, 68 audit-logging plugin, 368 authenticate method, 422, 424–425 authentication definition of, 407, 417 implementing with JSecurity plugin, 422–427 realms, 419–420 Authentication plugin, 416 AuthFilters class overview of, 427–428 security URI within, 447 authorization, 407, 416 AuthRealm class, 422–423, 438 automatic time stamping, 288 automating deployment to Tomcat, 317–320 autowiring configuring beans for, 488 overview of, 291, 379 Axis 2 plugin, 479 ■B Bash shell, JAVA_OPTS, setting in, 300 BasicDataSource class, 492 batch data binding, vulnerability to attacks, 413–414 batch fetching, 281–282 bean scopes, 496–497 BeanBuilder domain-specific language (DSL) abstract beans, 495–496 bean scopes, 496–497 configuring BeanBuilder with, 500–502 defining beans, 491–492 dynamically creating beans, 497–498 575 ■INDEX Find it faster at http://superindex.apress.com factory beans, 493–495 inner beans, 495 overriding beans, 492–493 overview of, 490–491 providing Spring beans, 379–382 beans See also Spring beans configuring for autowiring, 488 DataSource, overriding, 493 dynamically creating, 497–498 inner, 495 managing definitions with Grails, 490 streamingService creating, 515 using, 516 before advice (AOP), 90–91 before attribute (Ajax), 177–178 behaviors, adding at runtime, 563–565 belongsTo property, 54, 254 binary response, writing, 89 bind errors, dealing with, 13 bindData method, 80–81 binding, 109 blog plugin example adding metadata to, 397 create.gsp view, 402–404 creating, 397 directory structure of, 398 list.gsp view, 399–401 Post domain class, 398 PostController, 399 _post.gsp template, 401 URL mapping to customize layout of, 401 blog posts in gTunes application, creating, 404–405 blog-type URL mapping, 149 Blowfish encryption codec class, 414–415 BootStrap classes, populating database with, 364–365 Bootstrap.groovy script, 317 bootstrapping Grails from command line, 317 browsers, older, and ACCEPT header, 456–457 build system, Gant and bootstrapping Grails from command line, 317 command-line variables, 313–314 documenting scripts, 315–316 overview of, 310–311 parsing command-line arguments, 314–315 reusing Grails scripts, 316 scripts, creating, 312–313 build.xml file, 325 builders (Groovy), 567–569 BuilderSupport class, 569 built-in operators (Groovy), 560 built-in tags. See tags, built-in business logic, accessing within application, 298–304 “Buy” button, disabling, 439 buyFlow defining, 212 full code for, 240–244 ■C cache key, 187 <cache:text> tag, 382 caching application layer, 373 content-level, 382 in GORM, 282–284 return value of blocks of code using closures, 381 caching pattern, 380 caching solution, Ehcache, 187 calling methods on integers, 558 cascade behavior, 254 checkBox tag, 120–121 chooseGiftWrapFlow flow, 206–207 576 ■INDEX classes See also domain classes Address applying constraints to, 542 code for, 537, 539–540 column annotation, 538 creating, 536–537 defining, 210–211 entities fields, 537 id property, 538 version property, 538 AlbumArtKey cache key, 188 AlbumPayment, 433 AlbumPermission, 437–438 AlbumService, 480 Artist, 61 ArtistSubscription, 505–506 AuthFilters, 427–428, 447 AuthRealm, 422–423, 438 BasicDataSource, 492 BootStrap, populating database with, 364–365 BuilderSupport, 569 codec, 414–416 ControllerUnitTestCase, 91–93 CreditCardCommand, 233 declaring, 548 DefaultMessageListenerContainer, 504 GrailsApplication, 375–376 GrailsTestUnitCase, 61 GrailsUrlMappingsTestCase, 155–158 Groovy BuilderSupport, 569 groovy.lang.Script, 548 GroovyShell, 409 Hibernate, Session, 266–267 java.text.MessageFormat, 164–165 java.util.ResourceBundle, 161 LoggingFilters, 417 LoginCommand, 102–104, 425–426 MessageListenerAdapter, 503 MetaClass, 384, 562–563 methods, adding to, 384 MonetaryAmount, 526 org.springframework.mock.web.MockHtt pServletResponse, 92 Person, 51–53 Realm, 419 SampleController, 65–66 SecurityUtils, 420 Song, 46, 62 SongController, stream action, 513 StoreService creating, 290 purchaseAlbums method, 293–294 storeService property, 294–295 StreamingMarkupBuilder, 322 StreamingService, 514–515 SubscriptionTagLib implementing, 507 testing, 508–509 TagLibUnitTestCase using, 508 transactional service, 512 UrlMappings, 155–158 User, 347, 535 UserController, 416 UserControllerTests, 100 ClassPathXmlApplicationContext instance, 489 clear() method, 269–270 clearErrors() method, 48 clearing session, 269–270 client storage, flows and, 204–205 clients, calling SOAP from, 482–484 closures caching return value of blocks of code using, 381 Groovy, 552–553 577 ■INDEX Find it faster at http://superindex.apress.com reusing action states with, 227–231 Cobertura (Source Forge), code coverage with, 330–331 code, executing before and after calls, 177–178 code blocks, reusable, 552 code coverage, with Cobertura, 330–331 code synthesis, 566–567 codec classes, 414–416 collect tag (GSP), 114–115 column name mapping, changing, 520–521 com.sun.management.jmxremote system property, 300 command line, bootstrapping Grails from, 317 command objects defining, 82–83 using, 83–84 using with flows, 231–235 command-line arguments, parsing, 314–315 command-line interface, 6 command-line variables, 313–314 commands create-app, 7 create-controller, 8, 20 create-domain-class, 18, 95 create-plugin, 370 create-script, 312 create-tag-lib, 191, 373 create-unit-test, 92 gant, 311 generate-controller, 27 grails, 34 grails console, 455 grails create-service, 183 grails war, 362 help, 6, 315 install-plugin, 369 install-plugin -global, 369 JSecurity plugin, 419 list-plugins, 367, 369 package-plugin, 389 for plugin discovery, 367–369 for plugin installation, 369–370 plugin-info, 368–369 release-plugin, 390–391 run-app, 13 run-war, 41 set-version, 362 test-app, 12–13, 61 uninstall-pluginl, 370 war, 41 Commons HttpClient project (Apache), 473 Company class, transient property, 50 company table, 50 compilation paths, 314 composite identifiers, using, 531–532 composition, 59–60 Config.groovy file environment-specific configuration, 306 locations setting, 310 log4j property, 306–309 overview of, 305–306 configuring ActiveMQ with BeanBuilder, 500–502 assigned generator, 531 beans for autowiring, 488 composite identifier, 531 data sources DataSource.groovy file, 35–37 JNDI, 39 MySQL database, 37–39 overview of, 34 Ehcache Spring bean, 187 GORM custom dialect, 264–265 Hibernate properties, 265 overview of, 263 SQL logging, 264 578 ■INDEX configuring (continued) Grails environment-specific configuration, 306 externalized configuration, 310 logging, 306–309 overview of, 305–306 stack trace filtering, 309 Grails build in Hudson, 334 Grails installation in Hudson, 332 hilo generator, 530, 530 Mail plugin, 346 confirming purchase, 237 confirmRegistration view, 349 Connect to Agent dialog box (JConsole), 300 constraints description of, 21 domain class with, 166 using with POJO entities, 541–542 constraints block, URL mappings, 144, 149–150 constraints property (domain class), 46, 150 consuming JMS messages with Spring, 503–505 container, deploying to, 361–362 content negotiation (REST) overview of, 452 view and, 459–460 with ACCEPT header, 452–457 with CONTENT_TYPE header, 457–458 with file extensions, 458 with request parameters, 459 content-level caching, 382 contentType directive, 109 CONTENT_TYPE header, content negotiation with, 457–458 continuous integration with Hudson, 331–335 controllers See also specific controllers binary response, writing, 89 command objects defining, 82–83 using, 83–84 creating, 8–10 data binding associations and, 81–82 bindData method, 80–81 Errors API and, 79–80 file uploads and, 86–89 overview of, 77–78 to multiple domain objects, 80 validating incoming data, 78–79 default index action of, 10 default action, setting, 65–67 dynamic scaffolding and, 19–21 dynamically mapping to, 451 generating, to implement CRUD functionality, 27–31 home page, creating, 94–95 HTTP method restrictions, 85–86 index action, 10 injecting service instance into, 291 IO and, 86 logging, 67–68 login form, creating, 96–97 login process, testing, 104–106 LoginCommand class, 102–104 mapping to view for particular, 148 methods, adding to, 384 model, creating, 75 names, removing from URL mapping, 145 overview of, 65 prototyped, 65 redirecting request, 73–74 registration code, testing, 100–102 registration, implementing, 97–100 rendering text, 73 request attributes, accessing, 68–70 [...]... 563–565 grails- app/domain directory, 18 code synthesis, 566–567 grails- app/i18n/ directory, 159 intercepting method dispatch, 565 grails- app/i18n/messages_es.properties file, 162 MetaClass, 562–563 grails- app/i18n/messages.properties file See properties file grails- app/services/com/g2one/gtunes/Stor eService.groovy, 290 grails- app/taglib directory, 116 grails- app/view/car/list.gsp, 130–131 grails- app/views/error.gsp... 130–131 grails- app/views/error.gsp page, 153–154 grails- app/views/person/create.gsp, 166 grails- app/views/store/genre.gsp page, 127 grails- app/views/store/shop.gsp page, 134 GrailsApplication class, 375–376 grails. converters package, 454 grails- debug executable, 344 grailsEnv variable, 313 GrailsTestUnitCase class, 61 GrailsUrlMappingsTestCase class, 155–158 grails. war.resources setting, 363 ... creating, 17–19 application, 41–42 custom validators, using, 49 to container, 361–362 defining bidirectional one -to- many relationship, 24 customizing WAR file, 363 with Grails, 361 populating database with BootStrap classes, 364–365 versioning and metadata, 362–363 defining one -to- many relationship between, 24 embedding objects, 59–60 errors property, 48 deployment to Tomcat, automating, 317–320 extending with... simplicity and power of, 2 grails command, 34, 311 grails console command, 455 Grails context menu (TextMate), 343 grails create-service command, 183 grails create-taglib target, 137 Grails stack, 2 grails war command, 362 Find it faster at http://superindex.apress.com overview of, 252–253 586 ■I N D E X grails- app/conf/UrlMappings.groovy, 143 metaprogramming grails- app/controllers directory, 65 adding behavior... using, 288 element, 326 GPath expression, interacting with, 115 externalized configuration, 310 Grails executable, running, 6 externalizing DataSource configuration, 310 grails- app/services/com/g2one/gtunes/S toreService.groovy, 290 FactoryBean interface, 493 grails- app/view/car/list.gsp, 130–131 factoryMethod property, 494 grails- app/views/error.gsp page, 153–154 fckeditor, enabling... (UserController), 104 , 176 login form, creating, 96–97 login process, testing, 104 106 login request, Ajax, handling, 176 login, validating with action state, 212–216 LoginCommand class, 102 104 , 425–426 logSql setting (DataSource.groovy file), 264 ■M Mac SOAP Client project, 482 Mail plugin, 346 main window (JConsole), 300 many -to- many association, mapping, 523–524 many -to- one association, 81, 521 mapping table-per-hierarchy,... 359–360 Mail plugin, configuring, 346 object equality, 276 many -to- many association, mappings for, 523 onChange event, 386 mapping closure, 519 one -to- many association bidirectional, 523 ■I N D E X overview of, 54 owning side of, 56 with type, 55 one -to- one relationship, 53 597 person, employee, and player tables database mapping, 51 table-per-subclass mapping, 57 pessimistic locking onNewAlbum method,... 234 enterShipping state, 218 enterShipping.gsp view, 219–220 environment-specific data-source configuration, 36 from grails- app/views/user/register.gsp, 119 with url attribute, 120 Gant build script, 310 generate-controller command, 27 equals and hashCode, implementing, 276 genre action of StoreController, 128 export-library -to- xml script genre.gsp page, 127 full code for, 323–324 get method, 249 output... code into, 214 StoreController buyFlow, 212 test-app command, 12 default index action, 10 TestApp.groovy script, 316 web flow logic in, 292–293 testing StoreControllerTests suite, 10 contents of response, 92 storeLayout.gsp file, 214 data binding in flows, 246–247 StoreService if user is logged in, 244 calling purchaseAlbums method, 294–295 render method, 93 purchaseAlbums method, 293–294 StoreController... defining bidirectional one -to- many relationship, 24 defining one -to- many relationship between, 24 creating, 8 doWithSpring hook, 380, 393 dynamically mapping to, 451 doWithWebDescriptor hook, adding Servlet filter with, 388 controller action vulnerable to attack correcting, 413 injecting service instance into, 291 as model, 75 ControllerUnitTestCase class, 92 create action, 31 create-app gTunes command, 7 . 362 586 ■INDEX grails- app/conf/UrlMappings.groovy, 143 grails- app/controllers directory, 65 grails- app/domain directory, 18 grails- app/i18n/ directory, 159 grails- app/i18n/messages_es.properties file, 162 grails- app/i18n/messages.properties. 370 create-script, 312 create-tag-lib, 191, 373 create-unit-test, 92 gant, 311 generate-controller, 27 grails, 34 grails console, 455 grails create-service, 183 grails war, 362 help, 6, 315 install-plugin,. 521–524 associations data binding and, 81–82 GORM, overview of, 252–253 one -to- many, 24, 54–56, 521, 522–523 one -to- one, 53–54 many -to- many, 523–524 many -to- one, 81, 521 performance tuning and, 278–281 querying

Ngày đăng: 13/08/2014, 08:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan