text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <title>AspectJ Reference - Porting Notes</title>

© Copyright 1998-2002 Palo Alto Research Center Incorporated,
                 2003-2004 Contributors.
All rights reserved.

AspectJ Porting Notes

Pre-1.2 code

Pre-1.1 code

Pre-1.0.4 code

Pre-1.0rc1 code

Pre-1.0beta1 code

Pre-1.0alpha1 code

Pre-0.8beta3 code

Pre-0.8beta1 code

Pre-0.7beta11 code

Pre-0.7beta10 code

Porting pre-1.2 code to AspectJ 1.2

README-12.html contains a discussion
of the changes between 1.1 and 1.2.  The key points are:

The default AspectJ compiler compliance level is now 1.4 (whereas in
previous releases the default compliance level was 1.3). This has a number
of implications:

 class files generated by the compiler are now JRE v1.2 and upwards
compatible. (At compliance level 1.3, AspectJ generated class files that
were compatible with JRE 1.1 also).

 call pointcuts may match more join points than in the same
program compiled at compliance level 1.3.

The AspectJ compiler can be restored to 1.3 compliance settings by specifying the
"-1.3" option on the command-line.

The following example program illustrates the differences in join point matching
with the call pointcut designator between 1.4 and 1.3 compliance levels.

01 class A {
02   public void doIt() {...};
03 }
04
05 class B extends A {
06   public void doThisToo() {...};
07 }
08
09
10 public class CallsAandB {
11
12  public static void main(String[] args) {
13    B b = new B();
14    A bInDisguise = new B();
15
16    b.doIt();               // AspectJ 1.2 matches here
17    bInDisguise.doIt();     // this is never matched
18  }
19
20 }
21
22 aspect CallPCDMatchingExample {
23
24   before() : call(* B.doIt(..)) {
25     System.out.println("About to call B.doIt(...)");
26   }
27
28 }

When this program is compiled with AspectJ 1.2 using the default compiler options,
it will produce one line of output when it is executed:

About to call B.doIt(...)

The same program compiled under AspectJ 1.1 (or using AspectJ 1.2 with the -1.3 flag specified)
does not produce any output when it is run.

The reason for the additional call pcd match is that prior to compliance level 1.4,
Java compilers produced bytecodes that call A.doIt() (the defining type of the method),
rather than B.doIt() (the declared type in the program text). The generated call to
A.doIt() is not matched by the call pcd used in the before advice.  At
compliance level 1.4, the bytecodes retain the declared type of the receiver in the
program source, generating a call to B.doIt(), which is matched by the call pcd.

This is a good example of why the recommended style is to use call(* doIt(..)) && target(B),
which always matches based on the actual type of the receiver.

New warnings emitted by the compiler for unmatched call pcds. Because users have found
the static type matching used for a type pattern specified in a call pcd confusing
(as evidenced by the example above), AspectJ 1.2 has a new Xlint warning which is enable by default.
The compiler will now produce a warning whenever a call pointcut designator does not match at a
join point, and a user may have expected it to. Compiling the above program using AspectJ 1.2
produces the following compiler output:

CallsAandB.java:24 warning does not match because declaring type is A, if match desired use target(B) [Xlint:unmatchedSuperTypeInCall]
before() : call(* B.doIt(..)) {
           ^^^^^^^^^^^^^^^

	see also: CallsAandB.java:17

1 warning

The warning is telling us that the call pointcut associated with the before advice on line 24 of the source file
does not match at a join point where the user may have expected it to. The source location
corresponding to the unmatched join point is indicated by the "see also" line - in this case line 17 of the
source file. At line 17 we find a call to bInDisguise.doIt(). Since the static type of
bInDisguise is A, this call will never be matched.  The warning also tells us
a possible solution if we intended the pointcut to match at this join point: use
call(* doIt(..) && target(B).

If you find warnings of this kind coming out when you use the AspectJ 1.2 compiler, the recommended fix is to
switch to using the target designator in place of a type pattern in the call pointcut
expression. Note that there is no loss of runtime efficiency here - runtime tests are only added in the cases
where it cannot be determined at compile time whether the type of the receiver will match the type specified in
the target expression. Note that target cannot be used in declare statements.

Use of non-statically determinable pointcut expressions in declare statements has always been forbidden,
but prior to 1.2 the AspectJ compiler did not raise an error if they were used. The AspectJ Language
Semantics appendix states that cflow, cflowbelow, this, target, args and if pointcut
designators cannot be used directly or indirectly (through a user-defined pointcut) inside of a declare
statment. When moving code from 1.1 to 1.2, additional errors may be raised due to the stricter policing of this
rule. The solution is to recode the declare statement avoiding pointcut expressions that may require a run-time test.

Interface constructors no longer supported.
Declaring a constructor on an interface is now (correctly) prohibited,
and there will no longer be a constructor-execution join point for the interface.
To initialize a field declared on an interface, use initialization, e.g.,

int I.i;
after(I i) returning: initialization(I) && this(i) { i.i = 2; }

To pick out the constructor-execution for any implementation of I, try

execution(I+.new(..))

For more information, see bug
	49295.

Declaring a static method on an interface is now (correctly) prohibited.
One workaround is to define a static method on the aspect instead.
For more information, see bug
	47754.

Watch for problems due to incompatible BCEL versions.
AspectJ 1.2 includes a different version of BCEL than AspectJ 1.1.  If you have the older
version of BCEL available earlier on your classpath than the version included in the
1.2 aspectjtools.jar then you will see errors like:

C:\work\test\TestAspect.aj error Internal compiler error
java.lang.NoSuchMethodError: org.apache.bcel.generic.InstructionFactory.
createNewArray(Lorg/apache/bcel/generic/Type;S)Lorg/apache/bcel/generic/Instruction;

This typically happens because the old version of BCEL has been included as a standard
extension in your JVM configuration.  Ensure you have removed it from jre/lib/ext
under your JDK installation.

For more information, see bugs including
	60389,
	59921.

Porting pre-1.1 code to AspectJ 1.1

README-11.html contains a discussion
of the language changes from 1.0 to 1.1.  The high points:

The call(..) pointcut designator is now implemented
only at the call site; by contrast, the AspectJ 1.0 compiler could
also implement it on the callee side.  So in 1.0 if you
compiled a pointcut using call(..) but only passed
the compiler the code for the target of the call, the pointcut
could be implemented.  This is not true for 1.1.  To fix this,
use execution(..) in place of call(..),
or include all calling clients in the compile.
(more info)

Type-patterns are no longer permitted for the defining
type of inter-type declarations.  Replace the pattern with a
type.
In many cases, you can declare members on an interface type,
and then declare that the types picked out by the type-pattern
implement have the interface as their parent.
(more info)

Type-patterns are no longer permitted when specifying
declare soft.
Replace the pattern with a literal type.

Wildcards patterns (foo..*) are no longer
permitted for
this(),
target(), or
args().
Replace the pattern with a literal type or
with a subtype wildcard (Type+).
(more info)

Conflicts will be reported for no-argument constructors
generated by compilers when no constructor is defined
for a class. That means the following code will compile
in 1.0 but not in 1.1:

class C {}
aspect A {
   C.new() {}  // permitted in 1.0; conflict in 1.1
}

One fix is to declare a non-conflicting constructor
by adding arguments (or defining a constructor in the
target class); a better fix might be to do the work of the
declared constructor in advice on the initialization
join point for the object.
(more info)

The pointcut designators
within() and withincode()
 will not pick out
code within the lexical extent of method-local
and anonymous inner types (because these are not
represented as such in bytecode form).  Because
within forms specify staticly-determinable pointcuts,
they might be used in declare error or declare warning
statements, which might produce different results.
(more info)

The compiler will report an error that
the form aspect {name} dominates {list}...
is no longer supported.  It has
been replaced by a new declare statement:

declare precedence : {name} {list}...

(more info)

The field set join point now has a return type of void.
Compiling programs using around advice on these join points might
cause errors unless the return type of the around advice
and the result of any proceed() call is
Object or void.
(more info)

The compiler cannot implement after or around advice for
the handler PCD because the end of exception handlers is
ambiguous in bytecode.  Try to use before advice.
(more info)

Porting pre-1.0.4 code

In versions of AspectJ prior to 1.0.4, the compiler was not
correctly implementing the AspectJ-1.0 language design for some uses
of after returning advice.

 The main change that was made was of after returning advice for
constructor execution join points.  Previously, this advice was legal:

after() returning (Foo f): execution(Foo.new(..)) { ... }

 However, it has always been a part of the 1.0 language design (and
of Java's language design) that constructors themselves (as opposed to
constructor calls) do not return the value of the new object.  Rather,
this is bound to the new object, and the constructor
behaves like a void method.  With that in mind, any code like the
above should be conveted to the form.

after(Foo f) returning: this(f) && execution(Foo.new(..)) { ... }

 In compilers prior to 1.0.4, the following advice could pick out
join points

after() returning (String s): call(void foo()) { ... }

 This is no longer picked out.  This pattern was most commonly used
in highly polymorphic contexts, such as

after() returning (String s): call(* foo()) { ... }

 If you want to capture all calls, binding null objects for those
that would otherwise have no value, you must use the
Object type.

after() returning (Object o): call(* foo()) { ... }

 Uses of both of these forms are highleted with compiler warnings
in the 1.0.4 compiler.

Porting pre-1.0rc1 code

 Aspects can no longer be declared to implement the
Serializable or Cloneable interfaces.  If
you previously used serializable or cloneable aspects, you should
refactor your code to keep the state you need to serialize or clone in
objects associated with the aspects.

Porting pre-1.0beta1 code

 The static modifier is no longer allowed on pointcut
declarations anywhere.  Porting is simple; just remove the static
declarations when you find them.

 Also, though the returns modifier on pointcuts has
not been part of the language since 1.0alpha1, the compiler still
accepted them until now.  If you used this feature, now is the right
time to remove the returns modifier when the compiler
complains about it.

Porting pre-1.0alpha1 code

 The release of AspectJ 1.0alpha1 involved sweeping cleanups of the
language to bring it to 1.0 status.

Pointcuts

Type patterns

Advice

Introduction and
	 static crosscutting

Aspects

Pointcuts

Removing the "s" from pointcuts

 One of the most pervasive changes in porting code written before
1.0alpha1 is the change in some of the pointcut names from plural to
singular, that is, they lose an "s".  In one sense, making this change
in your programs is easy: just go through and whever you see uses of
the pointcuts

calls executions gets sets handlers initializations
staticinitializations

 Just take off the final "s", to make one of

call execution get set handler initialization
staticinitialization

 Often, there will be other changes you should make for each of
these pointcuts, but as for the name, just take off the "s".

 One risk you will have when doing this is creating name conflicts.
If, for example, you named a parameter of a pointcut "set", you should
(for your own sanity -- the compiler doesn't require it) rename it in
the rewritten pointcut.

pointcut sort(Collection set): calls(void addAll(set));
==>
pointcut sort(Collection mySet): call(void addAll(mySet));

 While converting to use singular nouns for the primitive
pointcuts, you may also want to remove the "s" from your user-defined
pointcuts.

pointcut publicCalls(): calls(public * *(..));
==>
pointcut publicCall(): call(public * *(..));

 Of course, your naming conventions are your own, but throughout
these porting notes we will be making these changes in our example
ports.

Removing the receptions pointcut

 Perhaps the largest semantic change in the 1.0 language is the
removal of receptions join points.  They have been merged with call
join points in AspectJ 1.0, so now a call join point doesn't represent
the "caller-side" of a call, but the call itself, both caller and
receiver.

 Changing code that used the receptions pointcut should be
fairly straightforward, depending on whether the pointcut exposed state or
not.

Not exposing state

 Receptions pointcuts that did not expose state can simply be
replaced by the new call and target pointcuts:

receptions(void Foo.m())
==>
target(Foo) && call(void m())

Exposing state

 Some receptions pointcuts exposed the receiving object by
replacing the receiving type with a pointcut formal.  These PCDs
should be rewritten to use the new target pointcut to expose
the receiving object.

pointcut fooCallees(Foo f): receptions(void f.m());
==>
pointcut fooCallee(Foo f): target(f) && call(void m());

 Like other pointcuts,
receptions pointcuts that exposed one or more arguments should be
rewritten to use the args pointcut:

pointcut intPassers(int i, int j): receptions(void Foo.m(i, j));
==>
pointcut intPasser(int i, int j):
    args(i, j) && target(Foo) && call(void m(int, int));

Constructor receptions

 There are two issues with constructor receptions in
particular.

Like constructor calls,
constructor receptions pointcuts had a dynamic character, in that
receptions(C.new()) would capture constructions of not
only C classes, but also of classes that extended C.

 If you want this behaviour, then you need to use the new subtypes
operator, +, on the type name in question.  So,

receptions(C.new())
==>
call(C+.new())

Also like constructor calls,
constructor receptions allowed access to the constructed object in the
same way as any other object.  Since the only advice possible on
constructor receptions join points was after returning
advice, the object was always guaranteed to be there.  But since
constructor call join points allow all kinds of advice it may be that
the object isn't constructed yet (say, in before or around advice).
This is a benefit, in that it allows caching constructed objects

aspect Singleton {
    private C theC = null;

    C around(): call(C.new(..)) {
        if (c == null) theC = proceed();
        return theC;
    }
}

 but it does require some rewriting.  The new object can be
accessed as the return value in after returning advice.  So,

after(Point p) returning (): receptions(p.new(int, int)) { ... }
==>
after() returning (Point p): call(Point+.new(int, int)) { ... }

Fixing state access

 In previous versions of AspectJ, state such as the currently
executing object or a particular argument of a method call could be
accessed from the signatures of many pointcuts, leading to
difficult-to-read forms.  In AspectJ 1.0, all state accesses now use
only three pointcuts

args this target

 which pick out argument values, the currently executing object,
and the target object of a method call or field operation,
respectively.

Using args

 Any time you have a pointcut that has a signature where one of the
arguments was a pointcut or advice formal, just replace that formal
with its type and add an args pointcut.

pointcut intPassers(int i, int j): calls(void Foo.m(i, j));
==>
pointcut intPasser(int i, int j): args(i, j) && call(void Foo.m(int, int));

pointcut stringPassers(String s): receptions(void Foo.m(s, ..));
==>
pointcut stringPasser(String s): args(s, ..) && call(void Foo.m(String, ..));

Rewriting calls

 If a calls pointcut exposed the the receiving object, such as

pointcut fooCallees(Foo f): calls(void f.m());

 then the new version should use the target pointcut
to get at that object

pointcut fooCallee(Foo f): target(f) && call(void Foo.m());

 AspectJ's calls pointcut previously allowed the new object to be
exposed, even though it may not have been constructed yet.  AspectJ
1.0 no longer allows this; you can access the new instance only in
after returning advice, when it is guaranteed that the object was
successfully constructed.  So instead of using the target
pointcut to expose the value, you should use the normal after
returning mechanism:

after(Point p) returning (): calls(p.new(int, int)) { ... }
==>
after() returning (Point p): call(Point+.new(int, int)) { ... }

Rewriting gets and sets

 Exposing the target object of a gets or
sets pointcut should be done the same way it was for
calls pointcuts, with the new target
pointcut.

before(Frame f): gets(Color f.color) { ... }
==>
before(Frame f): target(f) && get(Color Frame.color) { ... }

before(Frame f): sets(Color f.color) { ... }
==>
before(Frame f): target(f) && set(Color Frame.color) { ... }

 In addition, the clumsy syntax for getting the old value of the
field has been eliminated.  For before advice, the port is simple;
just access the field yourself in the body.  Depending on the rest of
your system, you may need to restrict the advice from the aspect body
to eliminiate the circularity.

aspect A {
    before(Frame f, Color c): gets(Color f.color)[c] { ... }
}
==>
aspect A {
    before(Frame f):
            target(f) && get(Color Frame.color) && !within(A) {
        Color c = f.color;
        ...
    }
}

 The same can be done for around advice.  However, the
only way to port after advice that needs the old value is to convert
it to around advice.

aspect A {
    after(Frame f, Color c) returning (): gets(Color f.color)[c] { ... }
}
==>
aspect A {
    void around(Frame f):
            target(f) && get(Color Frame.color) && !within(A) {
        Color c = f.color;
        proceed(f);
        ...
    }
}

 When porting sets pointcuts, the new value of a field
is still available, but not the way it was previously.  Instead of
using the square bracket syntax, we use an args pointcut.
All set join points are assumed to have exactly one argument, which
holds the new value.  So,

after(Color newColor): sets(Color Frame.color)[][newColor] { ... }
==>
after(Color newColor): args(newColor) && set(Color Frame.color) { ... }

 Also, if the field was declared private, in order to get at its
old value the aspect must be declared privileged.

Rewriting handlers

 The value of the exception at an exception handler join point is
now accessed through the args pointcut; all exception
handler join points are treated as having exactly one argument, the
exception value.  So,

before(NotFoundException e): handlers(e) { ... }
==>
before(NotFoundException e): args(e) && handler(NotFoundException) { ... }

Rewriting within

 The within pointcut was not typically used to export
context.  Though it was accidentally possible to do so in versions of
AspectJ before 1.0, it often didn't do what users expected it to.
This loophole has now been closed, and within can only take type
patterns, not pointcut or advice formals.  A use of the
this pointcut will capture what previous implementations
did:

pointcut usesFoo(Foo f): within(f);
==>
pointcut usesFoo(Foo f): this(f) && within(Foo);

Understanding signatures

 Now that we have this, target, and
args pointcuts, all of our signatures are composed of
just types, names, and wildcards; there are no more parameters.

 Also, now that we have the + wildcard to pick out
subtypes, we can make signature
matching much more uniform.

 Previously, some signatures matched based on subtypes, some based
on instanceof, and some exactly.  Now, we have made all signatures
match exactly.

 What does this mean for your program?  Well, it means that you
may have to add + to some of your signatures, depending
on what you meant them to match.

 For example, the pointcut

calls(void m(Object))

 previously picked out all method calls to a method named m that
took one argument, which was a subtype of Object.  Now, however, it
will only pick out method calls to methods that are defined to take
exactly the type Object, which may be a lot fewer join points.  If you
want the old behaviour, simply convert to

call(void m(Object+))

Removing the instanceof pointcut

 The intanceof pointcut has been split into two different
pointcuts, this and target.

 Typically, the instanceof pointcut would only exist in a compound
pointcut, composed (with &&) with another
pointcut.  If the other pointcut was a receptions
pointcut, then instanceof should be converted to
target (and receptions converted to
call).  So,

pointcut stateChanges(Subject s):
    instanceof(s) && receptions(void Button.click());
==>
pointcut stateChange(Subject s):
    target(s) && call(void Button.click());

 In all other cases, instanceof referred to the
currently executing object, and so should be converted into
this

before(Point p): instanceof(p) && executions(* makePolar(..)) { ... }
==>
before(Point p): this(p) && execution(* makePolar(..)) { ... }

pointcut setup(Client c): instanceof(c) && calls(Remote Naming.lookup(String));
==>
pointcut setup(Client c): this(c) && calls(Remote Naming.lookup(String));

Rewriting the initializations pointcut

 Object initialization join points are now more complicated, and
more true to Java's execution model.  Now they bracket all of the
initialization that a class can do, after the return of its super
constructor call (before which no initialization can happen). Previous
versions of AspectJ had object initialization join points that only
included initialization that was made in dynamic initializers and
fields.

 The old behaviour can be recovered with a simple rewrite.

initializations(A)
==>
initialization(A.new(..)) && !execution(A.new(..))

Understanding constructor calls

 Previously, constructor call join points were matched by subtypes,
so calls(Foo.new()) would match both calls to create new
Foo objects, and new SubFoo objects.  The
new call pointcut designator matches types exactly, so if
you want the old behaviour, you should write
call(Foo+.new()).

 Similarly, constructor execution join points were matched by
subtypes.  So the old executions(Foo.new()) is now
represented by execution(Foo+.new()).

 In both of these cases, think before using the + operator; it may
be that you didn't intend subtype matching in the first place.

Removing the hasaspect pointcut

 The hasaspect pointcut is no longer defined, but you
can get the same behaviour using the new if pointcut.

 If the aspect whose presense you are checking for was defined
of eachcflow, of eachcflowbelow, or, more
unlikely, of eachJVM(), then the conversion is simple:

hasaspect(A)
==>
if(A.hasAspect())

 If the aspect was defined of eachobject, then you
will have to expose the current object in your pointcut or advice
parameters:

pointcut cut(): hasaspect(A) ... ;
==>
pointcut cut(Object o): this(o) && if(A.hasAspect(o)) ... ;
or
pointcut cut(Object o): target(o) && if(A.hasAspect(o)) ... ;

 If you were using the hasaspect pointcut to expose
the state of the aspect, then you can get the same state by using
A.aspectOf() in the body of the advice.  For example, if
the aspect A were defined of eachcflow, then

before(A myA): hasaspect(myA) {
    myA.checkStatus();
}
==>
before(): if(A.hasAspect()) {
    A myA = A.aspectOf();
    myA.checkStatus();
}

Removing the withinall pointcut

 The withinall poinctut is no longer defined.  You can use a
combination of within and the new
subtypes operator, +, instead.  You'll save two characters and be
using a simpler and more orthogonal language.

withinall(Foo)
==>
within(Foo+)

Removing returns modifier from pointcuts

The returns keyword is no longer necessary for user-defined
pointcuts.  Simply remove it when you find it.

pointcut publicIntCalls() returns int: calls(public int *(..));
==>
pointcut publicIntCall(): call(public int *(..));

Making some pointcuts static

 In Java, only static members may be accessed by their declaring
type name, like the static method Math.max() can be
accessed.

 Pointcuts now have that property too.  Pointcuts may be declared
to be static, in which case they can be accessed like
MyAspect.move(), or they can be left non-static, in which
case they can be overridden by a subaspect.

 In addition, while pointcuts can still be defined in classes, only
static pointcuts can be defined in classes.

 Porting should be straightforward; just make all your pointcuts in
classes static, and make any pointcut with a qualified
reference static.

Type patterns

Understanding * and .. in type patterns

 Previous versions of AspectJ treated * and .. too cleverly in type
patterns, placing restrictions based on what is a package and what is
a type, and basing their meanings on the definition of a package
hierarchy.

 In AspectJ 1.0, both of these wildcards are defined simply, and
textually:

 The * wildcard alone matches all types.

 The * wildcard in a pattern matches zero or more characters,
       but will not match "."

 The .. wildcard matches any sequence of characters that begins
       and ends with "."

 That's it.

 This change won't affect most programs, but it will make
understanding programs easier.  There is one ugly idiom, however, that
this change disposes of.  If your program includes the type pattern
*..*, which used to match all types, you can replace it with the
much simpler *.

pointcut unaryVoidMethods(): call(void *(*..*));
==>
pointcut unaryVoidMethod(): call(void *(*));

Fixing subtypes in introduction

 The new + operator is used to normalize the many places you want
to use subtypes of some types.

 In introduction forms, you will need to replace
subtypes(<var>TypePattern</var>) type patterns with the
new subtype operator, +.  In the case where you wrote
subtypes(Foo), i.e., the subtypes of a single type,
simply replace this with Foo+.  Otherwise, use the
+ operator as appropriate in <var>TypePattern</var>.

public void (subtypes(Target0 || Target1)).accept(Visitor v) {
    v.visit(this);
}
==>
public void (Target0+ || Target1+).accept(Visitor v) {
    v.visit(this);
}

Advice

Moving the return type of around

 The returns keyword is no longer used for around advice.  Instead,
the return type is declared as it is for methods.  So,

around(Point p) returns void: setters(p) { ... }
==>
void around(Point p): setter(p) { ... }

Adding a throws clause to around

 Around advice must now declare the checked exceptions it throws
with a throws clause, much like a method.

char around(char c) throws java.io.CharConversionException: converter(c) {
    char result;
    try { result = proceed(); }
    catch (Exception e) {
        throw new java.io.CharConversionException();
    }
    if (result == 0) throw new java.io.CharConversionException();
    return result;
}

Understanding advice precedence

 In previous versions of AspectJ, advice precedence within an
aspect was simple: if a piece of advice appeared before another piece,
it was more precedent.  This made perfect sense for
before and around advice, but was the cause
of confusion (even among the AspectJ designers, more than once) for
after advice, as it seemed backward.

 In addition, advice was ordered by kind, in that around advice
always surrounded before and after advice.

 AspectJ 1.0 has changed this; precedence for after
advice is inverted, and advice is no longer ordered by kind.

This won't matter to you unless you write pieces of advice in the
same aspect that apply to the same join point.

If you do, here's what to think about: If you're looking at two
pieces of advice and want to know which has precedence, if either is
after advice, then the second one has precedence.
Otherwise, the first does.

 This allows interesting advice interaction.  In the following
advice, for example, the after throwing advice will catch
the exception thrown by the before advice

aspect A {
    before(): call(void main(..)) {
        throw new RuntimeException();
    }
    after() throwing(RuntimeException e): call(void main(..)) {
         System.err.println("caught you!");
    }
}

 But reversing the order will give the before advice
more precedence, making its exception uncatchable by the after
throwing advice

aspect A {
    after() throwing(RuntimeException e): call(void main(..)) {
         System.err.println("missed you!");
    }
    before(): call(void main(..)) {
        throw new RuntimeException();
    }
}

 Advice in different aspects is ordered by the normal aspect
precedence rules of subtyping and the dominates modifier.

Fixing after returning

 If you use after returning advice and do not need to expose the
return value, you no longer need to write an empty set of parentheses
to indicate that fact.  So,

after(<var>Formals</var>) returning (): <var>Pointcut</var> { ... }
==>
after(<var>Formals</var>) returning: <var>Pointcut</var> { ... }

 The same syntax is now available for after throwing advice, in
case you do not care what Throwable is thrown.

after(<var>Formals</var>) throwing: <var>Pointcut</var> { ... }

Renaming thisStaticJoinPoint

 thisStaticJoinPoint has been renamed
thisJoinPointStaticPart, to reflect that it is now
exactly the static part of thisJoinPoint: It will return
the same object as thisJoinPoint.getStaticPart().

Converting access to thisJoinPoint

 The JoinPoint object hierarchy has been folded into a
single class, org.aspectj.lang.JoinPoint.  A common
pattern in logging, for example, was

before() executions(* myMethod()) {
    ExecutionJoinPoint jp = (ExecutionJoinPoint)thisJoinPoint;
    CodeSignature jp = (CodeSignature)jp.getSignature();
    System.err.println(jp.getParameters());
    System.err.println(jp.getParameterNames());
}

 While there is still a rich hierarchy for signatures, there is
only one JoinPoint type, so this can be rewritten as:

before() executions(* myMethod()) {
    JoinPoint jp = thisJoinPoint;
    CodeSignature jp = (CodeSignature)jp.getSignature();
    System.err.println(jp.getArgs());
    System.err.println(jp.getParameterNames());
}

 Some of the method names of JoinPoint have been
reorganized, as well.

Introduction and static crosscutting

Removing +implements and +extends

 The keywords +implements and +extends no
longer exist.  Instead, AspectJ uses the declare
form for exactly the same functionality.

Point +implements Serializable;
=>
declare parents: Point implements Serializable;

MyButton +extends ButtonAdaptor;
=>
declare parents: MyButton extends ButtonAdaptor;

Using declare soft

 Around advice advice no longer effects the static exception
checking of Java.  This means that the following code previously
compiled:

class C {
    void noExceptionDeclared() {
        exceptionDeclared();
    }
    void exceptionDeclared() throws IOException {}
}
aspect A {
    around(): call(void C.exceptionDeclared()) {
        try { proceed(); }
        catch (IOException e) {}
    }
}

 even though the class C is not compilable on its own (because
noExceptionDeclared actually throws an Exception).

 AspectJ now firmly places everything that affects the type system
of Java, including the declared-exception checking system, into the
space of introduction and declare.  So, in order to state that the
call to exceptionDeclared() will not, actually, throw an exception, we
now "soften" that exception, that is, take it out of the space of
declared exceptions.

declare soft: <var>ExceptionType</var>: <var>Pointcut</var>;

 The pointcuts allowed here are limited; you cannot use pointcuts
that would require runtime information.  But picking out method calls
is just fine.  So in order to make the above example work, one new
declaration is needed:

declare soft: IOException:
    call(void C.exceptionDeclared()) &&
    withincode(void noExceptionDeclared());

Aspects

 The syntax of "of each" modifiers has changed.  For of
eachcflow and of eachcflowbelow, you can simply
replace "of each" with "per".  So,

aspect A of eachcflow(...) { ... }
==>
aspect A percflow(...) { ... }

 If you have any aspects defined of eachJVM(), then
you should either remove that declaration entirely (because this is
the default behaviour), or replace the of eachJVM()
declaration with an issingleton declaration.

aspect of eachJVM() { ... }
==>
aspect A { ... }
or
aspect A issingleton { ... }

 The of eachobject(<var>Pointcut</var>) modifier has
been split into two different forms, of
perthis(<var>Pointcut</var>) and of
pertarget(<var>Pointcut</var>).  Which one you replace with
depends on the <var>Pointcut</var> you use.

 If you use a pointcut that picked out reception join points, then
use pertarget, and rewrite the pointcut to pick out call
join points.  So

aspect Shadow
        of eachobject(receptions(void Point.setX(int)) ||
                      receptions(void Point.setY(int))) {
    ...
}
==>
aspect Shadow pertarget(call(void Point.setX(int)) ||
                        call(void Point.setY(int))) {
    ...
}

 Otherwise, in most cases, use perthis.  When you
convert, remember the meaning of each of these modifiers.
perthis(<var>Pointcut</var>) indicates that an instance
of the aspect should be associated with every object that is
this at each of the join points picked out by
<var>Pointcut</var>, while pertarget(<var>Pointcut</var>)
associates with every object that is the target object at such join
points.

Porting pre-0.8beta3 code

Changing cflow terminology

Overriding abstract pointcuts

Limiting recursive advice

The following changes are only required when porting code written
prior to the 0.8beta3 release of AspectJ.

Changing cflow terminology

 Changing pre-0.8beta3 code that uses AspectJ's control-flow-based
features only requires rewriting occurrences of
eachcflowroot, cflow, and
cflowtop.  No editing of other aspect code is
necessary.

eachcflowroot

 The aspect modifier "of
eachcflowroot(<var>Pointcut</var>)" should now be written more
as "percflow(<var>Pointcut</var>)".

cflow

 In previous versions of AspectJ, the pointcut
cflow(<var>Pointcut</var>) picked out all join points in
the cflow below the join points of <var>Pointcut</var>.  That is, it
did not include the join points of <var>Pointcut</var>, only the join
points in their control flow.

 As of version 0.8beta3,
cflowbelow(<var>Pointcut</var>) has that behavior.
cflow(<var>Pointcut</var>) includes the join points of
<var>Pointcut</var>.

 In many cases, you may not care whether the points of
<var>Pointcut</var> are included or not, and so can safely leave
cflow(<var>Pointcut</var>) pointcut designators alone.
However, if you use the idiom

<var>Pointcut</var> && ! cflow(<var>Pointcut</var>)

 to capture the non-recursive entries to a particular pointcut, you
will definitely want to rewrite that as

<var>Pointcut</var> && ! cflowbelow(<var>Pointcut</var>)

cflowtop

 The primitive pointcut designator
cflowtop(<var>Pointcut</var>) has been removed from the
language, as it is expressible with cflow or
cflowbelow.  All uses of
cflowtop(<var>Pointcut</var>) can be rewritten as:

cflowbelow(<var>Pointcut</var> && ! cflowbelow(<var>Pointcut</var>))

 Though in most cases the following is sufficient

cflow(<var>Pointcut</var> && ! cflowbelow(<var>Pointcut</var>))

Overriding abstract pointcuts

 In previous versions of AspectJ, a concrete aspect would
implicitly override all of its abstract pointcuts with an empty
pointcut.  AspectJ 0.8beta3 enforces the restriction that a concrete
aspect may not have any abstract pointcuts.  Thus the following
extension:

abstract aspect A {
    abstract pointcut pc();
}

aspect B {}

 will no longer compile.

 Adding the new empty pointcut designator

pointcut <var>Id</var>();

 in the declaration of the concrete aspect fixes this problem.

abstract aspect A {
    abstract pointcut pc();
}

aspect B {
    pointcut pc();
}

Limiting recursive advice

 Previously, the compiler silently refrained from applying a piece
of advice to join points within its own advice body.  So, for example,
in

class C {
    static int i;
}

aspect A {
    before(): gets(int C.i) {
        System.err.println("C.i was " + C.i)
    }
}

 The advice would trace all references of the static field
C.i except those in the body of the before.

 The compiler has now removed this special case, and so running the
above example will now cause a StackOverflowException to
be thrown.

 Most cases of this error can be fixed by correctly specifying the
desired pointcut:  In the above example, the intention is clearly not
to trace all references of C.i, just those
outside the aspect.

class C {
    static int i;
}

aspect A {
    before(): get(int C.i) && ! within(A) {
        System.err.println("C.i was " + C.i)
    }
}

 In a very few cases, you may want the advice to be applicable to
other code in the aspect, but not in the particular piece of advice.
In such cases, you can pull the body of the advice into a method and
restrict away from that method (and away from calls to that method):

class C {
    static int i;
}

aspect A {
    public static int getCi() {
        return C.i;                          // will be traced
    }

    before(): get(int C.i) &&
              ! withincode(void A.traceCi())
              ! call(void A.traceCi())      {
        traceCi();
    }
    private void traceCi() {
        System.err.println("C.i was " + C.i) // will not be traced
    }
}

Porting pre-0.8beta1 code

Rewriting introductions

Removing static advice

Fixing aspect-aspect inheritance

Using private introduction

The following changes are only required when porting code written
prior to the 0.8beta1 release of AspectJ.

Rewriting introductions

Syntax

 The syntax of introduction has changed.  Porting most programs
should require some simple editing.  Anywhere you have an introduction
block

introduction <var>GTN</var> {
    ...
}

 simply move the <var>GTN</var> down into the introduction
declarations and remove the block.

For method introduction, place the <var>GTN</var> in front of the
method name, For field introduction, place the <var>GTN</var> in front
of the field name, and for constructor introduction, place the
<var>GTN</var> in front of the new identifier.

introduction Foo {
    public void doStuff() { this.doStuffLater(); }
    public int calorieCount = 3;
    public new(int x) { super(); calorieCount = x; }
}

==>

public void Foo.doStuff() { this.doStuffLater(); }
public int Foo.calorieCount= 3;
public Foo.new(int x) { super(); calorieCount = x; }

 For implements and extends introduction, move the <var>GTN</var>
in front of the new identifiers implements or
extends, and place that in a declare parents
form.

introduction Foo {
    implements Comparable;
    extends Goo;
}

==>

declare parents: Foo implements Comparable;
declare parents: Foo extends Goo;

 In all cases, if the <var>GTN</var> is just a type name, it can be
moved down on its own.  However, if the <var>GTN</var> uses any of
&&, ||, and !, it must
be parenthesized.

introduction subtypes(Foo) && !Goo {
    int x;
}

==>

int (Foo+ && !Goo).x;

Access

If you had an introduction that was referring to private or
protected members of the target class, this will no longer work.  You
will either need to modify your code to avoid this accessibility
issue, or you will need to use the privileged modifier on
the aspect that contains the introduction.

class Counter {
    private int count = 2;
}

aspect ExposeCountersPrivates {
    introduction Counter {
        public int getCount() { return count; }
    }
}

==>
// in 0.8, only privileged aspects can expose a class's privates
privileged aspect ExposeCountersPrivates {
    public int Counter.getCount() { return count; }
}

 If you have introduced private or package-protected members, you
will probably have to re-write some code.  Most previous uses of
introducing privates can be improved by using private introduction
instead.

class C {
}

aspect AddCounter {
    introduction C {
        private int count;
        public int getCount() { return count; }
    }
}

==>
aspect AddCounter {
    private int Counter.count;
    public int Counter.getCount() { return count; }
}

 There is one case that we know of where the inability to perform
the introduction of private members makes 0.7 code difficult to
port to 0.8.  If you were using the introduction of a private
void writeObject(..) or a private void
readObject(..) method to interact with Java's serialization
API, you will need to come up with an alternative design.  Using some
combination of Externalizable,
writeReplace(..) and/or readResolve(..)
methods should allow you to port your code.  If you find this isn't
the case, we'd like to hear about it.

 If you were introducing either a protected member or a
package-private member onto a class in order to override a protected
member that was inherited from a superclass, you will have to make
this introduction public.

Removing static advice

 Static advice has been removed from the language.  Now, every
piece of advice is non-static, meaning that it will run in the context
of an aspect instance.

 If you have an aspect that only contains static advice, has no
"of" clause or is declared "of eachJVM()", and is not extended by
another aspect, simply remove the keyword "static" from all pieces of
advice, and make sure the aspect is not defined with the "abstract"
modifier.

aspect Tracing {
    static before(): executions(* *(..)) {
        System.out.println("Got Here! " + thisJoinPoint);
    }
}

==>

aspect Tracing {
    before(): execution(* *(..)) {
        System.out.println("Got Here! " + thisJoinPoint);
    }
}

 Otherwise, if you have an aspect contains both static and
non-static advice, is extended, or is "of eachObject(...)" or "of
eachcflowroot(...)", you should group your static advice together and
put it in a new aspect, possibly even an inner aspect.

aspect ComplexTracing of eachobject(cflow(executions(void Main.main(..)))) {
    static before(): executions(* *(..)) {
        System.out.println("Got Here! " + thisJoinPoint);
    }
    static after(): executions(* *(..)) {
        System.out.println("Returned! " + thisJoinPoint);
    }

    // some other dynamic advice, fields, etc
}

==>

aspect ComplexTracing of eachobject(cflow(executions(void Main.main(..)))) {
    static aspect AlwaysTracing {
        before(): execution(* *(..)) {
            System.out.println("Got Here! " + thisJoinPoint);
        }
        after(): execution(* *(..)) {
            System.out.println("Returned! " + thisJoinPoint);
        }
    }

    // some other dynamic advice, fields, etc
}

Fixing aspect-aspect inheritance

 Aspects can now only extend abstract aspects.  This restriction
may cause some redesign of aspect hierarchies.  You will probably find
that for the majority of your code the most serious change this
requires is to add an explicit abstract modifier to a
super-aspect that was already implicitly abstract.

aspect BaseTracing {
    abstract pointcut traced();
    before(): traced() {
        System.out.println("Got Here! " + thisJoinPoint);
    }
}

==>

// make this abstract aspect explicitly abstract
abstract aspect BaseTracing {
    ...
}

 This change has also affected the getAspect static
method.  Now, getAspect is only defined on non-abstract
aspects.  Previously, you could call getAspect on an
abstract superaspect and (sometimes) get an instance of a subaspect
back.

This pattern was used in the Spacewar example in the AspectJ
distribution.  We had the class hierarchy

  SpaceObject (abstract)
    |- Ship
    |- Bullet
    |- EnergyPellet

 And the aspect hierarchy

  SpaceObjectDA (abstract)
    |- ShipDA of eachobject(instanceof(Ship))
    |- BulletDA of eachobject(instanceof(Ship))
    |- EnergyPacketDA of eachobject(instanceof(Ship))

 And we would call SpaceObjectDA.getAspect(SpaceObject) to access
the aspect associated with a ship, bullet, or energy pellet.  This
pattern depended on the SpaceObjectDA aspect hierarchy
exactly mirroring the SpaceObject hierarchy, and being
maintained that way.

 A better way to implement this kind of design aspect is to use
private introduction, a new feature of AspectJ.

Using private introduction

 A common pattern for AspectJ programs that need to associate some
state with every object of a particular type has been to use aspects
that are defined of eachobject(instanceof(...)).  A prime
example of this was the BoundPoint aspect of the bean
example: which needed to associate each point with a
PropertyChangeSupport object.

aspect BoundPoint of eachobject(instanceof(Point)) {

    java.beans.PropertyChangeSupport support = null;

    after() returning(Point p): receptions(p.new(..)){
        support = new PropertyChangeSupport(myPoint);
    }

    around(Point p) returns void: receptions(void p.set*(*)) {
        // code that uses support
    }
}

 In the new version of AspectJ, a better way of accomplishing many
of these state association is to use privately introduced fields.
Instead of creating an aspect instance for every Point
object, store the PropertyChagneSupport object in the
Point objects themselves.

aspect BoundPoint {
    private PropertyChangeSupport Point.support = new PropertyChangeSupport(this);

    void around(Point p): setters(p) {
        // code that uses p.support
    }
}

 Just as in the past, the PropertyChangeSupport object is not
accessable to anyone but the aspect, but now less mechanism is needed.

 There are times when changing aspects that are defined of
eachobject(instanceof(...)) may not be reasonable.  If the
aspect instance is stored or passed to other methods, then having a
real of eachobject(instanceof(...)), now written
perthis(this(...)), association may capture the
crosscutting concern best.

Porting pre-0.7beta11 code

Removing two-argument calls

Removing advice from Class declarations

The following changes are only required when porting code written
prior to the 0.7beta11 release of AspectJ.

Removing two-argument calls

 In AspectJ 0.7beta11, the two-argument calls
primitive pointcut designator was deprecated.  Removing these
designators will require different cases depending on what the
original pointcut did.

Calls to static methods

 For pointcuts denoting calls to particular static methods, such as

calls(String, static String valueOf(int)) // deprecated

 the transformation is easy.  Simply make the desired signature
explicit.  Instead of catching all calls to any static method that
happens to have the signature String valueOf(int), catch
calls to that exact method defined in the String class.

call(static String String.valueOf(int))

 Pointcuts denoting calls to classes of static methods can also be
rewritten with these rules.  For example,

calls(my.package.*, static * get*(..)) // deprecated

 should now be written

call(static * my.package.*.get*(..))

Calls to non-static methods

 Many pointcuts denoting calls to non-static methods can be
fixed the same way that those pointcuts denoting calls to static
methods are fixed.  So,

calls(Thread, int getPriority()) // deprecated

 which denotes all calls to nullary int methods named getPriority
when the called object is an instance of the Thread type,
can almost always be rewritten

call(int Thread.getPriority())

 which denotes all calls to the nullary int Thread.getPriority()
method.

 Expanding the signature picks out slightly different join points
than the original two-argument form.  This won't matter for most
programs, but in some cases the differences may be noticable.  In
particular, the expanded-signature form only picks out those calls
where the called object is statically typed to Thread
when its int getPriority() method is called.  If you want
to capture calls to the int Thread.getPriority() method,
regardless of how the called object is statically typed, you shoud use
the different translation:

call(int getPriority()) && target(Thread)

 This will capture all call join points of methods with signature
int Thread.getPriority().

 It will also denote any join points if the Thread type does not
define (possibly abstractly) some int getPriority()
method, though.

Removing advice from Class declarations

 The simplest way to remove an advice declaration from a class is
to simply define the advice declaration in an inner aspect.  So,
instead of

class C {
    static before(): executions(C.new()) { ... } // deprecated
}

 write

class C {
    static aspect ConstructionProtocol {
        static before(): executions(C.new()) { ... }
    }
}

 If your advice doesn't refer to any inner classes or interfaces of
C, you can move the inner aspect out of the class entirely.

class C { ... }

aspect ConstructionProtocol {
    static before(): execution(C.new()) { ... }
}

 Your code will be clearer if you consider the purpose of each
piece of advice when you make this change.  It may be that some of the
advice naturally belongs to another aspect, perhaps already existing.
Or it may be that some pieces of advice in a class are associated to
one concern and some to another; in which case more than aspect would
be appropriate.

Porting pre-0.7beta10 code

Changing access to thisJoinPoint

The following changes are only required when porting code written
prior to the 0.7beta10 release of AspectJ.

Changing access to thisJoinPoint

 In AspectJ 0.7beta10, access to the reflective object
thisJoinPoint substantially changed.  The two parts of
this change were the elimination of the runNext() static
method, and the use of an interface hierarchy represent the join point
object.

thisJoinPoint.runNext() to
proceed()

 The elimination of the runNext() static method
requires almost no porting work.  An automatic replacement of the
string

thisJoinPoint.runNext

 with the string

proceed

 will do the job.  However, if any around advice used the
identifier "proceed" as a formal parameter or local
variable, it must be renamed, and if any aspect used it as a field,
then references to the field in around advice should be made explicit
(prefixing the reference with the aspect name or "this",
depending on whether the field is static or not).

Using thisJoinPoint

 While access to reflective information through
thisJoinPoint is more powerful and regular through its
interface hierarchy, the previous uses must be rewritten.  Changing
your code will likely require manual editing, but in doing so your
code should get simpler and cleaner.

 Many existing uses of the fields on join points can be re-written
to use one of:

thisJoinPoint.toString()

thisJoinPoint.toShortString()

thisJoinPoint.toLongString()

thisJoinPoint.getSignature().toString()

thisJoinPoint.getSignature().toShortString()

thisJoinPoint.getSignature().toLongString()

For example:

System.out.println(thisJoinPoint.className + "." +
                   thisJoinPoint.methodName)

 can be replaced with

System.out.println(thisJoinPoint)

 or

System.out.println(thisJoinPoint.getSignature().toShortString())

 with comparable behavior.

 Accesses to the parameters field of join points should be changed
as follows.  A field access like:

thisJoinPoint.parameters

 must be changed to:

thisJoinPoint.getArgs()

 Accesses to the methodName and className fields of join points
that are not suitable for replacement with a toString method,
should be changed as follows.  Field accesses like:

thisJoinPoint.className

thisJoinPoint.methodName

 must be changed to:

thisJoinPoint.getSignature().getDeclaringType().getName()

thisJoinPoint.getSignature().getName()

 Accessses to the parameterNames and parameterTypes fields of
join points, that are not suitable for conversion to one of the
toString() methods should be changed as follows.  Field access
like:

thisJoinPoint.parameterNames

thisJoinPoint.parameterTypes

 must be changed to:

((CodeSignature)thisJoinPoint.getSignature()).getParameterNames()

((CodeSignature)thisJoinPoint.getSignature()).getParameterTypes()


text:
var zlibpool = exports,
    spdy = require('../spdy');

//
// ### function Pool (compression)
// #### @compression {Boolean} whether to enable compression
// Zlib streams pool
//
function Pool(compression) {
  this.compression = compression;
  this.pool = {
    'spdy/2': [],
    'spdy/3': [],
    'spdy/3.1': []
  };
}

//
// ### function create (compression)
// #### @compression {Boolean} whether to enable compression
// Returns instance of Pool
//
zlibpool.create = function create(compression) {
  return new Pool(compression);
};

var x = 0;
//
// ### function get ()
// Returns pair from pool or a new one
//
Pool.prototype.get = function get(version, callback) {
  if (this.pool[version].length > 0) {
    return this.pool[version].pop();
  } else {
    var id = version.split('/', 2)[1];

    return {
      version: version,
      deflate: spdy.utils.createDeflate(id, this.compression),
      inflate: spdy.utils.createInflate(id)
    };
  }
};

//
// ### function put (pair)
// Puts pair into pool
//
Pool.prototype.put = function put(pair) {
  var self = this,
      waiting = 2;

  spdy.utils.resetZlibStream(pair.inflate, done);
  spdy.utils.resetZlibStream(pair.deflate, done);

  function done() {
    if (--waiting === 0)
      self.pool[pair.version].push(pair);
  }
};

redpajama_set_name: RedPajamaGithub


text:
namespace NewsSystem.Web.Controllers
{
    using System.Web.Mvc;

    using Data.Services.Contracts.NSImages;
    using Base;
    using System;

    public class NSImageController : BaseController
    {
        private INSImageService _nsImageService;

        public NSImageController(INSImageService nsiService)
        {
            _nsImageService = nsiService;
        }

        [HttpGet]
        public ActionResult NSImage(long imageId)
        {
            try
            {
                var imageModel = _nsImageService.GetImageById(imageId);
                return File(imageModel.ByteContent, "image/gif");

            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}


text:
package logbook.util;

import javax.json.JsonNumber;
import javax.json.JsonString;
import javax.json.JsonValue;

/**
 * JSONを読むutilです
 *
 */
public class JsonUtils {

    public static int getInt(JsonValue obj) {
        if (obj instanceof JsonNumber)
            return ((JsonNumber) obj).intValue();
        else if (obj instanceof JsonString)
            return Integer.parseInt(((JsonString) obj).getString());
        throw new IllegalArgumentException();
    }

    public static long getLong(JsonValue obj) {
        if (obj instanceof JsonNumber)
            return ((JsonNumber) obj).longValue();
        else if (obj instanceof JsonString)
            return Long.parseLong(((JsonString) obj).getString());
        throw new IllegalArgumentException();
    }

    public static double getDouble(JsonValue obj) {
        if (obj instanceof JsonNumber)
            return ((JsonNumber) obj).doubleValue();
        else if (obj instanceof JsonString)
            return Double.parseDouble(((JsonString) obj).getString());
        throw new IllegalArgumentException();
    }

}


text:
package org.jasig.portal.events.aggr.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;
import javax.persistence.criteria.Subquery;

import org.jasig.portal.events.aggr.DateDimension;
import org.jasig.portal.events.aggr.dao.DateDimensionDao;
import org.jasig.portal.jpa.BaseAggrEventsJpaDao;
import org.jasig.portal.jpa.OpenEntityManager;
import org.joda.time.DateMidnight;
import org.joda.time.LocalDate;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.stereotype.Repository;

import com.google.common.base.Function;

/**
 * @author Eric Dalquist
 * @version $Revision$
 */
@Repository
public class JpaDateDimensionDao extends BaseAggrEventsJpaDao implements DateDimensionDao {
    private CriteriaQuery<DateDimensionImpl> findAllDateDimensionsQuery;
    private CriteriaQuery<DateDimensionImpl> findAllDateDimensionsBetweenQuery;
    private CriteriaQuery<DateDimensionImpl> findAllDateDimensionsWithoutTermQuery;
    private CriteriaQuery<DateDimensionImpl> findNewestDateDimensionQuery;
    private CriteriaQuery<DateDimensionImpl> findOldestDateDimensionQuery;
    private ParameterExpression<LocalDate> dateTimeParameter;
    private ParameterExpression<LocalDate> endDateTimeParameter;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.dateTimeParameter = this.createParameterExpression(LocalDate.class, "dateTime");
        this.endDateTimeParameter = this.createParameterExpression(LocalDate.class, "endDateTime");

        this.findAllDateDimensionsQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<DateDimensionImpl>>() {
            @Override
            public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
                final CriteriaQuery<DateDimensionImpl> criteriaQuery = cb.createQuery(DateDimensionImpl.class);
                final Root<DateDimensionImpl> dimensionRoot = criteriaQuery.from(DateDimensionImpl.class);
                criteriaQuery.orderBy(cb.asc(dimensionRoot.get(DateDimensionImpl_.date)));
                return criteriaQuery;
            }
        });

        this.findAllDateDimensionsBetweenQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<DateDimensionImpl>>() {
            @Override
            public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
                final CriteriaQuery<DateDimensionImpl> criteriaQuery = cb.createQuery(DateDimensionImpl.class);
                final Root<DateDimensionImpl> dimensionRoot = criteriaQuery.from(DateDimensionImpl.class);
                criteriaQuery.select(dimensionRoot);
                criteriaQuery.where(
                        cb.and(
                                cb.greaterThanOrEqualTo(dimensionRoot.get(DateDimensionImpl_.date), dateTimeParameter),
                                cb.lessThan(dimensionRoot.get(DateDimensionImpl_.date), endDateTimeParameter)
                        )
                    );
                criteriaQuery.orderBy(cb.asc(dimensionRoot.get(DateDimensionImpl_.date)));

                return criteriaQuery;
            }
        });

        this.findAllDateDimensionsWithoutTermQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<DateDimensionImpl>>() {
            @Override
            public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
                final CriteriaQuery<DateDimensionImpl> criteriaQuery = cb.createQuery(DateDimensionImpl.class);
                final Root<DateDimensionImpl> dimensionRoot = criteriaQuery.from(DateDimensionImpl.class);
                criteriaQuery.select(dimensionRoot);
                criteriaQuery.where(cb.isNull(dimensionRoot.get(DateDimensionImpl_.term)));

                return criteriaQuery;
            }
        });

        this.findNewestDateDimensionQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<DateDimensionImpl>>() {
            @Override
            public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
                final CriteriaQuery<DateDimensionImpl> criteriaQuery = cb.createQuery(DateDimensionImpl.class);
                final Root<DateDimensionImpl> dimensionRoot = criteriaQuery.from(DateDimensionImpl.class);

                //Build subquery for max date
                final Subquery<LocalDate> maxDateSub = criteriaQuery.subquery(LocalDate.class);
                final Root<DateDimensionImpl> maxDateDimensionSub = maxDateSub.from(DateDimensionImpl.class);
                maxDateSub
                    .select(cb.greatest(maxDateDimensionSub.get(DateDimensionImpl_.date)));

                //Get the date dimension
                criteriaQuery
                    .select(dimensionRoot)
                    .where(cb.equal(dimensionRoot.get(DateDimensionImpl_.date), maxDateSub));

                return criteriaQuery;
            }
        });

        this.findOldestDateDimensionQuery = this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<DateDimensionImpl>>() {
            @Override
            public CriteriaQuery<DateDimensionImpl> apply(CriteriaBuilder cb) {
                final CriteriaQuery<DateDimensionImpl> criteriaQuery = cb.createQuery(DateDimensionImpl.class);
                final Root<DateDimensionImpl> dimensionRoot = criteriaQuery.from(DateDimensionImpl.class);

                //Build subquery for max date
                final Subquery<LocalDate> maxDateSub = criteriaQuery.subquery(LocalDate.class);
                final Root<DateDimensionImpl> maxDateDimensionSub = maxDateSub.from(DateDimensionImpl.class);
                maxDateSub
                    .select(cb.least(maxDateDimensionSub.get(DateDimensionImpl_.date)));

                //Get the date dimension
                criteriaQuery
                    .select(dimensionRoot)
                    .where(cb.equal(dimensionRoot.get(DateDimensionImpl_.date), maxDateSub));

                return criteriaQuery;
            }
        });
    }

    @Override
    public DateDimension getNewestDateDimension() {
        final TypedQuery<DateDimensionImpl> query = this.createCachedQuery(this.findNewestDateDimensionQuery);
        final List<DateDimensionImpl> resultList = query.getResultList();
        return DataAccessUtils.uniqueResult(resultList);
    }

    @Override
    public DateDimension getOldestDateDimension() {
        final TypedQuery<DateDimensionImpl> query = this.createCachedQuery(this.findOldestDateDimensionQuery);
        final List<DateDimensionImpl> resultList = query.getResultList();
        return DataAccessUtils.uniqueResult(resultList);
    }

    @Override
    @AggrEventsTransactional
    public DateDimension createDateDimension(DateMidnight date, int quarter, String term) {
        final DateDimension dateDimension = new DateDimensionImpl(date, quarter, term);

        this.getEntityManager().persist(dateDimension);

        return dateDimension;
    }

    @Override
    @AggrEventsTransactional
    public void updateDateDimension(DateDimension dateDimension) {
        this.getEntityManager().persist(dateDimension);
    }

    @Override
    public List<DateDimension> getDateDimensions() {
        final TypedQuery<DateDimensionImpl> query = this.createCachedQuery(this.findAllDateDimensionsQuery);

        final List<DateDimensionImpl> portletDefinitions = query.getResultList();
        return new ArrayList<DateDimension>(portletDefinitions);
    }

    @Override
    public List<DateDimension> getDateDimensionsBetween(DateMidnight start, DateMidnight end) {
        final TypedQuery<DateDimensionImpl> query = this.createCachedQuery(this.findAllDateDimensionsBetweenQuery);
        query.setParameter(this.dateTimeParameter, start.toLocalDate());
        query.setParameter(this.endDateTimeParameter, end.toLocalDate());

        final List<DateDimensionImpl> portletDefinitions = query.getResultList();
        return new ArrayList<DateDimension>(portletDefinitions);
    }

    @Override
    public List<DateDimension> getDateDimensionsWithoutTerm() {
        final TypedQuery<DateDimensionImpl> query = this.createQuery(this.findAllDateDimensionsWithoutTermQuery);

        final List<DateDimensionImpl> portletDefinitions = query.getResultList();
        return new ArrayList<DateDimension>(portletDefinitions);
    }

    @Override
    public DateDimension getDateDimensionById(long key) {
        final DateDimension dateDimension = this.getEntityManager().find(DateDimensionImpl.class, key);

        return dateDimension;
    }

    @OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
    @Override
    public DateDimension getDateDimensionByDate(DateMidnight date) {
        final NaturalIdQuery<DateDimensionImpl> query = this.createNaturalIdQuery(DateDimensionImpl.class);
        query.using(DateDimensionImpl_.date, date.toLocalDate());
        return query.load();
    }
}


text:
@interface ViewController2 ()

@property(nonatomic, strong)YTAVPlayer      *player;

@end

@implementation ViewController2

- (void)loadView
{
    [super loadView];

    YTAVPlayerViewClickEventBlock block = ^(YTAVPlayerViewClickEvent event, YTRemoteResponseBlock remoteResponse){

        switch (event)
        {
            case kYTAVPlayerViewClickEventFullScreen:
            {
                NSLog(@"fullscreen");

                if (remoteResponse)
                {
                    remoteResponse(YES);
                }
                break;
            }
            default:
                if (remoteResponse)
                {
                    remoteResponse(YES);
                }
                break;
        }

    };

    self.player = [[YTAVPlayer alloc] init];
    [self.view addSubview: self.player.ytAVPlayerView];
    self.player.ytAVPlayerView.containerViewController = self;
    self.player.ytAVPlayerView.frame = CGRectMake(0, 0, self.view.frame.size.width, 200);
    self.player.ytAVPlayerView.clickEventBlock = block;
    self.player.ytAVPlayerView.backImage = [UIImage imageNamed:@"icon_ad"];
    self.player.ytAVPlayerView.watermark = @"aaaaaaa";
    [self.player play:[NSURL URLWithString:@"http://bj-vp.ml.streamocean.net:8080/out.m3u8"]];
}

@end


text:
a blockquote

followed by an heading


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GenericYearTest.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.AccountingTime.Test
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Linq;

    using FakeItEasy;

    using OBeautifulCode.Assertion.Recipes;
    using OBeautifulCode.AutoFakeItEasy;
    using OBeautifulCode.CodeAnalysis.Recipes;
    using OBeautifulCode.CodeGen.ModelObject.Recipes;

    using Xunit;

    public static partial class GenericYearTest
    {
        [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = ObcSuppressBecause.CA1810_InitializeReferenceTypeStaticFieldsInline_FieldsDeclaredInCodeGeneratedPartialTestClass)]
        static GenericYearTest()
        {
            var referenceGenericYear = A.Dummy<GenericYear>();

            ConstructorArgumentValidationTestScenarios
                .RemoveAllScenarios()
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericYear>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' is < 0",
                        ConstructionFunc = () => new GenericYear(A.Dummy<NegativeInteger>()),
                        ExpectedExceptionMessageContains = new[] { "'year' < '1'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericYear>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' = 0",
                        ConstructionFunc = () => new GenericYear(0),
                        ExpectedExceptionMessageContains = new[] { "'year' < '1'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericYear>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' = 10000",
                        ConstructionFunc = () => new GenericYear(10000),
                        ExpectedExceptionMessageContains = new[] { "'year' > '9999'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    })
                .AddScenario(() =>
                    new ConstructorArgumentValidationTestScenario<GenericYear>
                    {
                        Name = "Constructor should throw ArgumentOutOfRangeException when parameter 'year' > 9999",
                        ConstructionFunc = () => new GenericYear(A.Dummy<PositiveInteger>().ThatIs(_ => _ > 9999, -1)),
                        ExpectedExceptionMessageContains = new[] { "'year' > '9999'" },
                        ExpectedExceptionType = typeof(ArgumentOutOfRangeException),
                    });

            ComparableTestScenarios
                .RemoveAllScenarios()
                .AddScenario(() =>
                    new ComparableTestScenario<GenericYear>
                    {
                        Name = "Comparable Test Scenario",
                        ReferenceObject = referenceGenericYear,
                        ObjectsThatAreLessThanReferenceObject = new[]
                        {
                            referenceGenericYear.TweakBy(-1),
                        },
                        ObjectsThatAreGreaterThanReferenceObject = new[]
                        {
                            referenceGenericYear.TweakBy(1),
                        },
                        ObjectsThatAreEqualToButNotTheSameAsReferenceObject = new[]
                        {
                            referenceGenericYear.DeepClone(),
                        },
                        ObjectsThatAreNotOfTheSameTypeAsReferenceObject = new[]
                            {
                                A.Dummy<object>(),
                                A.Dummy<string>(),
                                A.Dummy<int>(),
                                A.Dummy<int?>(),
                                A.Dummy<Guid>(),
                            }
                            .Concat(TestCommon.GetDummyOfEachUnitOfTimeKind().Where(_ => _.GetType() != typeof(GenericYear)))
                            .ToList(),
                        ObjectsThatDeriveFromScenarioTypeButAreNotOfTheSameTypeAsReferenceObject = new GenericYear[]
                        {
                        },
                    });

            StringRepresentationTestScenarios
                .RemoveAllScenarios()
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericYear>
                    {
                        Name = "String Representation - case 1",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericYear>
                            {
                                SystemUnderTest = new GenericYear(2017),
                                ExpectedStringRepresentation = "2017",
                            },
                    })
                .AddScenario(() =>
                    new StringRepresentationTestScenario<GenericYear>
                    {
                        Name = "String Representation - case 2",
                        SystemUnderTestExpectedStringRepresentationFunc = () =>
                            new SystemUnderTestExpectedStringRepresentation<GenericYear>
                            {
                                SystemUnderTest = new GenericYear(2020),
                                ExpectedStringRepresentation = "2020",
                            },
                    });
        }

        [Fact]
        public static void UnitOfTimeKind__Should_return_Generic___When_called()
        {
            // Arrange
            var unitOfTime = A.Dummy<GenericYear>();

            // Act
            var kind = unitOfTime.UnitOfTimeKind;

            // Assert
            kind.AsTest().Must().BeEqualTo(UnitOfTimeKind.Generic);
        }

        [Fact]
        public static void UnitOfTimeGranularity__Should_return_Year___When_called()
        {
            // Arrange
            var unitOfTime = A.Dummy<GenericYear>();

            // Act
            var granularity = unitOfTime.UnitOfTimeGranularity;

            // Assert
            granularity.AsTest().Must().BeEqualTo(UnitOfTimeGranularity.Year);
        }

        private static GenericYear TweakBy(
            this GenericYear genericYear,
            int amount)
        {
            var result = new GenericYear(genericYear.Year + amount);

            return result;
        }
    }
}


text:
<#
.SYNOPSIS
Generates a code coverage report for PrtgAPI

.DESCRIPTION
The Get-PrtgCoverage cmdlet generates a code coverage report for PrtgAPI. By default, all tests will be executed using the Debug configuration. Coverage analysis can be limited to a subset of tests by specifying a wildcard to the -Name parameter.

When the coverage analysis has completed, a HTML report detailing the results of the analysis will automatically be opened in your default web browser.

.PARAMETER Name
Wildcard used to limit coverage to those whose test names match a specified pattern.

.PARAMETER Type
Types of tests to generate coverage for. If no type is specified, both C# and PowerShell test coverage will be generated.

.PARAMETER Configuration
Build configuration to use when calculating coverage. If no configuration is specified, Debug will be used.

.PARAMETER Legacy
Specifies whether code coverage should be generated using .NET Core CLI tooling (where applicable) or legacy .NET Framework tooling.

.PARAMETER TestOnly
Run the test commands used by OpenCover without collecting coverage.

.PARAMETER SkipReport
Skip generating a HTML report upon generating code coverage.

.EXAMPLE
C:\> Get-PrtgCoverage
Generate a code coverage report

.EXAMPLE
C:\> Get-PrtgCoverage *dynamic*
Generate a code coverage report of all tests whose name contains the word "dynamic"

.LINK
Invoke-PrtgBuild
#>
function Get-PrtgCoverage
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [string]$Name = "*",

        [Parameter(Mandatory = $false)]
        [ValidateSet('C#', 'PowerShell')]
        [string[]]$Type,

        [Parameter(Mandatory=$false)]
        [Configuration]$Configuration = "Debug",

        [ValidateScript({
            if($_ -and !(Test-IsWindows)) {
                throw "Parameter is only supported on Windows."
            }
            return $true
        })]
        [Parameter(Mandatory = $false)]
        [switch]$Legacy,

        [Parameter(Mandatory = $false)]
        [switch]$TestOnly,

        [Parameter(Mandatory = $false)]
        [switch]$SkipReport
    )

    if(!(Test-IsWindows))
    {
        throw "Code coverage is only supported on Windows"
    }

    $coverageArgs = @{
        Name = $Name
        BuildFolder = (Get-SolutionRoot)
        Type = $Type
        Configuration = $Configuration
        IsCore = -not $Legacy
        TestOnly = $TestOnly
    }

    Get-CodeCoverage @coverageArgs

    if($TestOnly -or $SkipReport)
    {
        return
    }

    $date = (Get-Date).ToString("yyyy-MM-dd_HH-mm-ss")

    $dir = Join-Path ([IO.Path]::GetTempPath()) "PrtgCoverage_$($date)"

    Write-Host -ForegroundColor Cyan "Generating coverage report in $dir"

    New-CoverageReport -TargetDir $dir

    Start-Process (Join-Path $dir "index.htm")
}


text:
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GL import _types as _cs
# End users want this...
from OpenGL.raw.GL._types import *
from OpenGL.raw.GL import _errors
from OpenGL.constant import Constant as _C

import ctypes
_EXTENSION_NAME = 'GL_AMD_interleaved_elements'
def _f( function ):
    return _p.createFunction( function,_p.PLATFORM.GL,'GL_AMD_interleaved_elements',error_checker=_errors._error_checker)
GL_ALPHA=_C('GL_ALPHA',0x1906)
GL_BLUE=_C('GL_BLUE',0x1905)
GL_GREEN=_C('GL_GREEN',0x1904)
GL_RED=_C('GL_RED',0x1903)
GL_RG16UI=_C('GL_RG16UI',0x823A)
GL_RG8UI=_C('GL_RG8UI',0x8238)
GL_RGBA8UI=_C('GL_RGBA8UI',0x8D7C)
GL_VERTEX_ELEMENT_SWIZZLE_AMD=_C('GL_VERTEX_ELEMENT_SWIZZLE_AMD',0x91A4)
GL_VERTEX_ID_SWIZZLE_AMD=_C('GL_VERTEX_ID_SWIZZLE_AMD',0x91A5)
@_f
@_p.types(None,_cs.GLuint,_cs.GLenum,_cs.GLint)
def glVertexAttribParameteriAMD(index,pname,param):pass


text:
Learning
========

codes of C++


text:
console.log("*************************************************************************************");
console.log("****** CLASSES ******");
console.log("*************************************************************************************");

// Javascript n'était initialement pas un langage orienté objet (pas dans le sens Java du terme)
// Des concepts ont été rajoutés au fur et à mesure pour ressembler aux langage modernes en adaptant les éléments existant.
// Pour cette raison, la synthaxe n'est pas forcément très intuitive.

// Rappel : en java, une classe se déclare comme ceci
// Note: en javascript on utilise les backquote `` (alt gr + è) pour écrire une chaine de caractère sur plusieurs lignes
`
public class MaClasse {
    // Attribut privé, seulement accessible à l'intérieur de la classe
    private int monAttributPrive;

    // Attribut d'objet public : accessible de partout à partir d'un objet de type MaClasse
    public String monAttributPublic;

    // Attribut de classe public : valeur partagée entre tous les objets de la classe
    public static String monAttributStaticPublic = "Static public";

    // Constructeur : initialise l'objet et ses attributs
    public MaClasse(int attribut){
        this.monAttributPrive = maMethodePrivee(attribut);
    }

    // Méthode d'objet publique (accessible sur tous les objets du type MaClasse)
    public int maMethodePublique(){
        return monAttributPrive;
    }

    // Méthode de classe, qui n'a pas besoin d'un objet pour être appelée
    // par exemple, une méthode utilitaire qui fait un calcul à partir de paramêtres
    public static String maMethodeStatique(int a, int b){
        return a + b;
    }

    // Méthode d'objet privée, accssible uniquement à l'intérieur de la classe
    private int maMethodePrivee(int attribut){
        return attribut + 2;
    }
}
`;

// On  l'utilise comme suit:
`
// création d'un objet à partir de la classe
MaClasse monObjet = new MaClasse(23);

// utilisation d'une méthode d'objet publique
int maValeur = monObjet.maMethodePublique();
// utilisation d'un attribut d'objet public
System.out.println(monObjet.monAttributPublic);

// utilisation d'une méthode de classe publique
int maValeur2 = MaClasse.maMethodeStatique(1,2);
// utilisation d'un attribut de classe public
System.out.println(MaClasse.monAttributStaticPublic);
`;

// En javascript, une classe se déclare de cette manière (entre autre, mais celle là est la plus courante)
function MaClasse(attribut) {
    // variable attachée à l'objet this => variable publique
    this.monAttributPublic = attribut;

    // variable qui n'existe qu'à l'intérieur de la fonction
    // ce qui correspond à peut pret à un attribut privé
    var monAttributPrive = 10;

    // On attache uné méthode à l'objet this => méthode publique
    this.maMethodePublique = function () {
        return monAttributPrive;
    }

    // On définit une méthode dans la classe de manière classique => méthode privée
    function maMethodePrivee(attribut) {
        return this.monAttributPublic + 2;
    }
}

// On est obligé de définir les méthodes statiques en dehors de la classe
MaClasse.monAttributStaticPublic = "Static public";
MaClasse.maMethodeStatique = function (a, b) {
    return a + b;
}

// Un classe JavaScript s'utilise de cette manière:
var monObjet = new MaClasse(10);
// le mot clef "new" indique que l'objet "this" à l'intérieur de la fonction est un nouvel objet vide {}
// il applique la fonction sur "this" (ajout des propriétés) puis il renvoie sa valeur.
console.log("monObjet");
console.log(monObjet);
console.log("monObjet.maMethodePublique()");
console.log(monObjet.maMethodePublique());
console.log("monObjet.monAttributPublic");
console.log(monObjet.monAttributPublic);
console.log("MaClasse.monAttributStaticPublic");
console.log(MaClasse.monAttributStaticPublic);
console.log("MaClasse.maMethodeStatique(1,3)");
console.log(MaClasse.maMethodeStatique(1, 3));

// On peut vérifier si un objet est de type MaClasse avec le mote clé "instanceof" qui renvoie un booléen
console.log("monObjet instanceof MaClass =>");
console.log(monObjet instanceof MaClasse); // renvoie true
console.log("monObjet instanceof Number =>");
console.log(monObjet instanceof Number); // renvoie false


text:
/**
 * Classes for the Monitor Service
 * @module monitor
 */

 // Classes
 import * as monitor from '../monitor'

 // Export
 export { monitor }


text:
/*
 * Do not modify this file. This file is generated from the codedeploy-2014-10-06.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;

using Amazon.CodeDeploy.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;

namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// ListOnPremisesInstances Request Marshaller
    /// </summary>
    public class ListOnPremisesInstancesRequestMarshaller : IMarshaller<IRequest, ListOnPremisesInstancesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
    {
        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public IRequest Marshall(AmazonWebServiceRequest input)
        {
            return this.Marshall((ListOnPremisesInstancesRequest)input);
        }

        /// <summary>
        /// Marshaller the request object to the HTTP request.
        /// </summary>
        /// <param name="publicRequest"></param>
        /// <returns></returns>
        public IRequest Marshall(ListOnPremisesInstancesRequest publicRequest)
        {
            IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeDeploy");
            string target = "CodeDeploy_20141006.ListOnPremisesInstances";
            request.Headers["X-Amz-Target"] = target;
            request.Headers["Content-Type"] = "application/x-amz-json-1.1";
            request.HttpMethod = "POST";

            string uriResourcePath = "/";
            request.ResourcePath = uriResourcePath;
            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                JsonWriter writer = new JsonWriter(stringWriter);
                writer.WriteObjectStart();
                var context = new JsonMarshallerContext(request, writer);
                if(publicRequest.IsSetNextToken())
                {
                    context.Writer.WritePropertyName("nextToken");
                    context.Writer.Write(publicRequest.NextToken);
                }

                if(publicRequest.IsSetRegistrationStatus())
                {
                    context.Writer.WritePropertyName("registrationStatus");
                    context.Writer.Write(publicRequest.RegistrationStatus);
                }

                if(publicRequest.IsSetTagFilters())
                {
                    context.Writer.WritePropertyName("tagFilters");
                    context.Writer.WriteArrayStart();
                    foreach(var publicRequestTagFiltersListValue in publicRequest.TagFilters)
                    {
                        context.Writer.WriteObjectStart();

                        var marshaller = TagFilterMarshaller.Instance;
                        marshaller.Marshall(publicRequestTagFiltersListValue, context);

                        context.Writer.WriteObjectEnd();
                    }
                    context.Writer.WriteArrayEnd();
                }

                writer.WriteObjectEnd();
                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

            return request;
        }

    }
}


text:
"""state -- xmpp connection state and event management"""

from __future__ import absolute_import
from . import interfaces as i
from .prelude import *
import threading

__all__ = ('State', )

### State

class State(object):
    """Manage events, synchronize plugins, keep plugin state."""

    def __init__(self, core, plugins=None):
        self.core = core
        self.plugins = plugins or NoPlugins()

        self.locked = False
        self.schedule = deque()
        self.events = ddict(list)
        self.stanzas = {}
        self.state = {}
        self.rlock = threading.RLock()

    def reset(self, clear_events = False):
        return self.flush(True).clear(clear_events).install()

    def install(self):
        self.plugins.install(self)
        return self

    def activate(self):
        self.plugins.activate(self)
        return self

    def clear(self, clear_events = False):
        log.debug("CLEAR %r %r" % (self.core, self))
        self.locked = False
        self.schedule.clear()
        if clear_events:
            self.events.clear()
        self.stanzas.clear()
        self.state.clear()
        return self

    ## ---------- Plugin State ----------

    def get(self, name, default=None):
        return self.state.get(name, default)

    def set(self, name, value):
        self.state[name] = value
        return self

    ## ---------- Events ----------

    def bind(self, kind, callback):
        log.debug("BIND core: %r state: %r trigger %r: handlers %r" % (self.core, self, kind, callback))
        self.events[kind].append(callback)
        return self

    def one(self, kind, callback):
        return self.bind(kind, Once(callback))

    def unbind(self, kind, callback):
        log.debug("UNBIND core: %r state: %r trigger %r: handlers %r" % (self.core, self, kind, callback))
        if kind in self.events:
            try:
                self.events[kind].remove(callback)
            except ValueError:
                pass
        return self

    def trigger(self, event, *args, **kwargs):
        handlers = self.events.get(event)
        log.debug("core: %r state: %r trigger %r: handlers %r" % (self.core, self, event, handlers))
        if handlers:
            idx = 0; lim = len(handlers)
            while idx < lim:
                handler = handlers[idx]
                log.debug("trigger %r: run %r" % (event, handler))
                self.run(handler, *args, **kwargs)
                if isinstance(handler, Once):
                    del handlers[idx]
                    lim -= 1
                else:
                    idx += 1
        return self

    ## ---------- Stanzas ----------

    def is_stanza(self, name):
        return name in self.stanzas

    def bind_stanza(self, name, callback, replace=True):
        exists = self.stanzas.get(name)
        if exists and not replace:
            raise ValueError('The %r stanza is handled by %r.' % (
                name,
                exists
            ))
        self.stanzas[name] = callback
        return self

    def one_stanza(self, name, callback, *args, **kwargs):
        return self.bind_stanza(name, Once(callback), *args, **kwargs)

    def unbind_stanza(name, callback=None):
        try:
            if not callback or self.stanzas[name] is callback:
                del self.stanzas[name]
        except KeyError:
            pass
        return self

    def trigger_stanza(self, name, *args, **kwargs):
        handler = self.stanzas.get(name)
        if not handler:
            raise i.StreamError(
                'unsupported-stanza-type',
                'Unrecognized stanza %r.\nstanzas: %r\nevents: %r\nstate: %r\nlocked: %r\ncore: %r\nplugins: %r\ncore.authJID: %r' % (name, self.stanzas, self.events, self.state, self.locked, self.core, self.plugins, self.core.authJID)
            )
        elif isinstance(handler, Once):
            del self.stanzas[name]
        return self.run(handler, *args, **kwargs)

    ## ---------- Synchronization ----------

    @contextmanager
    def lock(self):
        """A re-entrant lock that guards events and writes to the
        stream.  This is useful for coordinating activity across many
        plugins.  When the lock is released, pending jobs are run."""

        orig = self.locked
        self.rlock.acquire()
        try:
            self.locked = True
            log.debug("%r %r -> LOCKED" % (self, orig))
            yield self
        finally:
            self.rlock.release()
            self.locked = orig
            log.debug("%r LOCKED -> %r" % (self, orig))
            if not orig:
                log.debug("%r UNLOCKED, flushing" % self)
                self.schedule and self.flush()

    def run(self, method, *args, **kwargs):
        """Run or schedule a job; if delayed, it will be run later
        through flush()."""

        if self.locked:
            self.schedule.append(partial(method, *args, **kwargs))
            return self

        with self.lock():
            log.debug("++++ running  method %r" % method)
            if isinstance(method, partial):
                log.debug("    ====> %r" % method.func)
            method(*args, **kwargs)
            log.debug("---- finished method %r" % method)
        return self

    def flush(self, force=False):
        """Try to flush any scheduled jobs."""

        if not self.schedule or (self.locked and not force):
            return self

        try:
            self.locked = True
            while self.schedule:
                name = "%r" % self.schedule[0]
                log.debug("++++ delayed running method %s" % name)
                if isinstance(self.schedule[0], partial):
                    log.debug("     ====> %r" % self.schedule[0].func)
                self.schedule.popleft()()
                log.debug("---- delayed finished method %s" % name)
            return self
        finally:
            self.locked = False

class Once(namedtuple('once', 'callback')):
    """An event handler that should only be called once."""

    def __call__(self, *args, **kwargs):
        return self.callback(*args, **kwargs)

class NoPlugins(i.PluginManager):

    def install(self, state):
        pass

    def activate_default(self, state):
        pass


text:
function die() {
  echo "$@"
  exit 1
}

# Find enlistment root
cd $(dirname $0) >/dev/null
SDK=$(git rev-parse --show-toplevel) ||
  die "Could not access git"

# Build all samples
cd $SDK/samples
for SAMPLE in *; do
  if [[ -d $SAMPLE ]]; then
    cd $SAMPLE
    ant clean ||
      die "Error running 'ant clean' on sample $SAMPLE"
    ant debug ||
      die "Error running 'ant debug' on sample $SAMPLE"
    cd ..
  fi
done

# Remove any stale test bits, ignore errors here
adb uninstall com.facebook.sdk.tests 2>/dev/null

# Build and run tests
cd $SDK/facebook/tests
ant clean ||
  die "Error running 'ant clean' on facebook sdk"
ant debug install ||
  die "Error running 'ant debug install' on facebook sdk"
ant run-tests ||
  die "Error running 'ant run-tests' on facebook sdk"