creating custom java functions

  • Upload
    karlo

  • View
    259

  • Download
    0

Embed Size (px)

Citation preview

  • 8/9/2019 creating custom java functions

    1/16

    Creating Custom Java Functions

    Contents

    Custom Java Function SamplesCreating Custom Java Simple Functions

    Creating Custom Java Aggregate Functions

    Method Parameter and Return Types

    Related Topics

    You can call custom Java functions directly in StreamBase epressions !y an alias defined in the serverconfiguration file" or !y using the calljava() function# The StreamBase epression language provides

    t$o forms of thecalljava() function" to !e used in StreamBase simple and aggregate epressions#

    This topic provides guidelines for creating StreamBase custom functions in Java#

    Note

    StreamBase Studio ships $ith ne$ pro%ects configured !y default to !uild $ith Java As ofrelease '#(" Java ) is no longer supported $ithin Studio or for developing Custom *tensions"including Java functions#

    Custom Java Function Samples

    The StreamBase installation includes the source files for t$o custom Java function samples+

    Sample Described in

    custom,%ava,function Custom Java Simple Function Sample

    custom,%ava,aggregate Custom Java Aggregate Function Sample

    Custom aggregate functions are !uilt !y etendingthe com.streambase.sb.operator.AggregateWindow  class of the StreamBase Java Client li!rary#

    This class is descri!ed in Java AP- .ocumentation#

    Creating Custom Java Simple Functions

    Simple custom Java functions can !e called in epressions in the contet of most StreamBasecomponents" other than the Aggregate operator# Follo$ these steps to create a custom Java simple

    function+

    • /se the New StreamBase Java Function $i0ard to create the !ase code" as descri!ed in /sing

    the StreamBase Java Function 1i0ard#

    • -mplement a public static in a pu!lic Java class#

    • 2!serve the guidelines in Method Parameter and Return Types#

    For eample" Hypotenuse.java in the sample application declares the follo$ing class and method+

    public class Hypotenuse {

      public static double calculate(double a, double b) {

      return Math.srt(a!a " b!b)#  $

    $

    At compile time" the calljava() implementation loo3s for only a single method matching the eact

    types of the function call in the StreamBase epression# But there can !e multiple matching methods"such as these t$o functionally e4uivalent ones+

    http://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_sampleshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_creatingjavasimplehttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_creatingjavaaggregatehttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_relatedtopicshttp://www.streambase.com/developers/docs/latest/reference/sbdxml.html#sbdxml_customfunctionhttp://www.streambase.com/developers/docs/latest/reference/sbdxml.html#sbdxml_customfunctionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_calljava_functionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_calljava_functionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_calljava_functionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_aggregatecalljava_functionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_aggregatecalljava_functionhttp://www.streambase.com/developers/docs/latest/samplesinfo/Custom_Java_Function.htmlhttp://www.streambase.com/developers/docs/latest/samplesinfo/Custom_Java_Aggregate.htmlhttp://www.streambase.com/developers/docs/latest/apidocs/java/index.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_creatingjavasimplehttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_creatingjavaaggregatehttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_relatedtopicshttp://www.streambase.com/developers/docs/latest/reference/sbdxml.html#sbdxml_customfunctionhttp://www.streambase.com/developers/docs/latest/reference/sbdxml.html#sbdxml_customfunctionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_calljava_functionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_calljava_functionhttp://www.streambase.com/developers/docs/latest/reference/expressions.html#expressions_aggregatecalljava_functionhttp://www.streambase.com/developers/docs/latest/samplesinfo/Custom_Java_Function.htmlhttp://www.streambase.com/developers/docs/latest/samplesinfo/Custom_Java_Aggregate.htmlhttp://www.streambase.com/developers/docs/latest/apidocs/java/index.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_samples

  • 8/9/2019 creating custom java functions

    2/16

    public static boolean is%ero(int i) { return i && '# $

    public static oolean is%ero(nteger i) {

      return i && null * null + oolean.value-(i.intalue() && ')#

    $

    -f this case occurs" StreamBase thro$s an error#

    Creating Custom Java Aggregate Functions

    Follo$ these steps to create a custom Java aggregate function+

    • /se the New StreamBase Java Function $i0ard to create the !ase code" as descri!ed in /sing

    the StreamBase Java Function 1i0ard#

    • .efine a Java class that etends

    the com.streambase.sb.operator.AggregateWindow  class#

    • 2!serve the guidelines in Method Parameter and Return Types#

    • 2!serve the guidelines in the annotations to the eample !elo$#

    Consider the follo$ing annotated eample+

    pac/age com.mycompany#

    import com.streambase.sb.operator.AggregateWindow#

    public class My0tdev e1tends AggregateWindow {

      private double sum#

      private double sum-0uares#

      private int count#

      public void init() {

      sum & sum-0uares & '.'#

      count & '#

      $

    public double calculate() {

      return Math.srt((count ! sum-0uares 2 sum!sum) 3 count!(count24))#

      $

      public void accumulate(double value) {

      sum "& value#  sum-0uares "& value!value#

      ""count#

      $

      public void release() { 3! nothing to release in this e1ample !3 $

    $

    The follo$ing annotations descri!e points of interest in the preceding eample+

    .eclare a pu!lic class that etends the AggregateWindow class 5as documented in the

    StreamBase Java Client li!rary6#

    The init() method is called at the start of each ne$ use of the class# Since custom aggregate

    o!%ects are li3ely to !e reused" perform all initiali0ation in init() rather than in the

    constructor# 5The constructor is called only once" $hile init() is called !efore each use#6

    Your implementation must contain a calculate() method that ta3es no arguments and returns

    http://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputshttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/javafunctionwizd.htmlhttp://www.streambase.com/developers/docs/latest/apiguide/customjavafunctions.html#customjavafunctions_javainputsandoutputs

  • 8/9/2019 creating custom java functions

    3/16

    a value that is converti!le to a StreamBase data type# The calculate() method may !e called

    several times" or not at all#

    Your implementation must provide at least one accumulate() method" and can optionally

    provide several overloaded accumulate() methods" one per data

    type# calljava() determines $hich one to call !ased on type# The argument typesfor accumulate() and the return type for calculate() can !e any of the types descri!ed in

    the ta!le in the net section#

    The release() method is called at the end of each use of the class#

    Method Parameter and Return !pes

    The method can have any num!er of parameters" including none# *ach parameter must !e a Javaprimitive or o!%ect type corresponding to a StreamBase data type as sho$n in the follo$ing ta!le+

    StreamBase Data !pe Java Primitive Java "b#ect

    !lo! 7 com#stream!ase#s!#ByteArray8ie$

    !ool !oolean %ava#lang#Boolean

    dou!le dou!le %ava#lang#.ou!le

    int int %ava#lang#-nteger

    long long %ava#lang#9ong

    list primitive:type;< %ava#util#9ist

    string !yte;< %ava#lang#String

    timestamp 7 com#stream!ase#s!#Timestamp

    tuple 7 com#stream!ase#s!#Tuple

    Notes

    • For simple functions" the return type cannot !e void" and must !e one of the Java primitive or

    Java 2!%ect types sho$n a!ove#

    • You can use java.lang.0tring any$here a !yte;< is accepta!le as an argument or return

    value# -n this case" the StreamBase string is transparently converted to or froma java.lang.0tring using the system default encoding#

    • -f a parameter=s type is !yte;< and its value is null" it is represented as a Java null# 9i3e$ise"

    if a Java method $ith a !yte;< return type returns a null" the calling StreamBase epression $illsee the return value as string5null6#

    • You can pass a list of lists to functions epecting multi,dimensional array arguments# You can

    mi list and array notations $hen doing this# That is" a t$o,dimensional list of dou!les can !epassed to functions accepting any of the follo$ing arguments+

    o double5656

    o list7double568

    o list7list7double88

    Note

    2nly Java primitive arrays and string arrays are compati!le $ith lists" not comple data typessuch as timestamps or tuples# .ata type coercion is not supported#

    Note

    1hen an array argument has more than t$o dimensions" you cannot use a function alias# Youmust invo3e the function via calljava()#

    • For !etter performance" Java functions can return arrays in place of lists# For eample" the

    follo$ing return types are e4uivalent+

    • double56 -oo() {$ 33 && list(double)

  • 8/9/2019 creating custom java functions

    4/16

    • double565656 -oo() {$ 33 && list(list(list(double)))

    • -f the parameter or return type is list or tuple" you must either provide a custom function

    resolver" or must define the argument types in a custom2-unction element in the server

    configuration file# See Custom Functions $ith Comple .ata Types for details#

    • -f any value of a parameter $ith a primitive type is null at runtime" the method that

    implements the custom function is not invo3ed# >o$ever" Java 2!%ect parameter types can !e usedto pass in null parameter values#

    For eample" if a StreamBase custom function call $ould involve converting aStreamBase int(null) or bool(null) value to a primitive Java int or boolean" the method is

    not called" and null is assumed as the return value#

    public static boolean is%ero(int i) { return i && '# $

    calljava(9:he;lass9, 9is%ero9, 4) 3! -alse !

    calljava(9:he;lass9, 9is%ero9, ') 3! true !3

    calljava(9:he;lass9, 9is%ero9, int(null)) 3! null !3

    Related opics• Simple call%ava56 function

    • Aggregate call%ava56 function• Java AP- .ocumentation

    • Class Aggregate1indo$

    • StreamBase Custom Java Function Sample

    • StreamBase Custom Java Aggregate Sample

    Creating Method:

    Considering the following example to explain the syntax of a method:

    public static int -unc

  • 8/9/2019 creating custom java functions

    5/16

    • Functions: They return value.

    Method definition consists of a method header and a method body. The same is shown below:

    modi-ier return:ype name-Method (=arameter >ist) {

     33 method body

    $

    The syntax shown above includes:

    • modifier: It defines the access type of the method and it is optional to use.

    • returnType: Method may return a value.

    • nameOfMethod: This is the method name. The method signature consists of the method name and the

    parameter list.

    • Parameter List: The list of parameters, it is the type, order, and number of parameters of a method. These

    are optional, method may contain zero parameters.

    • method body: The method body defines what the method does with statements.

    Example:

    Here is the source code of the above defined method called max(). This method takes two parameters num1 and

    num2 and returns the maximum between the two:

    3!! the snippet returns the minimum between two numbers !3

    public static int min?unction(int n4, int n@) {

      int min#

      i- (n4 8 n@)

      min & n@#

      else

      min & n4#

      return min#

    $

    Method Calling:

    For using a method, it should be called. There are two ways in which a method is called i.e. method returns a value or

    returning nothing (no return value).

    The process of method calling is simple. When a program invokes a method, the program control gets transferred to

    the called method. This called method then returns control to the caller in two conditions, when:

    • return statement is executed.

    • reaches the method ending closing brace.

  • 8/9/2019 creating custom java functions

    6/16

    The methods returning void is considered as call to a statement. Lets consider an example:

    0ystem.out.println(9:his is tutorialspoint.com9)#

    The method returning value can be understood by the following example:

    int result & sum(B, C)#

    Example:

    Following is the example to demonstrate how to define a method and how to call it:

    public class D1ampleMin

  • 8/9/2019 creating custom java functions

    7/16

    public class D1ampleoid {

      public static void main(0tring56 args) {

      methodEan/=oints(@FF.G)#

      $

      public static void methodEan/=oints(double points) {

      i- (points 8& @'@.F) {

      0ystem.out.println(9Ean/+A49)#

      $

      else i- (points 8& 4@@.) {

      0ystem.out.println(9Ean/+A@9)#

      $

      else {

      0ystem.out.println(9Ean/+AI9)#

      $

      $

    $

    This would produce the following result:

    Ean/+A4

    Passing Parameters by Value:

    While working under calling process, arguments is to be passed. These should be in the same order as their

    respective parameters in the method specification. Parameters can be passed by value or by reference.

    Passing Parameters by Value means calling a method with a parameter. Through this the argument value is passed to

    the parameter.

    Example:

    The following program shows an example of passing parameter by value. The values of the arguments remains the

    same even after the method invocation.

    public class swappingD1ample {

      public static void main(0tring56 args) {

      int a & I'#

      int b & F#

      0ystem.out.println(9e-ore swapping, a & 9 "

      a " 9 and b & 9 " b)#

      33 nvo/e the swap method

  • 8/9/2019 creating custom java functions

    8/16

      swap?unction(a, b)#

      0ystem.out.println(9Jn!!

  • 8/9/2019 creating custom java functions

    9/16

      int result4 & min?unction(a, b)#

      33 same -unction name with di--erent parameters

      double result@ & min?unction(c, d)#

      0ystem.out.println(9Minimum alue & 9 " result4)#

      0ystem.out.println(9Minimum alue & 9 " result@)#

      $

      33 -or integer

      public static int min?unction(int n4, int n@) {

      int min#

      i- (n4 8 n@)

      min & n@#

      else

      min & n4#

      return min#

    $

      33 -or double

      public static double min?unction(double n4, double n@) {

      double min#

      i- (n4 8 n@)

      min & n@#

      else

      min & n4#

      return min#

    $

    $

    This would produce the following result:

    Minimum alue & B

    Minimum alue & G.I

    Overloading methods makes program readable. Here, two methods are given same name but with different

    parameters. The minimum number from integer and double types is the result.

    Using Command-Line Arguments:

    Sometimes you will want to pass information into a program when you run it. This is accomplished by passing

    command-line arguments to main( ).

    A command-line argument is the information that directly follows the program's name on the command line when it is

    executed. To access the command-line arguments inside a Java program is quite easy.they are stored as strings in

    the String array passed to main( ).

  • 8/9/2019 creating custom java functions

    10/16

    Example:

    The following program displays all of the command-line arguments that it is called with:

    public class ;ommand>ine {

      public static void main(0tring args56){

    -or(int i&'# i7args.length# i""){

      0ystem.out.println(9args59 " i " 96+ 9 "

      args5i6)#

      $

      $

    $

    Try executing this program as shown here:

    java ;ommand>ine this is a command line @'' 24''

    This would produce the following result:

    args5'6+ this

    args546+ is

    args5@6+ a

    args5I6+ command

    args56+ line

    args5F6+ @''

    args5B6+ 24''

    The Constructors:

    A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a

    method. However, constructors have no explicit return type.

    Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform

    any other startup procedures required to create a fully formed object.

    All classes have constructors, whether you define one or not, because Java automatically provides a default

    constructor that initializes all member variables to zero. However, once you define your own constructor, the default

    constructor is no longer used.

    Example:

    Here is a simple example that uses a constructor:

    33 A simple constructor.

    class My;lass {

      int 1#

  • 8/9/2019 creating custom java functions

    11/16

     

    33 ?ollowing is the constructor

      My;lass() {

      1 & 4'#

      $

    $

    You would call constructor to initialize objects as follows:

    public class ;onsKemo {

      public static void main(0tring args56) {

      My;lass t4 & new My;lass()#

      My;lass t@ & new My;lass()#

      0ystem.out.println(t4.1 " 9 9 " [email protected])#

      $

    $

    Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor

    in the same way that they are added to a method, just declare them inside the parentheses after the constructor's

    name.

    Example:Here is a simple example that uses a constructor:

    33 A simple constructor.

    class My;lass {

      int 1#

     

    33 ?ollowing is the constructor

      My;lass(int i ) {

      1 & i#

      $

    $

    You would call constructor to initialize objects as follows:

    public class ;onsKemo {

      public static void main(0tring args56) {

      My;lass t4 & new My;lass( 4' )#

      My;lass t@ & new My;lass( @' )#

      0ystem.out.println(t4.1 " 9 9 " [email protected])#

      $

    $

  • 8/9/2019 creating custom java functions

    12/16

    This would produce the following result:

    4' @'

    Variable Arguments(var-args):JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the

    method is declared as follows:

    type

  • 8/9/2019 creating custom java functions

    13/16

    It is possible to define a method that will be called just before an object's final destruction by the garbage collector.

    This method is calledfinalize( ), and it can be used to ensure that an object terminates cleanly.

    For example, you might use finalize( ) to make sure that an open file owned by that object is closed.

    To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever itis about to recycle an object of that class.

    Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

    The finalize( ) method has this general form:

    protected void -inaliLe( )

    {

      33 -inaliLation code here

    $

    Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.

    This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends

    before garbage collection occurs, finalize( ) will not execute.

    Method Headers

    We summarize method headers, define the signature of amethod, and discuss its use. This material is covered in

    more detail in the course text, Gries/Gries.

    A method declaration consists of a specification (as a

    comment, a method header , and a !od". Here is a methoddeclaration#

    3!! & 91 is in the range 4..F'9. !3

     public boolean is>ess(int 1) {

      return  1 8& 4 1 7& F'#

    $

    Here is the format of the method header $e use in this

    class for the three %inds of methods in &ava, giving

    information a!out calls on each %ind of method, $ith a fe$notes !elo$#

    http://www.cs.cornell.edu/courses/cs1130/2011sp/module2/module2part1/methodHeaders.html#signaturehttp://www.cs.cornell.edu/courses/cs1130/2011sp/module2/module2part1/methodHeaders.html#signature

  • 8/9/2019 creating custom java functions

    14/16

    'ind of

    methodormat of header A call on a method#

    procedure  public void )name*

    (  +

    s a statement.

    function  public )return-type* )name*

    s an expression, $hich "ields a value.

    constructo

    r

     public )class-name*

    ( ) parameter-list *

    Appears in a ne$-expression or as the first

    statement of a constructor.

    Notes

    • 'e"$ord public ma" !e replaced !" private,if "ou $ant the method to !e accessi!le onl" in the class in

    $hich it is declared.

    • The )name* is an" &ava identifier. onventions for it

    are covered !elo$.

    The )return-type* is the )type* of the valuereturned !" the function. t could !e a primitive t"pe or aclass t"pe.

    • The ) parameter-list * contains declarations of the

    parameters of the method. t is a (possi!l" empt"

    seuence of declarations separated !" commas. 0ach

    declaration has the form )type* )variable-name*.

    • The )class-name* is the name of the class in $hich

    the constructor is declared.

    • f the class in $hich this method header appears is

    a!stract, then %e"$ord abstract ma" appear after

    the access modifier ( public or private. This isexplained in another section.

    • or a function or procedure, place

    %e"$ord static after the access modifier if the methoddoes not refer directl" to an instance varia!le or instance

    method of the class. Then, there $ill !e onl" one cop" of

    the method, and it $ill !e placed in the file-dra$er of the

    class.

    http://www.cs.cornell.edu/courses/cs1130/2011sp/module2/module2part1/methodHeaders.html#nameshttp://www.cs.cornell.edu/courses/cs1130/2011sp/module2/module2part1/methodHeaders.html#names

  • 8/9/2019 creating custom java functions

    15/16

    Method names

    A method name is often $ritten as a seuence of one or

    more $ords, li%e to0tring, setess. The first letter of each $ord, except thefirst , is capitalized.

    A procedure name is usuall" a command to do something,

    e.g. setess(int)

    n &ava, the methods in a class must have different

    signatures. This means, for example, that one cannot have

    !oth a procedure and a function $ith name is>ess and

    one int parameter. &ava constrains methods in thisfashion so that, for an" method call, there is no am!iguit"

    concerning $hich method is !eing called.

     

  • 8/9/2019 creating custom java functions

    16/16