concept method in category java

appears as: method, The method, methods, The methods, methods, method, A method, The methods, A method, The method
Java SE 11 Programmer I Certification Guide MEAP V03

This is an excerpt from Manning's book Java SE 11 Programmer I Certification Guide MEAP V03.

The first requirement in creating an executable Java application is to create a class with a method whose signature (name and method arguments) match the main method, defined as follows:

Figure 4.20 The scope of the method parameter val, which is defined in the method setTested

The classes Programmer and Manager inherit the nonprivate variables and methods defined in the class Employee and use them directly, as if they were defined in their own classes. Examine the following code:

class Employee {
    protected String name;
    protected String address;
    protected String phoneNumber;
    protected float experience;
}
class Manager extends Employee {
    protected int teamSize;
    public void reportProjectStatus() {}
}
class Programmer extends Employee {
    private String[] programmingLanguages;
    public void writeCode() {}
    public void accessBaseClassMembers() {   
        name = "Programmer";                 #A
    }   
}

How can the class Programmer assign a value to a variable that’s defined in the class Employee? You can think of this arrangement as follows: When a class inherits another class, it encloses within it an object of the inherited class. Hence, all the nonprivate members (variables and methods) of the inherited class are available to the class, as shown in figure 10.6.

A method without implementation details, or with an empty body is not the same as an abstract method:

public void displayName() { }     #A
public abstract void performance();   #B

Exam Tip A method with an empty body isn’t an abstract method.

 

JUnit in Action MEAP V06

This is an excerpt from Manning's book JUnit in Action MEAP V06.

The JUnit team didn’t invent software testing or even unit tests, of course. Originally, the term unit test described a test that examined the behavior of a single unit of work: a class or a method. Over time, the use of the term unit test broadened. The Institute of Electrical and Electronics Engineers (IEEE), for example, has defined unit testing as “testing of individual hardware or software units or groups of related units” (emphasis added).[4]

Listing 2.16 TestInfo parameters
class TestInfoTest {
    TestInfoTest(TestInfo testInfo) {
        assertEquals("TestInfoTest", testInfo.getDisplayName());        #1
    }
 
    @BeforeEach
    void setUp(TestInfo testInfo) {
        String displayName = testInfo.getDisplayName();
        assertTrue(displayName.equals("display name of the method") ||  #2
                   displayName.equals(                                    #2
                               "testGetNameOfTheMethod(TestInfo)"));      #2
    }
 
    @Test
    void testGetNameOfTheMethod(TestInfo testInfo) {
        assertEquals("testGetNameOfTheMethod(TestInfo)",
                     testInfo.getDisplayName());                          #3
    }
 
    @Test
    @DisplayName("display name of the method")
    void testGetNameOfTheMethodWithDisplayNameAnnotation(TestInfo testInfo) {
        assertEquals("display name of the method",
                     testInfo.getDisplayName());                          #4
    }
}

So far, this book has introduced JUnit and its latest version, 5, and explained the big architectural step between JUnit 4 and JUnit 5. I discussed the core classes and methods and presented them in action so that you have a good understanding of how to build your tests in an efficient way. I emphasized the importance of software architecture in general and shown the big architectural change between JUnit 4 and JUnit 5.

Modern Java in Action: Lambdas, streams, reactive and functional programming

This is an excerpt from Manning's book Modern Java in Action: Lambdas, streams, reactive and functional programming.

To help answer this, we’ll note that the whole point of a programming language is to manipulate values, which, following historical programming-language tradition, are therefore called first-class values (or citizens, in the terminology borrowed from the 1960s civil rights movement in the United States). Other structures in our programming languages, which perhaps help us express the structure of values but which can’t be passed around during program execution, are second-class citizens. Values as listed previously are first-class Java citizens, but various other Java concepts, such as methods and classes, exemplify second-class citizens. Methods are fine when used to define classes, which in turn may be instantiated to produce values, but neither are values themselves. Does this matter? Yes, it turns out that being able to pass methods around at runtime, and hence making them first-class citizens, is useful in programming, so the Java 8 designers added the ability to express this directly in Java. Incidentally, you might wonder whether making other second-class citizens such as classes into first-class-citizen values might also be a good idea. Various languages such as Smalltalk and JavaScript have explored this route.

Experiments in other languages, such as Scala and Groovy, have determined that allowing concepts like methods to be used as first-class values made programming easier by adding to the toolset available to programmers. And once programmers become familiar with a powerful feature, they become reluctant to use languages without it! The designers of Java 8 decided to allow methods to be values—to make it easier for you to program. Moreover, the Java 8 feature of methods as values forms the basis of various other Java 8 features (such as Streams).

The first new Java 8 feature we introduce is that of method references. Suppose you want to filter all the hidden files in a directory. You need to start writing a method that, given a File, will tell you whether it’s hidden. Fortunately, there’s such a method in the File class called isHidden. It can be viewed as a function that takes a File and returns a boolean. But to use it for filtering, you need to wrap it into a FileFilter object that you then pass to the File.listFiles method, as follows:

File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
    public boolean accept(File file) {
        return file.isHidden();                        #1
    }
});

Yuck! That’s horrible. Although it’s only three significant lines, it’s three opaque lines—we all remember saying “Do I really have to do it this way?” on first encounter. You already have the method isHidden that you could use. Why do you have to wrap it up in a verbose FileFilter class and then instantiate it? Because that’s what you had to do prior to Java 8.

Wow! Isn’t that cool? You already have the function isHidden available, so you pass it to the listFiles method using the Java 8 method reference :: syntax (meaning “use this method as a value”); note that we’ve also slipped into using the word function for methods. We’ll explain later how the mechanics work. One advantage is that your code now reads closer to the problem statement.

Here’s a taste of what’s coming: methods are no longer second-class values. Analogous to using an object reference when you pass an object around (and object references are created by new), in Java 8 when you write File::isHidden, you create a method reference, which can similarly be passed around. This concept is discussed in detail in chapter 3. Given that methods contain code (the executable body of a method), using method references enables passing code around as in figure 1.3. Figure 1.4 illustrates the concept. You’ll also see a concrete example (selecting apples from an inventory) in the next section.

Figure 1.4. Passing the method reference File::isHidden to the method listFiles

1.3.3. From passing methods to lambdas

Passing methods as values is clearly useful, but it’s annoying having to write a definition for short methods such as isHeavyApple and isGreenApple when they’re used perhaps only once or twice. But Java 8 has solved this, too. It introduces a new notation (anonymous functions, or lambdas) that enables you to write just

Java Testing with Spock

This is an excerpt from Manning's book Java Testing with Spock.

Several tricks of Groovy magic come from the powerful meta-programming facilities offered during runtime that can change classes and methods in ways impossible with vanilla Java. At the same time, Groovy also supports compile-time macros (abstract syntax tree, or AST, transformations in Groovy parlance). If you’re familiar with macros in other programming languages, you should be aware of the power they bring to code transformations. By using AST transformations, a programmer can add/change several syntactic features of Groovy code, modifying the syntax in forms that were difficult or impossible in Java.

As seen in this listing, Groovy not only supports the autogeneration of getters and setters, but also allows using only the name of the field instead of the method. The getter or the setter is implicitly called according to the surrounding context. Finally, as a shortcut to System.out.println, Groovy makes available the println method to any object.

It’s interesting to note that the def keyword can also be applied in methods, as shown in the following listing. This can trim the size of Spock test methods even further (after omitting the visibility modifier).

Listing 2.7. Groovy optional typing in methods
The Java Module System

This is an excerpt from Manning's book The Java Module System.

We can perceive parts on different levels of abstraction. Between the extremes of methods and entire applications, we can map them to classes, packages, and JARs. They also have names, dependencies, and features.

Figure 8.11 If a method in an automatic module (org.lib in this case) returns a type from the unnamed module (ImmutableList), named modules (your.app) can’t access it, because they don’t read the unnamed module. This crashes the application if the method declares that it returns the inaccessible type (ImmutableList). Declaring a supertype (here, most likely List) would work.

c08_11.png

Quite the opposite: reflection lost its superpowers and is bound to the exact same accessibility rules as compiled code. It can only access public members of public classes in exported packages. These frameworks, on the other hand, use reflection over fields and methods that often aren’t public and on classes that you may not want to export because they aren’t part of a module’s API. What do you do then? That’s what this chapter is all about!

Get Programming with Java MEAP V04 livebook

This is an excerpt from Manning's book Get Programming with Java MEAP V04 livebook.

Now that I have added the Car class and the fields for that class, the next important step is adding the behaviors to our class.  Each behavior is added as a method in Java.  A detailed explanation of methods in Java is in a later lesson, but for this example, I am adding a few simple methods. 

In figure 2.2, I have added methods that represent the behaviors of a car.  Each method has the keyword void before the method name.  This keyword indicates that the method does not return any values. 

Figure 2.2 Code listing of the Car class with methods added
Figure 2.2 Code listing of the Car class with methods added
Listing 7.3 Add a method to calculate the weekly payroll for an employee
1.    //code omitted
 2.    protected double calculateEarnings() {
 3.    double weeklyEarnings;
 4.    if (employeeType == 'h') {                //#A
 5.       if (hoursWorked <= 40) {
 6.          weeklyEarnings = hoursWorked * hourlyWage;
 7.       } else {
 8.          weeklyEarnings = 40 * hourlyWage + ((hoursWorked - 40)
 9.              * hourlyWage * 1.5);
 10.      }
 11.   } else {             //#B
 12.   weeklyEarnings = salary / 52;
 13.   }
 14.   return weeklyEarnings;
 15.   }

Method overloading only occurs within the same class file.  It is used to provide the same method name for multiple methods, but each method contains differences in the parameter list.  Method overriding occurs when a subclass contains the exact same method signature as a method in the superclass.  

Method overloading is sometimes referred to as static polymorphism, which is a fancy way of saying that it is checked at compile time, not run-time.   Method overriding is a form of run-time polymorphism.  This indicates that the method to be invoked is not determined until run-time.

OCA Java SE 8 Programmer I Certification Guide

This is an excerpt from Manning's book OCA Java SE 8 Programmer I Certification Guide.

Options (b) and (d) are incorrect. A method can’t be overridden if it defines a different parameter list.

In this section, you’ll work with the definitions of methods, which may or may not accept input parameters and may or may not return any values.

A method is a group of statements identified with a name. Methods are used to define the behavior of an object. A method can perform different operations, as shown in figure 3.13.

Figure 3.13. Different types of methods

Although the terms method parameters and method arguments are not the same, you may have noticed that many programmers use them interchangeably. Method parameters are the variables that appear in the definition of a method. Method arguments are the actual values that are passed to a method while executing it. In figure 3.15, the variables phNum and msg are method parameters. If you execute this method as sendMsg("123456", "Hello"), then the String values "123456" and "Hello" are method arguments. As you know, you can pass literal values or variables to a method. Thus, method arguments can be literal values or variables.

A method may accept zero or multiple method arguments. The following example accepts two int values and returns their average as a double value:

The following example shows a method that doesn’t accept any method parameters:

void printHello() {
    System.out.println("Hello");
}

If a method doesn’t accept any parameters, the parentheses that follow the name of the method are empty. Because the keyword void is used to specify that a method doesn’t return a value, you may think it’s correct to use the keyword void to specify that a method doesn’t accept any method parameters, but this is incorrect. The following is an invalid definition of a method that accepts no parameters:

  • When a method reassigns the object reference passed to it to another variable
  • When a method modifies the state of the object reference passed to it
  • The method resetValueOfMemberVariable accepts the object referred to by person1 and assigns it to the method parameter p1. Now both variables, person1 and p1, refer to the same object. p1.setName("Rodrigue") modifies the value of the object referred to by the variable p1. Because the variable person1 also refers to the same object, person1.getName() returns the new name, Rodrigue, in the method main. This sequence of actions is represented in figure 3.25.

    Figure 3.25. Modification of the state of an object passed to the method resetValueOfMember-Variable
    Functional Programming in Java: How functional techniques improve your Java programs

    This is an excerpt from Manning's book Functional Programming in Java: How functional techniques improve your Java programs.

    As you’ve seen, functional programming consists in writing programs by composing pure functions, which means functions without side effects. These functions may be represented by methods, or they may be first-class functions, such as the arguments of methods groupBy, map, or reduce, in the previous example. First-class functions are simply functions represented in such a way that, unlike methods, they can be manipulated by the program. In most cases, they’re used as arguments to other functions, or to methods. You’ll learn in chapter 2 how this is done.

    A method creating a Result from a function from T to Boolean and an instance of T might also be useful:

    Java 8 in Action: Lambdas, streams, and functional-style programming

    This is an excerpt from Manning's book Java 8 in Action: Lambdas, streams, and functional-style programming.

    To help answer this, we’ll note that the whole point of a programming language is to manipulate values, which, following historical programming-language tradition, are therefore called first-class values (or citizens, in the terminology borrowed from the 1960s civil rights movement in the United States). Other structures in our programming languages, which perhaps help us express the structure of values but which can’t be passed around during program execution, are second-class citizens. Values as listed previously are first-class Java citizens, but various other Java concepts, such as methods and classes, exemplify second-class citizens. Methods are fine when used to define classes, which in turn may be instantiated to produce values, but neither are values themselves. So does this matter? Yes, it turns out that being able to pass methods around at run-time, and hence making them first-class citizens, is very useful in programming, and so the Java 8 designers added this ability to Java. Incidentally, you might wonder whether making other second-class citizens such as classes into first-class-citizen values might also be a good idea. Various languages such as Smalltalk and JavaScript have explored this route.

    Experiments in other languages such as Scala and Groovy have determined that allowing concepts like methods to be used as first-class values made programming easier by adding to the toolset available to programmers. And once programmers become familiar with a powerful feature, they become reluctant to use languages without it! So the designers of Java 8 decided to allow methods to be values—to make it easier for you to program. Moreover, the Java 8 feature of methods as values forms the basis of various other Java 8 features (such as Streams).

    The first new Java 8 feature we introduce is that of method references. Suppose you want to filter all the hidden files in a directory. You need to start writing a method that given a File will tell you whether it’s hidden or not. Thankfully there’s such a method inside the File class called isHidden. It can be viewed as a function that takes a File and returns a boolean. But to use it for filtering you need to wrap it into a FileFilter object that you then pass to the File.listFiles method, as follows:

    Yuck! That’s horrible! Although it’s only three lines, it’s three opaque lines—we all remember saying “Do I really have to do it this way?” on first encounter. You already have a method isHidden that you could use. Why do you have to wrap it up in a verbose FileFilter class and then instantiate it? Because that’s what you had to do prior to Java 8!

    1.2.3. From passing methods to lambdas

    Passing methods as values is clearly useful, but it’s a bit annoying having to write a definition for short methods such as isHeavyApple and isGreenApple when they’re used perhaps only once or twice. But Java 8 has solved this too. It introduces a new notation (anonymous functions, or lambdas) that enables you to write just

    Listing 11.4. Implementing the getPriceAsync method
    Play for Java

    This is an excerpt from Manning's book Play for Java.

    Any route consists of three parts: the HTTP method, the path, and the action method, as illustrated in figure 2.1.

    Figure 2.1. Components of a route

    Our example route maps any HTTP GET request for ‘/’ to controllers.Application .index(). This means that any GET request for the / (root) URL is handled by the index method on the Application class in the controllers package. We call methods that handle requests action methods.

    Listing 6.8. Product save method with tag relationship

    In addition to the better performance, Scala templates are type-safe. Try to pass the template an object of a different type than expected, and the code that’s trying to call the template function won’t compile. Try to use a method that’s not available for the class of a given object, and the template itself won’t compile.

    Making Java Groovy: Foreword by Guillaume Laforge

    This is an excerpt from Manning's book Making Java Groovy: Foreword by Guillaume Laforge.

    When Java was created, the thinking in the industry was that static typing—the fact that you must declare the type of every variable—was a benefit. The combination of static typing and dynamic binding meant that developers had enough structure to let the compiler catch problems right away, but still had enough freedom to implement and use polymorphism. Polymorphism lets developers override methods from superclasses and change their behavior in subclasses, making reuse by inheritance practical. Even better, Java is dynamically bound by default, so you can override anything you want unless the keyword final is applied to a method.

    Static typing makes Integrated Development Environments useful too, because they can use the types to prompt developers for the correct fields and methods. IDEs like Eclipse and NetBeans, both powerful and free, became pervasive in the industry partly as a result of this convenience.

    In Java one object can only stand in for another if the two classes are related by inheritance or if both implement the same interface. A static reference can only be assigned to an object of that type or one of its subclasses, or a class that implements that interface if the reference is of interface type. In a dynamically typed language, however, we can have any classes stand in for another, as long as they implement the methods we need. In the dynamic world this is known as duck typing: if it walks like a duck and it quacks like a duck, it’s a duck. See figure 1.2.

    Figure 1.2. Arrays and strings from a duck-typing point of view. Each is a collection with an append method. If that’s all we care about, they’re the same.

    We don’t care that a string is not an array as long as it has the append method we need. This example also shows another feature of Groovy that was left out of Java: operator overloading. In Groovy all operators are represented by methods that can be overridden. For example, the + operator uses a plus() method and * uses multiply(). In the previous figure the << operator represents the leftShift() method, which is implemented as append for both arrays and strings.

    Java is firmly rooted in that world. In Java all methods (verbs) must reside inside classes (nouns). You can’t have a method by itself. It has to be in a class somewhere. Most of the time that’s not a big issue, but consider, for example, sorting strings.

    Spring Integration in Action

    This is an excerpt from Manning's book Spring Integration in Action.

    It gets even more interesting and more relevant for our lead-up to Spring Integration when we look at Spring’s support for invoking methods on any Spring-managed object. Sure, the MessageListener interface seems simple enough, but it has a few limitations. First, it requires a dependency on the JMS API. This inhibits testing and also pollutes otherwise pure business logic achieved by relying on the IoC principle. Second, and more severe, it has a void return type. That means you can’t easily send a reply message from the listener method’s implementation. Both of these limitations are eliminated if you instead reference a POJO instance that doesn’t implement MessageListener and add the method attribute to the configuration. For example, let’s assume you want to invoke the following service method:

    Finally, you’ll learn about some AOP capabilities provided by Spring Integration. One such capability is the noninvasive interception of application methods to send messages. Another is the framework’s ability to dynamically generate proxy implementations of an application interface so that invoking a method will send a message.

    The Well-Grounded Java Developer

    This is an excerpt from Manning's book The Well-Grounded Java Developer.

    For example, consider this snippet, in which a null InputStream is returned from a method:

    These aspects can interact in subtle ways. For example, the compilation subsystem uses timers to decide which methods to compile. This means that the set of methods that are candidates for compilation can be affected by concerns such as scheduling and GC. The methods that get compiled could be different from run to run.

    Inlining of methods is entirely automatic, and under almost all circumstances the default parameter values are fine. There are switches to control what size of methods will be inlined, and how often a method needs to be called before becoming a candidate. These switches are mostly useful for the curious programmer to get a better understanding of how the inlining part of the internals works. They aren’t often useful for production code and should be considered something of a last resort as a performance technique, because they may well have other unpredictable effects on the performance of the runtime system.

    Griffon in Action

    This is an excerpt from Manning's book Griffon in Action.

    Both openFile() and quit() look like methods, but they’re actually something different. Groovy has support for closures—reusable blocks of code. Closures are far more versatile than methods in many situations, as you’re about to see.

    A controller, in its most basic form, can be thought of as a collection of action handlers. By now, you shouldn’t be surprised when we tell you that Griffon adds a couple of convenience mechanisms to make working with controllers easy. Just like views, controllers have access to injected properties and methods that will make your job easier. In some circumstances, when a controller is fully initialized, you may want to perform additional setup or initialization. For example, you may want to cache some data from a web service or a database. Griffon provides a post-initialization hook to help you; we’ll look at that too. Once we have that foundation set, we’ll examine the primary purpose of controllers: actions.

    Let’s get started on our dissection of controllers by looking at injected properties and methods.

    An action is nothing more than a closure property or a method that follows a conventional set of arguments. It looks like the following when defined as a closure property:

    def openFile = { evt = null -> ... }

    The alternate form, for an action defined as a method, looks like this:

    5.1.1. Quick tour of injected properties and methods

    Controllers don’t exist in a vacuum. They interact with other parts of the application, such as their view, the model, and the application. To understand controllers, let’s preview some of the information we’ll cover in chapter 6: the properties and methods that are injected into every controller managed by Griffon. We’ll start with four properties.

    Spring Roo in Action

    This is an excerpt from Manning's book Spring Roo in Action.

  • Write methods to retrieve, save, update, delete, and search for entities.
  • Looks pretty empty, doesn’t it? Actually, it’s backed by an AspectJ ITD, CourseIntegrationTest_Roo_IntegrationTest.aj, which is chock-full of tests against the methods in the entity ITDs, thanks to the Roo shell and the @RooIntegrationTest annotation.

    Here’s a small fragment of generated test ITD code for one of the methods, testPersist():

    This interface provides access to the Spring Data features for providing criteria-based query and paging support. The methods accept a Specification class, which is used to define the search criteria to pass to the repository to find, sort, and page through a list of entities, or fetch a single entity. For example, to provide a predicate that expects a non-null run date:

    The toPredicate() method takes a Root<Course>, which provides access to the types in the JPA entity, a JPA CriteriaQuery, which is built by Spring and passed into the method automatically at runtime to be executed, and a CriteriaBuilder, which allows you to add predicates to the query using English language–like calls, such as cb.isNotNull above.

    The Bean Validation API provides an @AssertTrue annotation that can make expressing one-off rules like the one above quite easy. Instead of that three-step process we discussed earlier, you can just build a Boolean method and annotate it with the @AssertTrue annotation. If the method returns true, the entity is valid. If not, it fails validation.

    @RequestMapping(value = "/{id}", params="form"
    
                    method = RequestMethod.GET)
    public String CourseController.updateForm(
                   @PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("course", Course.findCourse(id));
        return "courses/update";
    }
    Portlets in Action

    This is an excerpt from Manning's book Portlets in Action.

    <form id="search" name="... " action="http://localhost:8080/web/guest/home?
    p_p_id=HelloWorldPortlet_WAR_helloWorld_INSTANCE_MrP9
    &amp;p_p_lifecycle=1&amp;p_p_state=normal&amp;p_p_mode=view&amp;
    p_p_col_id=column-1&amp;p_p_col_count=1&amp;
    _HelloWorldPortlet_WAR_helloWorld_INSTANCE_MrP9_action=someAction"
    method="post">

    The following code snippet shows an @RenderMode annotation indicating that the method is a render method for the VIEW portlet mode:

    If a method-level @RequestMapping annotation doesn’t specify the portlet mode and request parameter to which the method maps, the method is the default action or render method of the controller. For instance, the following method-level @RequestMapping annotation indicates that the doSomething method is the default render or action method of the handler class:

    Spring identifies a method as an action, render, resource, or event method based on method arguments and return type. The following listing shows the SomeController handler, in which the method arguments are specified.

    Listing 8.6. Method-level @RequestMapping annotations

    In listing 8.6, the showSomething method is a render method, but it hasn’t been defined to accept RenderRequest and RenderResponse objects; the doSomething method is an action method that only accepts an ActionRequest parameter. You can define action and render methods with such signatures because annotated controllers allow you to have flexible method signatures; you can pass arguments and define return types appropriate for your request-handling method.

    Flex on Java

    This is an excerpt from Manning's book Flex on Java.

    Integrating Flex with Java is what this book is all about. That’s why chapter 5 will demonstrate further how to connect a Flex client more directly to the server side using the open source BlazeDS framework. BlazeDS provides a mechanism for allowing Flex to call methods on Java objects through binary serialization with the Action Message Format or AMF. This is much faster than what’s possible with web services or XML/HTTP(s) because it uses real objects and doesn’t have to marshal XML.

    Even though all the remote components that you use to communicate with external services have methods supporting sending credentials for authentication, this is not an ideal solution because the application would need to hold the username and password, in order for you to manually pass them along with every remote method call you made. Not only is this tedious, it’s error prone. Instead you’ll leverage the ChannelSet to authenticate the user to the server side and maintain a session until you either close the application or log out.

    Figure 7.3. Error when trying to execute a method without authorization

    Moving on to a more finely grained security, you can set up a global method interceptor using AOP pointcut syntax to define a pattern of methods you want to secure. The following code shows an example of this taken from the security.xml file provided by AppFuse.

    <global-method-security>
    <protect-pointcut
    expression=" execution(* *..service.UserManager.getUsers(..))"
    access="ROLE_ADMIN"/>
    </global-method-security>

    This will constrain any call to a method named getUsers contained in a class or interface named UserManager whose package name ends with "service". As you can see this method allows you to apply very complex patterns to define which methods get secured.

    <bean id="issueService" class="org.foj.service.impl.IssueManagerImpl">
    <constructor-arg ref="issueDao"/>
    <constructor-arg ref="commentService"/>
    <security:intercept-methods>
    <security:protect method="save"
    access="ROLE_USER,ROLE_ADMIN" />
    <security:protect method="remove*"
    access="ROLE_ADMIN" />
    </security:intercept-methods>
    </bean>

    The code shows how to secure methods at the bean level in XML by using the Spring application context. This gives you more localized control over the security than the global method illustrated previously, keeping the security constraints closer to the code that it affects.

    public interface IssueManager {

    ...

    @Secured({"ROLE_USER", "ROLE_ADMIN"})
    @RemotingInclude
    Issue save(Issue issue);
    @Secured({"ROLE_ADMIN"})
    @RemotingInclude
    void remove(Long id);

    }

    The code shows the final method of securing the business methods by using the @Secured annotation. This is the most localized method of security and the method you’re going to use in upcoming examples. This keeps the declared security constraints right with the code you’re trying to secure. The other advantage to using the annotations over the other methods is that if people decide to override what you’ve defined in the code, they can override it using the XML configuration.

    JUnit in Action, Second Edition

    This is an excerpt from Manning's book JUnit in Action, Second Edition.

    Here’s a generic description of a typical unit test from our perspective: “Confirm that the method accepts the expected range of input and that the method returns the expected value for each input.”

    This description asks us to test the behavior of a method through its interface. If we give it value x, will it return value y? If we give it value z instead, will it throw the proper exception?

    Listing 4.2. Enforcing a timeout on a method with JUnit

    If later on we create a test case where it’s necessary to replace two ids, and we know they will be generated in sequence, the method is

    IDataSet dataSet = getReplacedDataSet(dataSetName, id, id+1);

    The method changes to

    AspectJ in Action, Second Edition

    This is an excerpt from Manning's book AspectJ in Action, Second Edition.

    The well-known observer design pattern decouples the subject (an object of interest) from observers (objects that need to respond to changes in the subject). When a subject changes its state, it notifies all observers of the change by calling a method such as notify<ChangeType>(), passing it an event object that encapsulates the information about the change. The notification method iterates over all the observers and calls a method on each observer (in message-oriented systems, these details change a bit, but the overall scheme remains the same). The called method in the observer includes the logic appropriate to respond to the event.

    Figure 3.2. Relationship between join points, signature patterns, and pointcuts. Types, methods, and fields all have a signature pattern associated with them (shown with a gray background); it’s a way to identify a program element. Pointcuts use signature patterns to select the associated join points.
    The part before the colon is the advice declaration, which specifies when the advice executes relative to the selected join point—before, after, or around it. The advice declaration also specifies the context information available to the advice body, such as the execution object and arguments, which the advice body can use to perform its logic in the same way a method would use its parameters. It also specifies any checked exceptions thrown by the advice. A before() or after() advice doesn’t declare a return type, but an around() advice declares the return type.
    The part after the colon is the pointcut; the advice executes whenever a join point matching the pointcut is encountered. You can use an advice not just with methods but also with any other kind of join point. For example, you can advise a constructor invocation, field write-access, exception handler, and so forth.
    Just like a method body, the advice body contains the actions to execute. In the example, the around advice prints the time elapsed during advised connection operations. thisJoinPoint is a special variable available in each join point; we’ll discuss it in section 4.5. In around advice, the proceed() statement is a special syntax to carry out the advised operation, as we’ll examine in section 4.3.3.

    Listing 4.1 simulates the network and other failures by making the method throw an exception randomly.

    Listing 4.1. Simulated remote service with high failure rate

    By checking against a randomly generated number, the getReply() method simulates a failure that results in an exception (statistically, the method fails approximately 75 percent of the time—a high failure rate!). When it doesn’t fail, it prints a message and returns 5. Note the use of org.springframework.remoting.RemoteAccessException: an unchecked exception that is thrown by Spring proxy when you implement RMI using Spring’s remoting solution. This example doesn’t use Spring to create proxies, because the local invocation suffices for illustration.

  • It takes arguments in the form of join point context that the advice body can use to perform its logic, just like in a method.
  • Struts 2 in Action

    This is an excerpt from Manning's book Struts 2 in Action.

    Following in the tradition of “support” classes, ActionSupport provides default implementations of several important interfaces. If your actions extend this class, they automatically gain the use of these implementations. This alone makes this class worth learning. However, the implementations provided by this class also provide a great case study in how to make an action cooperate with interceptors to achieve powerfully reusable solutions to common tasks. In this case, validation and text localization services are provided via a combination of interceptors and interfaces. The interceptors control the execution of the services while the actions implement interfaces with methods that are invoked by the interceptors. This important pattern will become clearer as we work through the details of ActionSupport by examining its use in our Struts 2 Portfolio application, which we’ll do a couple of pages from now.

    As far as the full syntax of OGNL goes, we’ll wait a bit on that. In the previous chapter, we saw as much of the OGNL syntax as we needed for writing our input field names that would target our properties. At the most complex, this included expressions that could reference map entries via string and object keys. But OGNL is much more. The OGNL expression language contains many powerful features, including the ability to call methods on the objects you reference. While these advanced features give you a set of flexible and powerful tools with which to solve the thorn that you inevitably find stuck in your side late on a Friday afternoon, they aren’t necessary in the normal course of things. We’ll continue to delay full coverage of the OGNL expression language until the end of this chapter, preferring instead to only introduce as much as we need while demonstrating the tags. The main idea here is to understand the role that the expression language plays in the framework.

    This relatively meaningless example demonstrates an expression that links three subexpressions. As with many languages, each of the first two expressions executes and passes control on to the next expression. The value returned by the last expression is the value returned for the entire expression. Now we’ll see how to invoke methods with OGNL.

    Listing 15.1. Struts action mappings with method specified
    GWT in Practice

    This is an excerpt from Manning's book GWT in Practice.

    Detailed mode preserves the full class name, as well as the method name . For overloaded methods, the signature of the method is encoded into the name, as in the case of the append() method .

    There are some important concepts to grasp about this compilation structure, especially given the way GWT interacts with native JavaScript, through the JavaScript Native Interface (JSNI), which will be discussed in section 1.5.3. The names of your classes and methods in their JavaScript form aren���t guaranteed, even for different compilations of the same application. Use of the special syntax provided with JSNI will let you invoke known JavaScript objects from your Java code and invoke your compiled Java classes from within JavaScript; but you can���t freely invoke your JavaScript when using obfuscated style, predictably. This imposes certain limitations on your development:

    The same-origin policy applies to most elements on the page by default, including most browser plugins such as Flash and Java. However, these plugins do often provide methods to get around this limitation, and we’ll address this later in the chapter. The same-origin policy also extends to the XMLHttpRequest object.

    The curses generally stem from developers being used to the very procedural request-response cycle of traditional web programming. Making a call to the server is not like calling a method on an EJB or other Remote Method Invocation (RMI) exposed object, where the method returns a value and the code continues to execute procedurally. All calls are handled by callbacks. In JavaScript, this is done by attaching closures to the XHR object at runtime. In the Java world of GWT, these callbacks are handled by classes that implement the appropriate interface for receiving the event. While the GWT nomenclature can be a bit mismatched (AsyncCallback for RPC services, or ResponseTextHandler for the HTTPRequest object), all the related constructs follow a traditional Observer design pattern. You implement the observer to the API’s observable.

    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest