archive-cr.com » CR » I » INFORMATECH.CR

Total: 292

Choose link from "Titles, links and description words view":

Or switch to "Titles and links view".
  • Informatech CR Blog | Geeks from paradise
    version 7 allows the use of underscores to help group individual digits or letters of literal values long baseDecimal 100 267 760 long octVal 04 13 long hexVal 0x10 BA 75 long binVal 0b1 0000 10 11 Underscores cannot be placed at the start or the end of a literal value cannot be placed right after prefixes for binary and hexadecimal values 0b 0B 0x and 0X but it can be placed right after the prefix for octal values 0 Underscores cannot be placed prior to a long suffix l or L finally they cannot be placed in positions where a string of digits is expected int i Integer parseInt 3 14 invalid use of underscore 2 1 2 2 Float and Double When expecting decimal numbers in Java float and double primitive data types can be used Float has smaller range than double and requires less space To initialize a decimal literal value as a float value the suffix F or f must be used because the default type of a decimal literal in java is double float average 17 925F After Java version 7 underscores can be used with floating point literal values following these rules You can t place an underscore prior to a D d F or f suffix these suffixes are used to mark a floating point literal as double or float You can t place an underscore adjacent to a decimal point 2 1 3 Character A char can store a single character from all the existing scripts and languages To assign a value to a char variable single quotes must be used instead of double quotes otherwise the code will fail to compile char v1 v Java stores char data as a positive integer therefore it is acceptable to assign an integer to a char char a1 97 a assigned to a1 2 1 3 1 Casting Casting is used to forcefully convert data to another data type and must be used between compatible data types when casting a bigger value to a smaller data type the compiler chops the extra bits that does not fit into the smaller variable Negative integer numbers can be casted into a char as follows char a2 char 97 successfully compiled 2 2 Identifiers Identifiers are names of packages classes interfaces methods and variables 2 2 1 Valid and Invalid Identifiers Rules to define valid and invalid identifiers 2 2 1 1 Java reserved words and keywords Words that cannot be used as an identifier name 2 3 Object Reference Variables An Object Reference is a memory address that points to a memory area where an object s data is located Class1 refVal new Class1 refVal is the name of the object reference variable In the previous line a reference variable refVal of type Class1 is created and an object is assigned to it The literal value of reference variables is null it can also be assigned explicitly Class1 refVal null 2 3 1 Object reference variables and primitive variables The main difference between these variables is that primitive variables store the values and reference variables store the memory address of the object they refer to 2 4 Operators Some of the most important Java operators 2 4 1 Assignment Operators The most frequently used operator is the and it is used to initialize variables with values and to reassign new values to them The and operators are short forms of addition subtraction multiplication and division with assignment and work as follows a b is equal to a a b a b is equal to a a b a b is equal to a a b a b is equal to a a b Multiple values can be assigned in the same line of code as follows int a 7 b 10 c 8 a b c here a 8 because the assignment starts from right to left 2 4 2 Arithmetic Operators Arithmetic operators in Java 2 4 2 1 And Unary increment and decrement operators Used to increment or decrement the value of a single variable by 1 Can be used in prefix or postfix notation int a 10 a a 11 int b 10 b b 11 When a unary operator is used in a expression its placement with respect to its operand decides whether its value will increment or decrement before the evaluation of the expression or after the evaluation of the expression int a 20 int b 10 int c a b System out println c c 9 System out println b b 11 int a 20 int b 10 int c a b System out println c c 10 System out println b b 11 int a 10 a a a a a a System out println a a 32 a 10 11 11 10 10 evaluates from left to right 2 4 3 Relational Operators Relational operators are used to check a condition The result of the relational operator is always a Boolean value Usually subdivided in two categories Comparing greater and lesser values Comparing values for equality and nonequality The operators and work with all types of numbers char and floating point variables that can be added and subtracted int a 10 int b 15 System out println a b prints false The operators and can be used to compare all types of primitives char byte short int long float double and boolean returns true if the values compared are not equal and false otherwise For the same set of values if returns true will return false These operators cannot be used to compare incomparable types for example comparing an int with a boolean will fail to compile 2 4 4 Logical Operators These Operators are used to evaluate one or more expressions and should return a boolean value And operator in Java returns true when both conditions are true Or operator in Java returns true when at least one condition is true Not operator reverses the outcome of a Boolean value int x 1 int y 5 System out println x y prints false System out println x y prints true boolean b1 false System out println b1 true prints false System out println b1 true prints true System out println b1 false prints true System out println b1 false prints false 2 4 5 Operator Precedence The next list illustrates the precedence of operators in Java the operators on top have the highest precedence and operators within the same group are evaluated from left to right This entry is the second part of of a series on Java Basics for further reading Java Basics I Java Basics III Share this Email Facebook Twitter Like this Like Loading June 9 2015 by ldac89 Categories Uncategorized 1 Comment Java Basics 1 1 The structure of a Java class and source code file 1 1 1 Structure of a Java class A class can define multiple components for example Package statement Import statement Comments Class declarations and definitions Variables Methods Constructors 1 1 1 1 Package Statement All Java classes are part of a package if a class is not defined in a named package it becomes part of a default package which doesn t have a name If a class includes a package statement it must be the first statement in the class definition it cannot appear within a class declaration or after the class declaration and if present it must appear exactly once in a class package certification should be the first statement in a class class Course 1 1 1 2 Import Statement Classes and interfaces from the same package can use each other without prefixing the package name But to use a class or interface from another package the import statement can be used package University import certification ExamQuestion import must be placed after the package class AnnualExam examQuestion eq The import statement follows the package but precedes the class declaration 1 1 1 3 Comments The comments in Java code can be placed at multiple places in a class To place multiline comments start with and end with End of line comments start with and are placed at the end of a line of code Comments can be placed before the package statement author JRamirez first name initial last name End of line within a multiline version 0 0 2 Class to store the details of a monument package uni package uni End of line comment class Monument int startYear 1 1 1 4 Class Declaration Components of a class declaration Access modifiers Nonaccess modifiers Class name Name of the base class if the class is extending another class All implemented interfaces if the class is implementing any interfaces Class body class fields methods constructors included within a pair of curly braces Example public final class Runner extends Person implements Athlete 1 1 1 5 Compulsory and optional elements of a class Compulsory Keyword class Name of the class Class body marked by the opening and closing curly braces Optional Keyword class Access modifier such as public Nonaccess modifier such as final Keyword extends together with the name of the base class Keyword implements together with the name of the interfaces being implemented 1 1 1 6 Class Definition The use of a class is to specify the behavior and properties of an object using methods and variables It is a design from which an object can be created 1 1 2 Structure and components of a Java source code file A Java source code file is used to define classes and interfaces All your Java code should be defined in Java source code files text files whose names end with java 1 1 2 1 Definition of interfaces in a Java source code file An interface is a grouping of related methods and constants but the methods in an interface cannot define any implementation interface Controls void changeChannel int channelNumber void increaseVolume void decreaseVolume 1 1 2 2 Definition of single and multiple classes in a single java source code file A single class or interface can be defined in a single Java source code or multiple classes and interfaces can be within the same source code The classes and interfaces can be defined in any order of occurrence in a Java source code file If a public class or interface is defined its name should match the name of the Java source code file 1 1 2 3 Application of package and import statements in Java source code files When an import or package statement is used within a java source code file it applies to all classes and interfaces defined in that code 1 2 Executable Java applications 1 2 1 Executable Java classes versus nonexecutable Java clases An executable Java class is a class which when handed over to the Java Virtual Machine starts its execution at a particular point in the class in the main method A nonexecutable class doesn t have it The programmer designates an executable class from all of the files of an application 1 2 2 Main method The first requirement in creating an executable Java application is to create a class with a method whose signature name and method arguments match the main method public class HelloExam public static void main String args System out println Hello exam This main method should comply with the following rules The method must be marked as a public method The method must be marked as a static method The name of the method must be main The return type of this method must be void The method must accept a method argument of a String array or a variable argument of type String The keywords public and static can be interchanged public static void main String args static public void main String args 1 3 Java Packages 1 3 1 The need for packages Packages are used to group classes and interfaces they also provide protection and namespace management Subpackages can also be created within the packages 1 3 2 Defining classes in a package using the package statement The first statement in a class or interface must be the package statement package certification class ExamQuestion code Rules about packages Per Java naming conventions package names should all be in lowercase The package and subpackage names are separated using a dot Package names follow the rules defined for valid identifiers in Java For packaged classes and interfaces the package statement is the first statement in a Java source file a java file The exception is that comments can appear before or after a package statement There can be a maximum of one package statement per Java source code file java file All the classes and interfaces defined in a Java source code file will be defined in the same package There is no way to package classes and interfaces defined within the same Java source code file in different packages 1 3 2 1 Directory Structure and Package Hierarchy The hierarchy of the packaged classes and interfaces should match the hierarchy of the directories in which those classes are defined 1 3 3 Using simple names with import statements For using classes and interfaces in other classes of your code there are two options using the fully qualified name or using the import statement with a simple name of the class or package package office class Cubicle home LivingRoom livingRoom package office import home LivingRoom class Cubicle LivingRoom livingRoom 1 3 4 Using packaged classes without using the import statement By using its fully qualified name a class or interface can be used without an import statement class AnnualExam certification ExamQuestion eq This is often used when there are multiple classes and interfaces with the same name because the import statement cannot be used in that case class AnnualExam java util Date date1 java sql Date date2 1 3 5 Importing a single or all members of a package By using an asterisk all the public classes members and interfaces of a package can be imported at once import certification class AnnualExam ExamQuestion eq MultipleChoice mc Importing a class in Java doesn t add to the size of the file 1 3 6 Importing Recursively By using an asterisk classes from a subpackage are not imported only classes from the main package 1 3 7 Default Package Import If no explicit package is defined for classes or interfaces they are imported in the default package automatically in all the classes and interfaces in the same directory class Person code class Office Person p A class from a default package can t be used in any named packaged class 1 3 8 Static Imports To import an individual static member of a class or all its static members the import static statement must be used package certification public class ExamQuestion static public int marks public static void print System out println 100 package university import static certification ExamQuestion marks class AnnualExam AnnualExam marks 20 Importing all of the static members package university import static certification ExamQuestion class AnnualExam AnnualExam marks 20 print 1 4 Java Access Modifiers 1 4 1 Access Modifiers Access modifiers control the accessibility of a class or interface and its members by other classes and interfaces They can be applied to classes interfaces and their members instance and class variables and methods Local variables and method parameters can t be defined using access modifiers Java defines four access modifiers public least restrictive protected default private most restrictive 1 4 3 Public Access Modifier Classes and interfaces defined using the public access modifier are accessible across all packages from derived to unrelated classes 1 4 4 Protected Access Modifier Classes and interfaces defined using the protected access modifier are accessible to classes and interfaces in the same package and all derived classes even in separate packages They cannot be accessed by unrelated classes in other packages 1 4 5 Default Access package access Classes and interfaces defined without any explicit access modifier are defined with package accessibility default accessibility They can only be accessed by classes and interfaces defined in the same package 1 4 6 Private Access Modifier The members of a class defined using the private access modifier are accessible only to themselves Private members are not accessible outside the class they are defined 1 5 Nonaccess Modifiers 1 5 1 Abstract Modifier When added to the definition of a class interface or method the abstract modifier changes its default behavior 1 5 1 1 Abstract Class When the abstract keyword is prefixed to the definition of a concrete class it changes it to an abstract class An abstract class can t be instantiated An abstract class can be defined without any abstract methods but a concrete class cannot define an abstract method 1 5 1 2 Abstract Interface An interface is an abstract entity by default The Java compiler automatically adds the keyword abstract to the definition of an interface 1 5 1 3 Abstract Method An abstract method doesn t have a body Usually an abstract method is implemented by a derived class 1 5 1 4 Abstract Variables No type of variable can be defined as abstract 1 5 2 Final Modifier The keyword final changes the default behavior of a class variable or method 1 5 2 1 Final Class A class defined final cannot be extended by other classes 1 5 2 2 Final Interface No interface can be marked as final 1 5 2 3 Final Variable A final variable can only be assigned a value once 1 5 2 4 Final Method A final method defined in a base class cannot be overridden in a derived class 1 5 3 Static Modifier Can be applied to the definitions of variables methods classes and interfaces 1 5 3 1 Static Variables They are common to all instances of a class and are not unique They are shared by all the objects of the class Static variables may be accessed even when no instances of a class have been created 1 5 3 2 Static Methods Static methods aren t associated with objects and can t use any of the instance variables of a class They can be used to use or manipulate static variables of a class Nonprivate static variables and methods can be inherited by derived classes and can be redefined within the derived class 1 5 3 3 What can a static method access Non static variables and methods can access static variables and methods Static methods and variables cannot access the instance methods of a class This entry is the first part of of a series on Java Basics for further reading Java Basics II Java Basics III Share this Email Facebook Twitter Like this Like Loading April 29 2015 by ldac89 Categories Java Programming Tags java Leave a comment Java 8 Streams and JPA Since the definition of the JPA Standard predates the release of Java 8 it is not surprising that the JPA API is only based on collections There is no way to obtain a Java 8 Stream out of a query object For those out there using Hibernate as their JPA provider there is an interesting way to create a stream for your JPQL queries Hibernate Scrollable Results Hibernate supports many more features than those offered by the JPA Standard only Hibernate s Query class allows us to obtain an iterator like object for a JQPL query This iterator like class is named ScrollableResults You can see a great example of this feature in this blog post about Reading Large Result Sets with Hibernate and MySQL I have taken the liberty of copying one of their examples Query query session createQuery query query setReadOnly true query setFetchSize 100 ScrollableResults results query scroll ScrollMode FORWARD ONLY while results next Object row results get process the entity here results close Creating an Iterator Wrapper around Scrollable Results Let s take this a bit further now by implementing a Java Iterator wrapper around the Hibernate s scrollable results object as shown below class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 Gaining Access to Hibernate Session through JPA Entity Manager As you can see the examples above use a Hibernate session object to obtain an instance of a Hibernate query object Supposing we are using JPA we typically have access to an EntityManager but not to any particular implementation objects of the underlaying provider To gain access to the Hibernate s Session object we can use a special method in the entity manger Session session entityManager unwrap Session class Be warned that at this point we are escaping from the safety of vendor agnostic code In other words if we ever wanted to use another provider like OpenJPA or EclipseLink we would be forced to find a different alternative to implement our code here since those other providers won t offer anything like Hibernate s Session and ScrollableResults From Iterators to Spliterators to Streams Our next step consists in obtaining a Java 8 stream out of this iterator Lukas Eder recently wrote an interesting article about the difficulties to obtain a stream out of an iterable object which will be pretty handy here To achieve our goal we now need to use two utility classes in Java 8 named StreamSupport and Spliterators For instance we could take an iterator like the one we defined above and transform it into a Spliterator by doing private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE This Splititerator is an intermediate product that we can now use to create a Java 8 stream out of it StreamSupport stream spliterator false At this point we have built enough to create our first stream out of a JPQL query We can do it as follows public Stream T getResultStream String sql Integer fetchSize Map String Object parameters Query query session createQuery sql if fetchSize null query setFetchSize fetchSize for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue query setReadOnly true ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close A JPA Stream API We can do a little bit better by defining the basics of the type of query object we are currently missing in JPA Standard API public interface StreamQuery T Stream T getResultStream StreamQuery T setParameter String name Object value StreamQuery T setFetchSize int fetchSize And putting together all we have learned so far we could create this implementation of our new StreamQuery interface public class HibernateQueryStream T implements StreamQuery T private final Session session private final String sql private final Class T type private final Map String Object parameters new HashMap private Integer fetchSize public HibernateQueryStream EntityManager entityManager String sql Class T type this session entityManager unwrap Session class this sql sql this type type Override public StreamQuery T setParameter String name Object value parameters put name value return this Override public StreamQuery T setFetchSize int fetchSize this fetchSize fetchSize return this Override public Stream T getResultStream Query query session createQuery sql if fetchSize null query setFetchSize fetchSize query setReadOnly true for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE private static class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 The Repository Layer On top of this component we can now build our repository layer Repository public class StreamRepository PersistenceContext unitName demo private EntityManager entityManager public Stream Order getOrderHistory String email String jpql SELECT o FROM Order o WHERE o customer email email StreamQuery Order query new HibernateQueryStream entityManager jpql Order class return query getResultStream And from here the rest is a piece of cake orderRepository findOrderHistory email filter order order total 100 map Order getOrderLines flatMap List stream map OrderLine getTotal reduce 0 x y x y It is important to highlight that the Hibernate session must be alive by the time we actually consume the stream because it is at that point that the entities will be mapped So make sure that wherever you consume the stream the Hibernate session or you entity manager context is still alive Further Reading Java Stream API JPA Specification Reading Large Result Sets with Hibernate and MySQL Really Too Bad that Java 8 Doesn t Have Iterable stream Share this Email Facebook Twitter Like this Like Loading December 17 2014 by Edwin Dalorzo Categories Java Tags java JPA Standard 2 Comments Functional Programming with Java 8 Functions I have finally had the opportunity to work in a couple of projects being entirely developed with Java 8 and during the past months I ve experienced first hand many of the new functional programming features in the language So I decided to write a series of articles about some of these things I ve being learning and how some of the well known functional programming constructs can be translated into Java 8 Preliminaries Ok let s start with something simple The following is a lambda expression i e an anonymous function that takes an argument x and increments it by one In other words a function that receives apparently an integer and returns a new incremented integer x x 1 And what is the type of this function in Java Well the answer is that it depends In Java the same lambda expression could be bound to variables of different types For instance the following two are valid declarations in Java Function Integer Integer add1 x x 1 Function String String concat1 x x 1 The first one increments an integer x by one whereas the second one concatenates the integer 1 to any string x And how can we invoke these functions Well now that they are bound to a reference we can treat them pretty much like we treat any object Integer two add1 apply 1 yields 2 String answer concat1 apply 0 1 yields 0 1 1 So as you can see every function has a method apply that we use to invoke it and pass it an argument And what if I already have a method that does that can I use it as a function Yes since an alternative way to create functions is by using methods we had already defined and that are compatible with our function definition Suppose that we have the following class definition with methods as defined below public class Utils public static Integer add1 Integer x return x 1 public static String concat1 String x return x 1 As you can see the methods in this class are compatible with our original function definitions so we could use them as method references to create the same functions we did before with lambda expressions Function Integer Integer add1 Utils add1 Function String String concat1 Utils concat1 These two are just the same thing as the ones we did before High Order Programming The cool thing about functions is that they encapsulate behavior and now we can take a piece of code put it into a function and pass it around to other functions or methods for them to use it This type of functions that operate on or produce new functions are typically called high order functions and the programming style based on exploiting this powerful feature is called unsurprisingly high order programming About Functions that Create Functions Let s see a couple of examples of how we can do this using function objects Let s consider the following example Function Integer Function Integer Integer makeAdder x y x y Above we have a function called makeAdder that takes an integer x and creates a new function that takes an integer y and when invoked adds x to y We can tell this is a high order function because it produces a new function Now we use this to create our original add1 function Function Integer Integer add1 makeAdder apply 1 Function Integer Integer add2 makeAdder apply 2 Function Integer Integer add3 makeAdder apply 3 With our new high order function however we could also create add2 add3 addn right Can t we define this in a simpler way as we did before with the Utils class methods Yes we can Consider the following addition to the Utils class public class Utils public static Function Intger Integer adder Integer x return y x y This signature is a bit simpler to read than that in our lambda expression but as you can see it is pretty much the same thing The function continues to receive the same number and type of arguments and continues to return the same type of result We can now use this simpler function factory to create our makeAdder and add1 functions again Function Integer Function Integer Integer makeAdder Utils adder Function Integer Integer add1 makeAdder apply 1 And there you have it this is exactly the same thing as before About Functions that Receive Functions as Arguments Let s suppose we had the following two functions defined Function Integer Integer add1 x x 1 Function Integer Integer mul3 x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply 10 Partial Function Application or Currying In most functional programming languages it is possible to create partially applied functions That is if a function is receiving multiple arguments we can partially invoke the function providing just a few arguments and receive a partially applied function out of it This is typically called currying Although you have not noticed it we have already covered that in this article but now we are going to make it much more evident So consider the following pseudo code sum x y x y Then we say that sum is a function that accepts one parameter x and fabricates another anonymous function that in turn accepts one parameter y that when invoked sums x and y In many functional programming languages a construct like this can be invoked as if this was just one simple function by doing sum 10 5 yields 15 But the truth is that this is just syntactic sugar to do sum 10 5 yields 15 Since sum is a function that returns a function The beauty of this idiom is that now we could partially apply sum plus10 sum 10 And now plus10 is a partially applied function of sum Can you see now where we had already talked about this plus10 5 yields 15 Can we do this with Java The truth is that we have already done it above we just probably did not notice Unfortunately in Java we do not have the syntactic sugar that some other language have and therefore this is a bit more verbose Function Integer Function Integer Integer sum x y x y Well you can see sum is declared in a currified way And now we can partially apply it Function Integer Integer plus10 sum apply 10 Integer res plus10 apply 5 yields 15 Unary Binary Ternary and n ary Functions So as mentioned above Java uses different functional interfaces for different function arities And so Function T R is a functional interface for any unary function where the domain and the codomain of the function may be of different types For instance we could define a function that receives a string value and parses it as an integer Function String Integer atoi s Integer valueOf s But most of our examples above are for integer functions whose argument and return value are of this same type For those cases we could alternatively use the UnaryOperator T instead This is just a Function T T Thus some our declarations above could be slightly simplified with this functional interface UnaryOperator Integer add1 n n 1 UnaryOperator String concat1 s s 1 Function Integer UnaryOperator Integer sum x y x y UnaryOperator Integer sum10 sum apply 10 I have already written another article that explains Why Java 8 has Interface Pollution like this in case you are interested in an explanation Value Types and Primitive Type Functions Evidently using a type like Integer incurs into the costs of boxing and unboxing when our functions have to deal with a primitive type like int As you know Java does not support value types as type arguments in generic declarations so to deal with this problem we can use alternative functional interfaces like ToIntFunction IntFunction or IntUnaryOperator Or we can define our own primitive function interface IntFx public int apply int value Then we can do IntFx add1 n n 1 IntFunction IntFx sum x

    Original URL path: http://blog.informatech.cr/ (2015-08-19)
    Open archived version from archive

  • Collaboration | Informatech CR Blog
    Categories Collaboration Leave a comment Communication Etiquette 101 How are you today Philip silence Philip did you hear me I said how are you today silence I doubt any of us would ever blatantly ignore someone that walked up to you and said hello It s just rude However it happens all the time with email chat voice messaging and texts Why Do people actually think they are invisible behind a keyboard Of course we cannot control how others deal with communication etiquette It s up to them We can control how we treat our electronic communications with our clients our co workers and our suppliers One simple principal should remembered Treat others the same way you would like to be treated For Informatech employees that should mean that timely response is the norm What if you don t know the answer to the question being posed Well how would you respond if it were face to face You would say I m not sure how to answer you right now Let me get back to you tomorrow or the end of the week or by a specific date Never is ignoring the request acceptable There I got that off my chest Oh in case you can t get hold of me here s my contact info Phil Palmer Phone 801 386 0683 email phil palmer informatech cr skype phil palmer twitter pjpalm801 Share this Email Facebook Twitter Like this Like Loading December 6 2010 by pjpalm801 Categories Collaboration 1 Comment Anthropological meaning of work I ve been wondering myself with this concept for a while so I decided to write a little something about it especially now that I think I work in a place where the mere experience of being here justifies my words Let me start with a tricky question to get the ball rolling What are you able to do with money What is it that drive us so hard to get more and more of it at some point in our lives Is it a cultural thing something that you learn to do or something that is innate to our nature By starting with this simple question I asked myself many years ago I discovered that well I needed to ask even more profound questions to even start to figure out the overall idea And I m not talking about existential or metaphysical questions Just common sense which most of the times is the least common of senses So I ask myself why do I need to work in the first place Why do you Is it a survival thing and if such does that make us mere survival beings trying to earn our day to day right to be here Too many questions I know Pardon me I guess what I really want to say or better yet to share is that over my almost 40 years of life I think I ve learned that it is not what you do what defines you

    Original URL path: http://blog.informatech.cr/category/collaboration/ (2015-08-19)
    Open archived version from archive

  • Costa Rica | Informatech CR Blog
    a company wants to try offshore services sometimes is hard to get talented or specialized people where the company has its office sometimes having resources in a different time zone will benefit for example if a 24 7 tech support schema is required Finally having resources overseas could help companies to reduce costs India is still country 1 in the top of offshore service providers around world However in the recent years some other countries have started to grow and follow it very close like China Philippines Ireland India bests Costa Rica in most of the decision criteria according to Gartner studios but I would say it is because of the proportion of people for example if 20 of Indian citizens speak English it represent more than 200 million people So they have more English speaking people However Costa Rican accent is more familiar for the US people India graduates about 300 000 software developers every year while Costa Rican public universities receive every year only about 400 people So their employment pool is definitively wider than Costa Rican However some companies that have experience with both India and Costa Rica say ticos are more proactive I think it is hard to compare it because of the huge proportional differences between the two countries We found cases of US companies that went to India failed and then came to Costa Rica and succeed We also found cases of companies that currently have services offshore in both countries with success they decide countries according to each specific need Costa Rica has experienced a great increment as an offshore provider in the recent years and today is part of the 7 Latin America countries that are part of the top 30 world countries to contract offshore services according to Gartner As an advantage Costa Rica is located in a geographical strategic location pretty close to time zone of most of North America and easy and cheap to travel Also Costa Rican pronunciation is very friendly for US people professionals here are proactive dedicated have willing to learn to improve and to grow those are qualities that US companies value So Costa Rica is very attractive and especially for US companies There is a challenge for the government here to go forward in making Costa Rica a more attractive place for business But this is not only an effort of the government The challenge for us IT people that work for offshore companies is to keep the good work and delivering results to our customer so Costa Rica can continue incrementing its rating between the best places to do offshore Ricardo Sánchez Share this Email Facebook Twitter Like this Like Loading October 29 2010 by ricardosar Categories Costa Rica Informatech Tags outsourcing 1 Comment Poll Favorite Vacation Spot in Costa Rica Take Our Poll 9 933333 84 083333 Share this Email Facebook Twitter Like this Like Loading October 28 2010 by pjpalm801 Categories Costa Rica 3 Comments A New Week A New Blog

    Original URL path: http://blog.informatech.cr/category/costa-rica/ (2015-08-19)
    Open archived version from archive

  • Informatech | Informatech CR Blog
    the Family Informatech Costa Rica is happy to announce the addition of three new employees Krissia Infante Administrative Assistant Jose Andres Java Developer and Andre Curione Java Developer Jose and Andre will be working with our new client Chesapeake System Solutions Inc headquartered in Owings Mills Maryland Kris is responsible for keeping our office running smoothly and after a week has already turned into a pro Welcome to all Phil Share this Email Facebook Twitter Like this Like Loading March 4 2011 by pjpalm801 Categories Informatech Leave a comment HOW TO Win the War for the Most Talented Employees Hi Everyone To start this new year I would like to share an article I recently read and enjoyed on HR management and recruitment and some best practices and recommendations on hiring and retaining great talent http mashable com 2011 01 03 find talented employees It s very nice to know that we are on the right track here Informatech CR Have a good one Cheers from Costa Rica Share this Email Facebook Twitter Like this Like Loading January 4 2011 by arielargo Categories Collaboration Costa Rica Informatech Tags best practices employees hiring Human Resouce informatech market outsourcing recruitment Talent welcome Leave a comment 2010 in review The stats helper monkeys at WordPress com mulled over how this blog did in 2010 and here s a high level summary of its overall blog health The Blog Health o Meter reads Fresher than ever Crunchy numbers The Leaning Tower of Pisa has 296 steps to reach the top This blog was viewed about 1 100 times in 2010 If those were steps it would have climbed the Leaning Tower of Pisa 4 times In 2010 there were 17 new posts not bad for the first year There were 11 pictures uploaded taking up a total of 737kb That s about a picture per month The busiest day of the year was November 15th with 178 views The most popular post that day was Win a brand spanking new iPod Nano for you and one of your friends Where did they come from The top referring sites in 2010 were facebook com informatech cr linkedin com twitter com and WordPress Dashboard Some visitors came searching mostly for informatech costa rica informatech linux on palm tx microsoft in costa rica and canopy Attractions in 2010 These are the posts and pages that got the most views in 2010 1 Win a brand spanking new iPod Nano for you and one of your friends November 2010 1 comment 2 Outsourcing offshore Costa Rica where are we October 2010 3 The Web is Dead October 2010 1 comment 4 Celebrating Thanksgiving in Costa Rica November 2010 5 Hello world October 2010 3 comments 9 933333 84 083333 Share this Email Facebook Twitter Like this Like Loading January 3 2011 by pjpalm801 Categories Informatech Tags 2010 blog Leave a comment Celebrating Thanksgiving in Costa Rica Thanksgiving is a tradition in the United States of America It s

    Original URL path: http://blog.informatech.cr/category/informatech/ (2015-08-19)
    Open archived version from archive

  • News | Informatech CR Blog
    so I can attend the match in April Of course I will be in Salt Lake for Game 1 on March 15th cheering RSL on Sorry Saprissa fans And I will be wearing my 15 jersey Saborio Anyone that wishes to join me at the stadium April 5th is welcome but just know that I will be the one guy in the stands cheering for the guys in Red Blue See you all very soon Phil Share this Email Facebook Twitter Like this Like Loading March 4 2011 by pjpalm801 Categories Costa Rica Informatech News Leave a comment 2010 The year the Future arrived Yep we re in 2011 now but I want you to remember 2010 as the year when we arrived at the Future That s right Future with a capital F the milestome that place that s been theorized and promised since the Space Age arrived Why Consider these two events that occured last year A computer virus Stuxnet was able to penetrate and deal as much damage to Iran s nuclear facilities as a full blown military strike Consider this not a life was lost not a bullet fired yet because of a piece of software that had to propagate through USB thumbdrives an entire country has been delayed years in a national endeavour Don t believe it Read Wikileaks I think that s all that needs to be said but more specifically how the entire diplomacy of the world s last superpower came to standstill because someone downloaded and posted it all online This is it this is the Future No longer are the virtual and real world separate they ve been meshing together and now finally the computer Internet revolutions changed all aspects of society world wide The challenges now are that as the

    Original URL path: http://blog.informatech.cr/category/news/ (2015-08-19)
    Open archived version from archive

  • Programming | Informatech CR Blog
    from another package the import statement can be used package University import certification ExamQuestion import must be placed after the package class AnnualExam examQuestion eq The import statement follows the package but precedes the class declaration 1 1 1 3 Comments The comments in Java code can be placed at multiple places in a class To place multiline comments start with and end with End of line comments start with and are placed at the end of a line of code Comments can be placed before the package statement author JRamirez first name initial last name End of line within a multiline version 0 0 2 Class to store the details of a monument package uni package uni End of line comment class Monument int startYear 1 1 1 4 Class Declaration Components of a class declaration Access modifiers Nonaccess modifiers Class name Name of the base class if the class is extending another class All implemented interfaces if the class is implementing any interfaces Class body class fields methods constructors included within a pair of curly braces Example public final class Runner extends Person implements Athlete 1 1 1 5 Compulsory and optional elements of a class Compulsory Keyword class Name of the class Class body marked by the opening and closing curly braces Optional Keyword class Access modifier such as public Nonaccess modifier such as final Keyword extends together with the name of the base class Keyword implements together with the name of the interfaces being implemented 1 1 1 6 Class Definition The use of a class is to specify the behavior and properties of an object using methods and variables It is a design from which an object can be created 1 1 2 Structure and components of a Java source code file A Java source code file is used to define classes and interfaces All your Java code should be defined in Java source code files text files whose names end with java 1 1 2 1 Definition of interfaces in a Java source code file An interface is a grouping of related methods and constants but the methods in an interface cannot define any implementation interface Controls void changeChannel int channelNumber void increaseVolume void decreaseVolume 1 1 2 2 Definition of single and multiple classes in a single java source code file A single class or interface can be defined in a single Java source code or multiple classes and interfaces can be within the same source code The classes and interfaces can be defined in any order of occurrence in a Java source code file If a public class or interface is defined its name should match the name of the Java source code file 1 1 2 3 Application of package and import statements in Java source code files When an import or package statement is used within a java source code file it applies to all classes and interfaces defined in that code 1 2 Executable Java applications 1 2 1 Executable Java classes versus nonexecutable Java clases An executable Java class is a class which when handed over to the Java Virtual Machine starts its execution at a particular point in the class in the main method A nonexecutable class doesn t have it The programmer designates an executable class from all of the files of an application 1 2 2 Main method The first requirement in creating an executable Java application is to create a class with a method whose signature name and method arguments match the main method public class HelloExam public static void main String args System out println Hello exam This main method should comply with the following rules The method must be marked as a public method The method must be marked as a static method The name of the method must be main The return type of this method must be void The method must accept a method argument of a String array or a variable argument of type String The keywords public and static can be interchanged public static void main String args static public void main String args 1 3 Java Packages 1 3 1 The need for packages Packages are used to group classes and interfaces they also provide protection and namespace management Subpackages can also be created within the packages 1 3 2 Defining classes in a package using the package statement The first statement in a class or interface must be the package statement package certification class ExamQuestion code Rules about packages Per Java naming conventions package names should all be in lowercase The package and subpackage names are separated using a dot Package names follow the rules defined for valid identifiers in Java For packaged classes and interfaces the package statement is the first statement in a Java source file a java file The exception is that comments can appear before or after a package statement There can be a maximum of one package statement per Java source code file java file All the classes and interfaces defined in a Java source code file will be defined in the same package There is no way to package classes and interfaces defined within the same Java source code file in different packages 1 3 2 1 Directory Structure and Package Hierarchy The hierarchy of the packaged classes and interfaces should match the hierarchy of the directories in which those classes are defined 1 3 3 Using simple names with import statements For using classes and interfaces in other classes of your code there are two options using the fully qualified name or using the import statement with a simple name of the class or package package office class Cubicle home LivingRoom livingRoom package office import home LivingRoom class Cubicle LivingRoom livingRoom 1 3 4 Using packaged classes without using the import statement By using its fully qualified name a class or interface can be used without an import statement class AnnualExam certification ExamQuestion eq This is often used when there are multiple classes and interfaces with the same name because the import statement cannot be used in that case class AnnualExam java util Date date1 java sql Date date2 1 3 5 Importing a single or all members of a package By using an asterisk all the public classes members and interfaces of a package can be imported at once import certification class AnnualExam ExamQuestion eq MultipleChoice mc Importing a class in Java doesn t add to the size of the file 1 3 6 Importing Recursively By using an asterisk classes from a subpackage are not imported only classes from the main package 1 3 7 Default Package Import If no explicit package is defined for classes or interfaces they are imported in the default package automatically in all the classes and interfaces in the same directory class Person code class Office Person p A class from a default package can t be used in any named packaged class 1 3 8 Static Imports To import an individual static member of a class or all its static members the import static statement must be used package certification public class ExamQuestion static public int marks public static void print System out println 100 package university import static certification ExamQuestion marks class AnnualExam AnnualExam marks 20 Importing all of the static members package university import static certification ExamQuestion class AnnualExam AnnualExam marks 20 print 1 4 Java Access Modifiers 1 4 1 Access Modifiers Access modifiers control the accessibility of a class or interface and its members by other classes and interfaces They can be applied to classes interfaces and their members instance and class variables and methods Local variables and method parameters can t be defined using access modifiers Java defines four access modifiers public least restrictive protected default private most restrictive 1 4 3 Public Access Modifier Classes and interfaces defined using the public access modifier are accessible across all packages from derived to unrelated classes 1 4 4 Protected Access Modifier Classes and interfaces defined using the protected access modifier are accessible to classes and interfaces in the same package and all derived classes even in separate packages They cannot be accessed by unrelated classes in other packages 1 4 5 Default Access package access Classes and interfaces defined without any explicit access modifier are defined with package accessibility default accessibility They can only be accessed by classes and interfaces defined in the same package 1 4 6 Private Access Modifier The members of a class defined using the private access modifier are accessible only to themselves Private members are not accessible outside the class they are defined 1 5 Nonaccess Modifiers 1 5 1 Abstract Modifier When added to the definition of a class interface or method the abstract modifier changes its default behavior 1 5 1 1 Abstract Class When the abstract keyword is prefixed to the definition of a concrete class it changes it to an abstract class An abstract class can t be instantiated An abstract class can be defined without any abstract methods but a concrete class cannot define an abstract method 1 5 1 2 Abstract Interface An interface is an abstract entity by default The Java compiler automatically adds the keyword abstract to the definition of an interface 1 5 1 3 Abstract Method An abstract method doesn t have a body Usually an abstract method is implemented by a derived class 1 5 1 4 Abstract Variables No type of variable can be defined as abstract 1 5 2 Final Modifier The keyword final changes the default behavior of a class variable or method 1 5 2 1 Final Class A class defined final cannot be extended by other classes 1 5 2 2 Final Interface No interface can be marked as final 1 5 2 3 Final Variable A final variable can only be assigned a value once 1 5 2 4 Final Method A final method defined in a base class cannot be overridden in a derived class 1 5 3 Static Modifier Can be applied to the definitions of variables methods classes and interfaces 1 5 3 1 Static Variables They are common to all instances of a class and are not unique They are shared by all the objects of the class Static variables may be accessed even when no instances of a class have been created 1 5 3 2 Static Methods Static methods aren t associated with objects and can t use any of the instance variables of a class They can be used to use or manipulate static variables of a class Nonprivate static variables and methods can be inherited by derived classes and can be redefined within the derived class 1 5 3 3 What can a static method access Non static variables and methods can access static variables and methods Static methods and variables cannot access the instance methods of a class This entry is the first part of of a series on Java Basics for further reading Java Basics II Java Basics III Share this Email Facebook Twitter Like this Like Loading April 29 2015 by ldac89 Categories Java Programming Tags java Leave a comment Java 8 Streams and JPA Since the definition of the JPA Standard predates the release of Java 8 it is not surprising that the JPA API is only based on collections There is no way to obtain a Java 8 Stream out of a query object For those out there using Hibernate as their JPA provider there is an interesting way to create a stream for your JPQL queries Hibernate Scrollable Results Hibernate supports many more features than those offered by the JPA Standard only Hibernate s Query class allows us to obtain an iterator like object for a JQPL query This iterator like class is named ScrollableResults You can see a great example of this feature in this blog post about Reading Large Result Sets with Hibernate and MySQL I have taken the liberty of copying one of their examples Query query session createQuery query query setReadOnly true query setFetchSize 100 ScrollableResults results query scroll ScrollMode FORWARD ONLY while results next Object row results get process the entity here results close Creating an Iterator Wrapper around Scrollable Results Let s take this a bit further now by implementing a Java Iterator wrapper around the Hibernate s scrollable results object as shown below class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 Gaining Access to Hibernate Session through JPA Entity Manager As you can see the examples above use a Hibernate session object to obtain an instance of a Hibernate query object Supposing we are using JPA we typically have access to an EntityManager but not to any particular implementation objects of the underlaying provider To gain access to the Hibernate s Session object we can use a special method in the entity manger Session session entityManager unwrap Session class Be warned that at this point we are escaping from the safety of vendor agnostic code In other words if we ever wanted to use another provider like OpenJPA or EclipseLink we would be forced to find a different alternative to implement our code here since those other providers won t offer anything like Hibernate s Session and ScrollableResults From Iterators to Spliterators to Streams Our next step consists in obtaining a Java 8 stream out of this iterator Lukas Eder recently wrote an interesting article about the difficulties to obtain a stream out of an iterable object which will be pretty handy here To achieve our goal we now need to use two utility classes in Java 8 named StreamSupport and Spliterators For instance we could take an iterator like the one we defined above and transform it into a Spliterator by doing private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE This Splititerator is an intermediate product that we can now use to create a Java 8 stream out of it StreamSupport stream spliterator false At this point we have built enough to create our first stream out of a JPQL query We can do it as follows public Stream T getResultStream String sql Integer fetchSize Map String Object parameters Query query session createQuery sql if fetchSize null query setFetchSize fetchSize for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue query setReadOnly true ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close A JPA Stream API We can do a little bit better by defining the basics of the type of query object we are currently missing in JPA Standard API public interface StreamQuery T Stream T getResultStream StreamQuery T setParameter String name Object value StreamQuery T setFetchSize int fetchSize And putting together all we have learned so far we could create this implementation of our new StreamQuery interface public class HibernateQueryStream T implements StreamQuery T private final Session session private final String sql private final Class T type private final Map String Object parameters new HashMap private Integer fetchSize public HibernateQueryStream EntityManager entityManager String sql Class T type this session entityManager unwrap Session class this sql sql this type type Override public StreamQuery T setParameter String name Object value parameters put name value return this Override public StreamQuery T setFetchSize int fetchSize this fetchSize fetchSize return this Override public Stream T getResultStream Query query session createQuery sql if fetchSize null query setFetchSize fetchSize query setReadOnly true for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE private static class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 The Repository Layer On top of this component we can now build our repository layer Repository public class StreamRepository PersistenceContext unitName demo private EntityManager entityManager public Stream Order getOrderHistory String email String jpql SELECT o FROM Order o WHERE o customer email email StreamQuery Order query new HibernateQueryStream entityManager jpql Order class return query getResultStream And from here the rest is a piece of cake orderRepository findOrderHistory email filter order order total 100 map Order getOrderLines flatMap List stream map OrderLine getTotal reduce 0 x y x y It is important to highlight that the Hibernate session must be alive by the time we actually consume the stream because it is at that point that the entities will be mapped So make sure that wherever you consume the stream the Hibernate session or you entity manager context is still alive Further Reading Java Stream API JPA Specification Reading Large Result Sets with Hibernate and MySQL Really Too Bad that Java 8 Doesn t Have Iterable stream Share this Email Facebook Twitter Like this Like Loading December 17 2014 by Edwin Dalorzo Categories Java Tags java JPA Standard 2 Comments Functional Programming with Java 8 Functions I have finally had the opportunity to work in a couple of projects being entirely developed with Java 8 and during the past months I ve experienced first hand many of the new functional programming features in the language So I decided to write a series of articles about some of these things I ve being learning and how some of the well known functional programming constructs can be translated into Java 8 Preliminaries Ok let s start with something simple The following is a lambda expression i e an anonymous function that takes an argument x and increments it by one In other words a function that receives apparently an integer and returns a new incremented integer x x 1 And what is the type of this function in Java Well the answer is that it depends In Java the same lambda expression could be bound to variables of different types For instance the following two are valid declarations in Java Function Integer Integer add1 x x 1 Function String String concat1 x x 1 The first one increments an integer x by one whereas the second one concatenates the integer 1 to any string x And how can we invoke these functions Well now that they are bound to a reference we can treat them pretty much like we treat any object Integer two add1 apply 1 yields 2 String answer concat1 apply 0 1 yields 0 1 1 So as you can see every function has a method apply that we use to invoke it and pass it an argument And what if I already have a method that does that can I use it as a function Yes since an alternative way to create functions is by using methods we had already defined and that are compatible with our function definition Suppose that we have the following class definition with methods as defined below public class Utils public static Integer add1 Integer x return x 1 public static String concat1 String x return x 1 As you can see the methods in this class are compatible with our original function definitions so we could use them as method references to create the same functions we did before with lambda expressions Function Integer Integer add1 Utils add1 Function String String concat1 Utils concat1 These two are just the same thing as the ones we did before High Order Programming The cool thing about functions is that they encapsulate behavior and now we can take a piece of code put it into a function and pass it around to other functions or methods for them to use it This type of functions that operate on or produce new functions are typically called high order functions and the programming style based on exploiting this powerful feature is called unsurprisingly high order programming About Functions that Create Functions Let s see a couple of examples of how we can do this using function objects Let s consider the following example Function Integer Function Integer Integer makeAdder x y x y Above we have a function called makeAdder that takes an integer x and creates a new function that takes an integer y and when invoked adds x to y We can tell this is a high order function because it produces a new function Now we use this to create our original add1 function Function Integer Integer add1 makeAdder apply 1 Function Integer Integer add2 makeAdder apply 2 Function Integer Integer add3 makeAdder apply 3 With our new high order function however we could also create add2 add3 addn right Can t we define this in a simpler way as we did before with the Utils class methods Yes we can Consider the following addition to the Utils class public class Utils public static Function Intger Integer adder Integer x return y x y This signature is a bit simpler to read than that in our lambda expression but as you can see it is pretty much the same thing The function continues to receive the same number and type of arguments and continues to return the same type of result We can now use this simpler function factory to create our makeAdder and add1 functions again Function Integer Function Integer Integer makeAdder Utils adder Function Integer Integer add1 makeAdder apply 1 And there you have it this is exactly the same thing as before About Functions that Receive Functions as Arguments Let s suppose we had the following two functions defined Function Integer Integer add1 x x 1 Function Integer Integer mul3 x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply 10 Partial Function Application or Currying In most functional programming languages it is possible to create partially applied functions That is if a function is receiving multiple arguments we can partially invoke the function providing just a few arguments and receive a partially applied function out of it This is typically called currying Although you have not noticed it we have already covered that in this article but now we are going to make it much more evident So consider the following pseudo code sum x y x y Then we say that sum is a function that accepts one parameter x and fabricates another anonymous function that in turn accepts one parameter y that when invoked sums x and y In many functional programming languages a construct like this can be invoked as if this was just one simple function by doing sum 10 5 yields 15 But the truth is that this is just syntactic sugar to do sum 10 5 yields 15 Since sum is a function that returns a function The beauty of this idiom is that now we could partially apply sum plus10 sum 10 And now plus10 is a partially applied function of sum Can you see now where we had already talked about this plus10 5 yields 15 Can we do this with Java The truth is that we have already done it above we just probably did not notice Unfortunately in Java we do not have the syntactic sugar that some other language have and therefore this is a bit more verbose Function Integer Function Integer Integer sum x y x y Well you can see sum is declared in a currified way And now we can partially apply it Function Integer Integer plus10 sum apply 10 Integer res plus10 apply 5 yields 15 Unary Binary Ternary and n ary Functions So as mentioned above Java uses different functional interfaces for different function arities And so Function T R is a functional interface for any unary function where the domain and the codomain of the function may be of different types For instance we could define a function that receives a string value and parses it as an integer Function String Integer atoi s Integer valueOf s But most of our examples above are for integer functions whose argument and return value are of this same type For those cases we could alternatively use the UnaryOperator T instead This is just a Function T T Thus some our declarations above could be slightly simplified with this functional interface UnaryOperator Integer add1 n n 1 UnaryOperator String concat1 s s 1 Function Integer UnaryOperator Integer sum x y x y UnaryOperator Integer sum10 sum apply 10 I have already written another article that explains Why Java 8 has Interface Pollution like this in case you are interested in an explanation Value Types and Primitive Type Functions Evidently using a type like Integer incurs into the costs of boxing and unboxing when our functions have to deal with a primitive type like int As you know Java does not support value types as type arguments in generic declarations so to deal with this problem we can use alternative functional interfaces like ToIntFunction IntFunction or IntUnaryOperator Or we can define our own primitive function interface IntFx public int apply int value Then we can do IntFx add1 n n 1 IntFunction IntFx sum x y x y IntFx sum10 sum apply 10 sum10 apply 4 yields 14 Similar functional interfaces can be found in the Java API for types double and long as well This topic is also covered in the alternative article mentioned above about interface pollution And that s it for the time being I hope that in a future article I can take this a bit further and show some practical applications derived from my experience in actual projects Further Reading High Order Programming High Order Functions Function Composition Currying Why Java 8 has Interface Pollution Share this Email Facebook Twitter Like this Like Loading October 19 2014 by Edwin Dalorzo Categories Java Programming Tags function composition functional programming high java java8 Leave a comment JSApps 101 AngularJS In A Nutshell Introduction Moving on with the topic in the previous part of this series we discussed about that interesting new tendency to let the browser do all the user interface heavy lifting on the client side since it is such a good guy Of course this involves a LOT of JavaScript going on since it is the only language the browser understands besides HTML We all know how complex and crazy things can get when you involve JavaScript in the picture The language is usually seen as over complicated it used to be hard to debug learning curve is steep as hell and it can get confusing quickly also there used to be a lack of tools and IDEs with strong support for its development just sums up for bad reputation However fear not After this article you will have a solid base on how you can turn the fiendish JavaScript you have known for years from a simple DOM traversal helper to a whole reliable application development framework with the aid of AngularJS man now THAT S a catchy name What In The World Is AngularJS AngularJS is a JavaScript library that allows you to implement the Model view controller pattern in some sort of way at a client side level dude the browser Why is this Because you have two options in life Option A You implement a 1000 lines JavaScript source file with a bunch of code that not only is in charge of handling manipulation of the HTML structure and creation of UI components but also handles all of the data validation and display logic of it all of this while your fellow teammates start hating the guts out of you Option B You be a good developer who cares about separation of concerns and split all those tasks in several components where each is in charge of a single thing those written in separate files for your code maintainability s sake while making a lot of friends in the process In the good old days option A was kind of affordable heavy quotations since JavaScript was used for simple things like adding and removing elements from the HTML structure changing colors and such But when we talk about implementing a client application only using JavaScript option A starts struggling Mainly because we are not only moving HTML elements around animating stuff and other user interface tasks but also performing data validation error handling and server communications in the client side Of course option B is the way to go Since there is a ton of things going on in the browser we need a way to create components that handle each task separately This is known as the Separation of Concerns principle or SOC which states that your code has to be split in several parts handling a single task each orchestrated in order to achieve a common good And this is where AngularJS shines It allows you to Organize your client side code in a Model view controller fashion so you have separate components where each handles a different task in the logic stack from user input to server data posting Don t worry we ll get on this later on Live template processing and data binding more specifically munch a template bind it to specific data coming from the server or anywhere else and then produce a valid HTML piece that can be displayed in the browser Creation of re usable user interface components Implementation of advanced patterns like dependency injection which is tied to Ability to implement unit tests for the JavaScript code Client side Model View Whatever We all know Model View Controller MVC from now on was conceived for a good reason Roles and responsibilities matters It was designed as a practical way to separate all of the front end logic into three interconnected parts so code having to do with how data is displayed is clearly separated from the code that validates stores and retrieves that data Also it was thought with unit testing in mind Now MVC is commonly used server side think of ASP NET MVC or Spring MVC where you have a class representing the controller which fetches data into models and then binds them to a template producing a view in the form of an HTML document which is returned to the browser for display on the user screen Remember each time we talk about MVC we are generally referring to the Presentation Layer of an application Now why go crazy and MVC fy my JavaScript code Well because what s trendy right now are dynamic web interfaces where pretty much everything is asynchronous little post backs are done to the server unless really necessary and you have complex UI components like pop ups multi level grids and others living on the screen think of Facebook for example The only way to do this is delegate the browser through JavaScript with the user interface composition interaction between all of the components and lastly fetching and posting data back and forth from the server You really really NEED a way to achieve law and order so the client side code does not become an uncontrollable mess OK enough talk already Let s dive into how to implement a simple application using AngularJS Hello Angular Consider the classic To do List example We want a screen that displays a list of items to be completed also we need to show a mini form that allows us to enter and add new items to the list Here is how it should look So in order to get this done we need to complete some steps Create the HTML document which will be representing our view Include the AngularJS library in the HTML document so we can start creating controllers that will handle behavior of the user interface Create and include a JavaScript file where we are going to create our application object wait for it and define some controllers Add scope almost there variables and functions that will be bound to the view through special AngularJS HTML attributes Basic View Markup Let s start this in a natural way let s create the user interface first We will create a file called todolist html and we will add the following HTML to it Now nothing fancy right there we just included the AngularJS library at line 8 and another file at line 9 which we will create in a moment However just notice the structure of the document We have an UL element which will represent our list of to do items and then a couple input controls so we can add new items to the list It does not have any information on it for now but eventually it will And it will be awesome Let s leave this code as it is for now let s move to the app js file which has all the

    Original URL path: http://blog.informatech.cr/category/programming-2/ (2015-08-19)
    Open archived version from archive

  • .NET | Informatech CR Blog
    handle class dependencies effectively but What exactly is a dependency In real life for instance a car needs an engine in order to function without it it probably won t work at all In programming it is the same thing when a class needs another one in order to function properly it has a dependency on it This is called a class dependency or coupling Let s look at the following code example public class UserManager private Md5PasswordHasher passwordHasher public UserManager this passwordHasher new Md5PasswordHasher public void ResetPassword string userName string password Get the user from the database User user DataContext Users GetByName userName string hashedPassword this passwordHasher Hash password Set the user new password user Password hashedPassword Save the user back to the database DataContext Users Update user DataContext Commit More methods public class Md5PasswordHasher public string Hash string plainTextPassword Hash password using an encryption algorithm The previous code describes two classes UserManager and PasswordHasher We can see how UserManager class initializes a new instance of the PasswordHasher class on its constructor and keeps it as a class level variable so all methods in the class can use it line 3 The method we are going to focus on is the ResetPassword method As you might have already noticed the line 15 is highlighted This line makes use of the PasswordHasher instance hence marking a strong class dependency between UserManager and PasswordHasher Don t Call Us We ll Call You When a class creates instances of its dependencies it knows what implementation of that dependency is using and probably how it works The class is the one controlling its own behavior By using inversion of control anyone using that class can specify the concrete implementation of each of the dependencies used by it this time the class user is the one partially controlling the class behavior or how it behaves on the parts where it uses those provided dependencies Anyways all of this is quite confusing Let s look at an example public class UserManager private IPasswordHasher passwordHasher public UserManager IPasswordHasher passwordHasher this passwordHasher passwordHasher public void ResetPassword string userName string password Get the user from the database User user DataContext Users GetByName userName string hashedPassword this passwordHasher Hash password Set the user new password user Password hashedPassword Save the user back to the database DataContext Users Update user DataContext Commit More methods public interface IPasswordHasher string Hash string plainTextPassword public class Md5PasswordHasher IPasswordHasher public string Hash string plainTextPassword Hash password using an encryption algorithm Inversion of Control is usually implemented by applying a design pattern called the Strategy Pattern as defined in The Gang Of Four book This pattern consists on abstracting concrete component and algorithm implementations from the rest of the classes by exposing only an interface they can use thus making implementations interchangeable at runtime and encapsulate how these implementations work since any class using them should not care about how they work So in order to achieve this we need to sort some things out Abstract an interface from the Md5PasswordHasher class IPasswordHasher so anyone can write custom implementations of password hashers line 28 31 Mark the Md5PasswordHasher class as an implementation of the IPasswordHasher interface line 33 Change the type of the password hasher used by UserManager to IPasswordHasher line 3 Add a new constructor parameter of type IPasswordHasher interface line 5 which is the instance the UserManager class will use to hash its passwords This way we delegate the creation of dependencies to the user of the class and allows the user to provide any implementation it wants allowing it to control how the password is going to be hashed This is the very essence of inversion of control Minimize class coupling The user of the UserManager class has now control over how passwords are hashed Password hashing control has been inverted from the class to the user Here is an example on how we can specify the only dependency of the UserManager class IPasswordHasher md5PasswordHasher new Md5PasswordHasher UserManager userManager new UserManager md5PasswordHasher userManager ResetPassword luis aguilar 12345 So Why is this useful Well we can go crazy and create our own hasher implementation to be used by the UserManager class Plain text password hasher public class PlainTextPasswordHasher IPasswordHasher public string Hash string plainTextPassword Let s disable password hashing by returning the plain text password return plainTextPassword Usage IPasswordHasher plainTextPasswordHasher new PlainTextPasswordHasher UserManager userManager new UserManager plainTextPasswordHasher Resulting password will be 12345 userManager ResetPassword luis aguilar 12345 Conclusion So this concludes our article on Inversion of Control Hopefully with a little more practice you will be able to start applying this to your code Of course the biggest benefit of this technique is related to unit testing So What does it has to do with unit testing Well we re going to see this when we get into type mocking So stay tuned Further Reading The Strategy Pattern by OODesign Design Patterns Elements of Reusable Object Oriented Software book at Amazon Share this Email Facebook Twitter Like this Like Loading April 3 2013 by Luis Aguilar Categories NET Programming 6 Comments Unit Testing 101 Basics Introduction We all know unit testing is an essential part of the development cycle Actually unit tests code is as important as the actual application code Yeap you read that right this is something we should never forget That s why we are going to look at some important introductory concepts relating to composing proper testing code I will be using NUnit as my testing library The package comes with the framework libraries and a set of test runner clients You can download it at their site s download section Unit Test Structure Unit tests are usually grouped in test fixtures Basically a test fixture is a group of unit tests targeted to verify a single application feature Let s illustrate this in code using NUnit Framework namespace AppDemo Tests TestFixture Category User Authentication public class WhenUserIsBeingAuthenticated Test public void ShouldReturnTrueIfValidationIsSuccessful TODO Implement test code Test public void ShouldReturnFalseIfUsernameOrPasswordIsNull TODO Implement test code We can now picture how a test fixture looks in code In this case the test fixture is a regular class filled out with test methods As you might have noticed the class name describes the state of the feature being tested When the user is being authenticated Each particular test method seeks to verify a required result on a specific condition Should return true if validation is successful Running Tests Once you have your fixture ready to go is now time to run all tests on it and see results I will be using the NUnit GUI Runner which looks for all classes in the assembly marked with the TestFixture attribute and then calls each method on them marked with the Test attribute Is important to remember that all tests must be in a separate class library First reason is because it is a good practice you should not be mixing application code with test code and second because the NUnit test runner can only load DLL files So first thing to do is to build the project so we have a DLL containing all our tests Once we have a DLL file with our test fixture classes on it fire up the NUnit test runner NUnit exe and load the file on it At this point everything is quite intuitive You can hit the Run button and see how all tests pass or rebuild the project on Visual Studio and see how the test runner auto updates with new changes Cool huh Arrange Act and Assert Test methods are usually composed of three common phases Arrange act and assert Or triple A if you like Arrange At the very beginning of the method you need to setup the test scenario This includes expected test results for comparison with actual results instances of the components to be tested and type mocking Act After arrangement is done we now have to actually perform the actions that will produce the actual test results For instance call the Validate method on the UserAuthenticator class which performs the actual user validation Assert The assertion phase verifies that actual tests results match what we are expecting Is a good practice to provide comments delimiting each phase Test public void ShouldReturnTrueValidationIsSuccessful Arrange var expectedResult true var userAuthenticator new UserAuthenticator Act var actualResult userAuthenticator Validate luis aguilar 1234 Assert Assert That actualResult Is EqualTo expectedResult message Authentication failed though it should have succeeded As you might see these three phases are executed in order Is a good practice to initialize variables with expected results at Arrange phase to make the Assert phase more readable Also for the sake of readability I am using the Assert That syntax of NUnit so assertions are more verbose Tests Before Implementation Even though unit testing is good for all development methodologies I m an avid supporter of the Test Driven Development TDD methodology As the name implies TDD is all about writing all tests BEFORE you implement actual application code That way your code will meet acceptance criteria right from inception Basically application infrastructure design is driven by tests Now we think on user requirements rather than UML diagrams and classes For instance you should write all the previous sample tests before implementing the UserAuthenticator class That way that particular class will be born satisfying user requirements so we don t have to change its code later on which helps save lots of time and money managers love to hear that and improves code efficiency and design greatly Conclusion Okay hopefully this served out as a brief introduction to the exciting world of unit testing Of course there s a lot more on this topic In next articles we are going to look at concepts like inversion of control type mocking and more things related to TDD Is going to be lots of fun Stay tuned Share this Email Facebook Twitter Like this Like Loading March 29 2013 by Luis Aguilar Categories NET Programming Leave a comment UI Design Using Model View Presenter Part 3 In The Previous Episode In the previous part of the series we finally wrote some code and implemented the three main components of the Model View Presenter pattern We defined our Model class extreme makeover d our old Windows Form class to a slick View compliant class and then created a Presenter which will orchestrate all sorts of evil things so the Model and View play together nicely In case you missed any of our adrenaline filled previous posts now it is a good time to go back to Part 1 or Part 2 and drop a sweat boy Wiring Everything Up Now is time to wire up the Model View and Presenter classes so we have a running application which does the exact same thing as our old application but with a pretty sexy code base This wiring will take place at the Main method of the application which will instantiate the repository class the View and the Presenter initialize everything and then finally run the application So here is our new Program class doing what it does best namespace Codenough Demos WinFormsMVP public static class Program STAThread public static void Main Application EnableVisualStyles Application SetCompatibleTextRenderingDefault false var clientsForm new ClientsForm var clientsRepository new ClientRepository var clientsPresenter new ClientsPresenter clientsForm clientsRepository clientsForm Closed Application Exit Application Run clientsForm If you smash on that Run toolbar button at this point you will see a really nice window poppin up on screen with the clients list box populated just like the old application only that this time all data coming back and forth the View is going through the Presenter what a controlling psycho freak Most important of it all You can now look in the code examples how each part has a single purpose The Model stores data the View displays data and the Presenter controls data flow Now the only thing left to do and hopefully show the real benefit behind this pattern is to try again and implement our pre defined unit tests so we can verify our application meets all requirements Meeting Acceptance Criteria Our application code has never been so ready before for some unit testing We had some already defined which we could not implement at the time simply because the code was being a total jack But now using the MVP pattern on all its glory we are set up for it So for unit testing I am using NUnit and Moq Moq is a library that allows me to create mocks in this case the repository class and the View interface without having to write additional code we don t like to do that Before we proceed let s see what a mock is and what it can do for us A mock is a fake implementation of an interface or a class which members produce data we already know basically is like making a TV display a TiVO recording instead of an actual live show You know in this example we can know what the data coming from the repository class is just by looking at the code but in the real world we might not have that source code at hand Or even worst that data might come from a production dabatase we don t have access to With a mock we can fake a method to do or return anything we want Our first test is called ItShouldLoadAllClients Since our test naming skills are so incredibly sharp we can imply just by reading that title that a clients list has to be loaded during Presenter class initialization We first create a new method called SetUp that will run right before each time a test method runs to set everything up in this case it will initialize mock instances for the repository class and view interface We then proceed to create an instance of the Presenter class which is the test subject our lab rat yes and then we use the Verify method of the mock that will throw a nasty exception and make the unit test fail miserably if the specified View method LoadClients for this particular case was never called during Presenter initialization using Moq using NUnit Framework using System Collections Generic using System Linq namespace Codenough Demos WinFormsMVP TestFixture public class WhenClientsWindowLoads private Mock IClientsView clientsViewMock private Mock ClientRepository clientsRepositoryMock SetUp public void SetUp this clientsViewMock new Mock IClientsView this clientsRepositoryMock new Mock ClientRepository Test public void ItShouldLoadAllClients Act var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Assert clientsViewMock Verify view view LoadClients It IsAny IList ClientModel Expected clients to be loaded on initialization Of course this test passes A call to the LoadClients method is done at the Presenter constructor The following tests are a little more complicated since we will be setting up methods of the View and repository mocks to return what we need them to return method setup Our next test is ItShouldShowFirstClientOnListDetails which requires our presenter to load the first client on the list after initialization For this case we let the SetUp method do its thing and create the respective mocks and then at our test arrange phase we use the Setup method to make the repository mock return a sample list of clients when the FindAll method is called Finally we verify the LoadClient method of the view was called making this the assertion that makes the test case pass and make us happy or fail and quit our jobs Test public void ItShouldShowFirstClientOnListDetails Arrange var clients new List ClientModel new ClientModel Id 1 Name Matt Dylan Age 28 Gender Male Email mattd none com new ClientModel Id 2 Name Anna Stone Age 22 Gender Female Email ann none com clientsRepositoryMock Setup repository repository FindAll Returns clients Act var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Assert clientsViewMock Verify view view LoadClient clients First Expected first client to be loaded on initialization The last test is ItShouldShowClientDetailsOnListItemSelected and finding out the way it works will be your homework dear reader This is the most complicated of them all since now we use Moq to fire view events and wake up the Presenter which should be listening to them Test public void ItShouldShowClientDetailsOnListItemSelected Arrange var clients new List ClientModel new ClientModel Id 1 Name Matt Dylan Age 28 Gender Male Email mattd none com new ClientModel Id 2 Name Anna Stone Age 22 Gender Female Email ann none com clientsRepositoryMock Setup repository repository FindAll Returns clients clientsRepositoryMock Setup repository repository GetById 1 Returns clients First clientsViewMock SetupGet view view SelectedClient Returns clients First var clientsPresenter new ClientsPresenter clientsViewMock Object clientsRepositoryMock Object Act clientsViewMock Raise view view ClientSelected null Assert clientsViewMock Verify view view LoadClient clients First Expected first client to be loaded on initialization Conclusion Making code testable is not easy at all No really AT ALL At least not at first since you have to think on all the possible test scenarios your code could go through But in the long term this is what makes testable code more robust and clean than regular hastily thrown together code Okay this makes it up for it Hope you enjoyed it and learned a couple things Stay tuned for more talk on patterns and good practices and maybe really off topic things Oh Don t forget to check out the code examples including an exciting port on Java Code Examples WinformsMVP C SwingMVP Java Share this Email Facebook Twitter Like this Like Loading March 21 2013 by Luis Aguilar Categories NET Programming Tags net c development model view presenter mvp user interface design 1 Comment UI Design Using Model View Presenter Part 2 What Just Happened In the previous part we demonstrated the traditional way of doing things when it comes to UI design We also reviewed some key concepts like Code Coverage and Separation Of Concerns Lastly we reviewed some concepts behind the Model View Presenter pattern Yeap that was a lot

    Original URL path: http://blog.informatech.cr/category/programming-2/net-programming/ (2015-08-19)
    Open archived version from archive

  • Java | Informatech CR Blog
    are accessible to classes and interfaces in the same package and all derived classes even in separate packages They cannot be accessed by unrelated classes in other packages 1 4 5 Default Access package access Classes and interfaces defined without any explicit access modifier are defined with package accessibility default accessibility They can only be accessed by classes and interfaces defined in the same package 1 4 6 Private Access Modifier The members of a class defined using the private access modifier are accessible only to themselves Private members are not accessible outside the class they are defined 1 5 Nonaccess Modifiers 1 5 1 Abstract Modifier When added to the definition of a class interface or method the abstract modifier changes its default behavior 1 5 1 1 Abstract Class When the abstract keyword is prefixed to the definition of a concrete class it changes it to an abstract class An abstract class can t be instantiated An abstract class can be defined without any abstract methods but a concrete class cannot define an abstract method 1 5 1 2 Abstract Interface An interface is an abstract entity by default The Java compiler automatically adds the keyword abstract to the definition of an interface 1 5 1 3 Abstract Method An abstract method doesn t have a body Usually an abstract method is implemented by a derived class 1 5 1 4 Abstract Variables No type of variable can be defined as abstract 1 5 2 Final Modifier The keyword final changes the default behavior of a class variable or method 1 5 2 1 Final Class A class defined final cannot be extended by other classes 1 5 2 2 Final Interface No interface can be marked as final 1 5 2 3 Final Variable A final variable can only be assigned a value once 1 5 2 4 Final Method A final method defined in a base class cannot be overridden in a derived class 1 5 3 Static Modifier Can be applied to the definitions of variables methods classes and interfaces 1 5 3 1 Static Variables They are common to all instances of a class and are not unique They are shared by all the objects of the class Static variables may be accessed even when no instances of a class have been created 1 5 3 2 Static Methods Static methods aren t associated with objects and can t use any of the instance variables of a class They can be used to use or manipulate static variables of a class Nonprivate static variables and methods can be inherited by derived classes and can be redefined within the derived class 1 5 3 3 What can a static method access Non static variables and methods can access static variables and methods Static methods and variables cannot access the instance methods of a class This entry is the first part of of a series on Java Basics for further reading Java Basics II Java Basics III Share this Email Facebook Twitter Like this Like Loading April 29 2015 by ldac89 Categories Java Programming Tags java Leave a comment Java 8 Streams and JPA Since the definition of the JPA Standard predates the release of Java 8 it is not surprising that the JPA API is only based on collections There is no way to obtain a Java 8 Stream out of a query object For those out there using Hibernate as their JPA provider there is an interesting way to create a stream for your JPQL queries Hibernate Scrollable Results Hibernate supports many more features than those offered by the JPA Standard only Hibernate s Query class allows us to obtain an iterator like object for a JQPL query This iterator like class is named ScrollableResults You can see a great example of this feature in this blog post about Reading Large Result Sets with Hibernate and MySQL I have taken the liberty of copying one of their examples Query query session createQuery query query setReadOnly true query setFetchSize 100 ScrollableResults results query scroll ScrollMode FORWARD ONLY while results next Object row results get process the entity here results close Creating an Iterator Wrapper around Scrollable Results Let s take this a bit further now by implementing a Java Iterator wrapper around the Hibernate s scrollable results object as shown below class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 Gaining Access to Hibernate Session through JPA Entity Manager As you can see the examples above use a Hibernate session object to obtain an instance of a Hibernate query object Supposing we are using JPA we typically have access to an EntityManager but not to any particular implementation objects of the underlaying provider To gain access to the Hibernate s Session object we can use a special method in the entity manger Session session entityManager unwrap Session class Be warned that at this point we are escaping from the safety of vendor agnostic code In other words if we ever wanted to use another provider like OpenJPA or EclipseLink we would be forced to find a different alternative to implement our code here since those other providers won t offer anything like Hibernate s Session and ScrollableResults From Iterators to Spliterators to Streams Our next step consists in obtaining a Java 8 stream out of this iterator Lukas Eder recently wrote an interesting article about the difficulties to obtain a stream out of an iterable object which will be pretty handy here To achieve our goal we now need to use two utility classes in Java 8 named StreamSupport and Spliterators For instance we could take an iterator like the one we defined above and transform it into a Spliterator by doing private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE This Splititerator is an intermediate product that we can now use to create a Java 8 stream out of it StreamSupport stream spliterator false At this point we have built enough to create our first stream out of a JPQL query We can do it as follows public Stream T getResultStream String sql Integer fetchSize Map String Object parameters Query query session createQuery sql if fetchSize null query setFetchSize fetchSize for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue query setReadOnly true ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close A JPA Stream API We can do a little bit better by defining the basics of the type of query object we are currently missing in JPA Standard API public interface StreamQuery T Stream T getResultStream StreamQuery T setParameter String name Object value StreamQuery T setFetchSize int fetchSize And putting together all we have learned so far we could create this implementation of our new StreamQuery interface public class HibernateQueryStream T implements StreamQuery T private final Session session private final String sql private final Class T type private final Map String Object parameters new HashMap private Integer fetchSize public HibernateQueryStream EntityManager entityManager String sql Class T type this session entityManager unwrap Session class this sql sql this type type Override public StreamQuery T setParameter String name Object value parameters put name value return this Override public StreamQuery T setFetchSize int fetchSize this fetchSize fetchSize return this Override public Stream T getResultStream Query query session createQuery sql if fetchSize null query setFetchSize fetchSize query setReadOnly true for Map Entry String Object parameter parameters entrySet query setParameter parameter getKey parameter getValue ScrollableResults scroll query scroll ScrollMode FORWARD ONLY return StreamSupport stream toSplitIterator scroll type false onClose scroll close private Spliterator T toSplitIterator ScrollableResults scroll Class T type return Spliterators spliteratorUnknownSize new ScrollableResultIterator scroll type Spliterator DISTINCT Spliterator NONNULL Spliterator CONCURRENT Spliterator IMMUTABLE private static class ScrollableResultIterator T implements Iterator T private final ScrollableResults results private final Class T type ScrollableResultIterator ScrollableResults results Class T type this results results this type type Override public boolean hasNext return results next Override public T next return type cast results get 0 The Repository Layer On top of this component we can now build our repository layer Repository public class StreamRepository PersistenceContext unitName demo private EntityManager entityManager public Stream Order getOrderHistory String email String jpql SELECT o FROM Order o WHERE o customer email email StreamQuery Order query new HibernateQueryStream entityManager jpql Order class return query getResultStream And from here the rest is a piece of cake orderRepository findOrderHistory email filter order order total 100 map Order getOrderLines flatMap List stream map OrderLine getTotal reduce 0 x y x y It is important to highlight that the Hibernate session must be alive by the time we actually consume the stream because it is at that point that the entities will be mapped So make sure that wherever you consume the stream the Hibernate session or you entity manager context is still alive Further Reading Java Stream API JPA Specification Reading Large Result Sets with Hibernate and MySQL Really Too Bad that Java 8 Doesn t Have Iterable stream Share this Email Facebook Twitter Like this Like Loading December 17 2014 by Edwin Dalorzo Categories Java Tags java JPA Standard 2 Comments Functional Programming with Java 8 Functions I have finally had the opportunity to work in a couple of projects being entirely developed with Java 8 and during the past months I ve experienced first hand many of the new functional programming features in the language So I decided to write a series of articles about some of these things I ve being learning and how some of the well known functional programming constructs can be translated into Java 8 Preliminaries Ok let s start with something simple The following is a lambda expression i e an anonymous function that takes an argument x and increments it by one In other words a function that receives apparently an integer and returns a new incremented integer x x 1 And what is the type of this function in Java Well the answer is that it depends In Java the same lambda expression could be bound to variables of different types For instance the following two are valid declarations in Java Function Integer Integer add1 x x 1 Function String String concat1 x x 1 The first one increments an integer x by one whereas the second one concatenates the integer 1 to any string x And how can we invoke these functions Well now that they are bound to a reference we can treat them pretty much like we treat any object Integer two add1 apply 1 yields 2 String answer concat1 apply 0 1 yields 0 1 1 So as you can see every function has a method apply that we use to invoke it and pass it an argument And what if I already have a method that does that can I use it as a function Yes since an alternative way to create functions is by using methods we had already defined and that are compatible with our function definition Suppose that we have the following class definition with methods as defined below public class Utils public static Integer add1 Integer x return x 1 public static String concat1 String x return x 1 As you can see the methods in this class are compatible with our original function definitions so we could use them as method references to create the same functions we did before with lambda expressions Function Integer Integer add1 Utils add1 Function String String concat1 Utils concat1 These two are just the same thing as the ones we did before High Order Programming The cool thing about functions is that they encapsulate behavior and now we can take a piece of code put it into a function and pass it around to other functions or methods for them to use it This type of functions that operate on or produce new functions are typically called high order functions and the programming style based on exploiting this powerful feature is called unsurprisingly high order programming About Functions that Create Functions Let s see a couple of examples of how we can do this using function objects Let s consider the following example Function Integer Function Integer Integer makeAdder x y x y Above we have a function called makeAdder that takes an integer x and creates a new function that takes an integer y and when invoked adds x to y We can tell this is a high order function because it produces a new function Now we use this to create our original add1 function Function Integer Integer add1 makeAdder apply 1 Function Integer Integer add2 makeAdder apply 2 Function Integer Integer add3 makeAdder apply 3 With our new high order function however we could also create add2 add3 addn right Can t we define this in a simpler way as we did before with the Utils class methods Yes we can Consider the following addition to the Utils class public class Utils public static Function Intger Integer adder Integer x return y x y This signature is a bit simpler to read than that in our lambda expression but as you can see it is pretty much the same thing The function continues to receive the same number and type of arguments and continues to return the same type of result We can now use this simpler function factory to create our makeAdder and add1 functions again Function Integer Function Integer Integer makeAdder Utils adder Function Integer Integer add1 makeAdder apply 1 And there you have it this is exactly the same thing as before About Functions that Receive Functions as Arguments Let s suppose we had the following two functions defined Function Integer Integer add1 x x 1 Function Integer Integer mul3 x x 3 Now naively we could invoke this two functions together to increment and multiply a number by 3 right Like this Integer x 10 Integer res mul3 apply add1 apply x yields 33 But what if we created a function that did both things instead Consider the following pseudocode f g x g f x This would be a function that takes two other unary functions and creates yet another function that applies the original two in certain order This is a classical example of what is called function composition In some languages there is even an operator to compose two functions in this way h f o g Where o would be a binary operator that would compose functions f and g pretty much as we did in pseudocode above and produce a new function h How can we do function composition in Java I can think of two ways to do this in Java one more difficult than the other Let s start with the more difficult first because that will let us appreciate the value of the simpler solution later on Function Composition Strategy 1 First we must start by realizing that the function in pseudocode above is a binary function i e a function that receives two arguments But all our examples so far have dealt only with unary functions It would seem this is not important but in Java it is since functions of different arities have different target functional interfaces In Java a function that receives two arguments is called BinaryOperator For instance using a BinaryOperator we could implement a sum operator BinaryOperator Integer sum a b a b Integer res sum apply 1 2 yields 3 Well just as easily we could implement the compose operator right Only that in this case instead of two simple integers we receive two unary functions BinaryOperator Function Integer Integer compose compose f g x g apply f apply x Now we can easily use this to fabricate a compound function that adds 1 and multiplies by 3 one after the other Function Integer Integer h compose apply add1 mul3 Integer res h apply 10 yields 33 And now we can beautifully and in really simple way combine two unary integer functions Function Composition Strategy 2 Now function composition is something so common that it would have been a mistake if the Java Expert Group would have not considered it in their API design and so to make our lives simpler all Function objects have a method called compose that allows us to very easily compose two functions together The following code produces the exact same result as above Function Integer Integer h mul3 compose add1 Integer res h apply 10 Partial Function Application or Currying In most functional programming languages it is possible to create partially applied functions That is if a function is receiving multiple arguments we can partially invoke the function providing just a few arguments and receive a partially applied function out of it This is typically called currying Although you have not noticed it we have already covered that in this article but now we are going to make it much more evident So consider the following pseudo code sum x y x y Then we say that sum is a function that accepts one parameter x and fabricates another anonymous function that in turn accepts one parameter y that when invoked sums x and y In many functional programming languages a construct like this can be invoked as if this was just one simple function by doing sum 10 5 yields 15 But the truth is that this is just syntactic sugar to do sum 10 5 yields 15 Since sum is a function that returns a function The beauty of this idiom is that now we could partially apply sum plus10 sum 10 And now plus10 is a partially applied function of sum Can you see now where we had already talked about this plus10 5 yields 15 Can we do this with Java The truth is that we have already done it above we just probably did not notice Unfortunately in Java we do not have the syntactic sugar that some other language have and therefore this is a bit more verbose Function Integer Function Integer Integer sum x y x y Well you can see sum is declared in a currified way And now we can partially apply it Function Integer Integer plus10 sum apply 10 Integer res plus10 apply 5 yields 15 Unary Binary Ternary and n ary Functions So as mentioned above Java uses different functional interfaces for different function arities And so Function T R is a functional interface for any unary function where the domain and the codomain of the function may be of different types For instance we could define a function that receives a string value and parses it as an integer Function String Integer atoi s Integer valueOf s But most of our examples above are for integer functions whose argument and return value are of this same type For those cases we could alternatively use the UnaryOperator T instead This is just a Function T T Thus some our declarations above could be slightly simplified with this functional interface UnaryOperator Integer add1 n n 1 UnaryOperator String concat1 s s 1 Function Integer UnaryOperator Integer sum x y x y UnaryOperator Integer sum10 sum apply 10 I have already written another article that explains Why Java 8 has Interface Pollution like this in case you are interested in an explanation Value Types and Primitive Type Functions Evidently using a type like Integer incurs into the costs of boxing and unboxing when our functions have to deal with a primitive type like int As you know Java does not support value types as type arguments in generic declarations so to deal with this problem we can use alternative functional interfaces like ToIntFunction IntFunction or IntUnaryOperator Or we can define our own primitive function interface IntFx public int apply int value Then we can do IntFx add1 n n 1 IntFunction IntFx sum x y x y IntFx sum10 sum apply 10 sum10 apply 4 yields 14 Similar functional interfaces can be found in the Java API for types double and long as well This topic is also covered in the alternative article mentioned above about interface pollution And that s it for the time being I hope that in a future article I can take this a bit further and show some practical applications derived from my experience in actual projects Further Reading High Order Programming High Order Functions Function Composition Currying Why Java 8 has Interface Pollution Share this Email Facebook Twitter Like this Like Loading October 19 2014 by Edwin Dalorzo Categories Java Programming Tags function composition functional programming high java java8 Leave a comment Why There Is Interface Pollution in Java 8 I was reading this interesting post about The Dark Side of Java 8 In it Lukas Eder the author mentions how bad it is that in the JDK 8 the types are not simply called functions For instance in a language like C there is a set of predefined function types accepting any number of arguments with an optional return type Func and Action each one going up to 16 parameters of different types T1 T2 T3 T16 but in the JDK 8 what we have is a set of different functional interfaces with different names and different method names and whose abstract methods represent a subset of well know function signatures function arities i e nullary unary binary ternary etc The Type Erasure Issue So in a way both languages suffer from some form of interface pollution or delegate pollution in C The only difference is that in C they all have the same name In Java unfortunately due to type erasure there is no difference between Function T1 T2 and Function T1 T2 T3 or Function T1 T2 T3 Tn so evidently we couldn t simply name them all the same way and we had to come up with creative names for all possible types of function combinations Don t think the expert group did not struggle with this problem In the words of Brian Goetz in the lambda mailing list As a single example let s take function types The lambda strawman offered at devoxx had function types I insisted we remove them and this made me unpopular But my objection to function types was not that I don t like function types I love function types but that function types fought badly with an existing aspect of the Java type system erasure Erased function types are the worst of both worlds So we removed this from the design But I am unwilling to say Java never will have function types though I recognize that Java may never have function types I believe that in order to get to function types we have to first deal with erasure That may or may not be possible But in a world of reified structural types function types start to make a lot more sense So how does this affect us as developers The following is a categorization of some of the most important new functional interfaces and some old ones in the JDK 8 organized by function return type and the number of expected arguments in the interface method Functions with Void Return Type In the realm of functions with a void return type we have the following Type of Function Lambda Expression Known Functional Interfaces Nullary doSomething Runnable Unary foo System out println foo Consumer IntConsumer LongConsumer DoubleConsumer Binary console text console print text BiConsumer ObjIntConsumer ObjLongConsumer ObjDoubleConsumer n ary sender host text sender send host text Define your own Functions with Some Return Type T In the realm of functions with a return type T we have the following Type of Function Lambda Expression Known Functional Interfaces Nullary Hello World Callable Supplier BooleanSupplier IntSupplier LongSupplier DoubleSupplier Unary n n 1 n n 0 Function IntFunction LongFunction DoubleFunction IntToLongFunction IntToDoubleFunction LongToIntFunction LongToDoubleFunction DoubleToIntFunction DoubleToLongFunction UnaryOperator IntUnaryOperator LongUnaryOperator DoubleUnaryOperator Predicate IntPredicate LongPredicate DoublePredicate Binary a b a b 1 0 x y x y x y x y 0 Comparator BiFunction ToIntBiFunction ToLongBiFunction ToDoubleBiFunction BinaryOperator IntBinaryOperator LongBinaryOperator DoubleBinaryOperator BiPredicate n ary x y z 2 x Math sqrt y z Define your own An advantage of this approach is that we can define our own interface types with methods accepting as many arguments as we would like and we could use them to create lambda expressions and method references as we see fit In other words we have the power to pollute the world with yet even more new functional interfaces Also we can create lambda expressions even for interfaces in earlier versions of the JDK or for earlier versions of our own APIs that defined SAM types like these And so now we have the power to use Runnable and Callable as functional interfaces However these interfaces become more difficult to memorize since they all have different names and methods Still I am one of those wondering why they didn t solve the problem as in Scala defining interfaces like Function0 Function1 Function2 FunctionN Perhaps the only argument I can come up with against that is that they wanted to maximize the possibilities of defining lambda expressions for interfaces in earlier versions of the APIs as mentioned before Lack of Value Types So evidently type erasure is one driving force here But if you are one of those wondering why we also need all these additional functional interfaces with similar names and method signatures and whose only difference is the use of a primitive type then let me remind you that in Java we also lack of value types like those in a language like C This means that the generic types used in our generic classes can only be reference types and not primitive types In other words we can t do this List int numbers asList 1 2 3 4 5 But we can indeed do this List Integer numbers asList 1 2 3 4 5 The second example though incurs in the cost of boxing and unboxing of the wrapped objects back and forth from to primitive types This can become really expensive in operations dealing with collections of primitive values So the expert group decided to create this explosion of interfaces to deal with the different scenarios To make things less worse they decided to only deal with three basic types int long and double Quoting the words of Brian Goetz in the lambda mailing list More generally the philosophy behind having specialized primitive streams e g IntStream is fraught with nasty tradeoffs On the one hand it s lots of ugly code duplication interface pollution etc On the other hand any kind of arithmetic on boxed ops sucks and having no story for reducing over ints would be terrible So we re in a tough corner and we re trying to not make it worse Trick 1 for not making it worse is we re not doing all eight primitive types We re doing int long and double all the others could be simulated by these Arguably we could get rid of int too but we don t think most Java developers are ready for that Yes there will be calls for Character and the answer is stick it in an int Each specialization is projected to 100K to the JRE footprint Trick 2 is we re using primitive streams to expose things that are best done in the primitive domain sorting reduction but not trying to duplicate everything you can do in the boxed domain For example there s no IntStream into as Aleksey points out If there were the next question s would be Where is IntCollection IntArrayList IntConcurrentSkipListMap The intention is many streams may start as reference streams and end up as primitive streams but not vice versa That s OK and that reduces the number of conversions needed e g no overload of map for int T no specialization of Function for int T etc We can see that this was a difficult decision for the expert group I think few would agree that this is cool and most of us would most likely agree it was necessary The Checked Exceptions Issue There was a third driving force that could have made things even worse and it is the fact that Java supports two type of exceptions checked and unchecked The compiler requires that we handle or explicitly declare checked exceptions but it requires nothing for unchecked ones So this creates an interesting problem because the method signatures of most of the functional interfaces do not declare to throw any exceptions So for instance this is not possible Writer out new StringWriter Consumer String printer s out write s oops compiler error It cannot be done because the write operation throws a checked exception i e IOException but the signature of the Consumer method does not declare it throws any exception at all So the only solution to this problem would have been to create even more interfaces some declaring exceptions and some not or come up with yet another mechanism at the language level for exception transparency Again to make things less worse the expert group decided to do nothing in this case In the words of Brian Goetz in the lambda mailing list Yes you d have to provide your own exceptional SAMs But then lambda conversion would work fine with them The EG discussed additional language and library support for this problem and in the end felt that this was a bad cost benefit tradeoff Library based solutions cause a 2x explosion in SAM types exceptional vs not which interact badly with existing combinatorial explosions for primitive specialization The available language based solutions were losers from a complexity value tradeoff Though there are some alternative solutions we are going to continue to explore though clearly not for 8 and probably not for 9 either In the meantime you have the tools to do what you want I get that you prefer we provide that last mile for you and secondarily your request is really a thinly veiled request for why don t you just give up on checked exceptions already but I think the current state lets you get your job done So it s up to us the developers to craft yet even more interface explosions to deal with these in a case by case basis interface IOConsumer T void accept T t throws IOException static T Consumer T exceptionWrappingBlock IOConsumer T b return e try b accept e catch Exception ex throw new RuntimeException ex In order to do Writer out new StringWriter Consumer String printer exceptionWrappingBlock s out write s Probably in the future maybe JDK 9 when we get Support for Value Types in Java and Reification we will be able to get rid of or at least no longer need to use anymore these multiple interfaces In summary we can see that the expert group struggled with several design issues The need requirement or constraint to keep backwards compatibility made things difficult then we have other important conditions like the lack of value types type erasure and checked exceptions If Java had the first and lacked of the other two the design of JDK 8 would probably have been different So we all must understand that these were difficult problems with lots of tradeoffs and the EG had to draw a line somewhere and make a decisions So when we find ourselves in the dark side of Java 8 probably we need to remind ourselves that there is a reason why things are dark in that side of the JDK Further Reading Related Answer in Stackoverflow Lambda Straw Man Proposal Neal Gafter on The Future of Java Share this Email Facebook Twitter Like this Like Loading April 4 2014 by Edwin Dalorzo Categories Java Programming 14 Comments Memoized Fibonacci Numbers with Java 8 Since today is Fibonacci Day I decided that it would be interesting to publish something related to it I believe one of the first algorithms we all see when learning non linear recursion is that of calculating a Fibonacci number I found a great explanation on the subject in the book Structure and Interpretation of Computer Programs SIC and I dedicated some time to playing with the Fibonacci algorithm just for fun While doing so I found an interesting way to improve the classical recursive algorithm by using one of the new methods added in Java 8 in the Map interface and which I used here to implement a form of memoization Classical Recursive Fibonacci In the classical definition of Fibonacci we learn that We program this very easily in Java public static long fibonacci int x if x 0 x 1 return x return fibonacci x 1 fibonacci x 2 Now the problem with this algorithm is that with the exception of the base case we recursively invoke our function twice and interestingly one of the branches recalculates part of other branch every time we invoke the function Consider the following image taken from SIC that represents an invocation to fibonacci 5 Clearly the branch to the right is redoing all the work already done during the recursive process carried out by the left branch Can you see how many times fibonacci 2 was calculated The problem gets worse as the function argument gets bigger In fact this problem is so serious that the calculation of a small argument like fibonacci 50 might take quite a long time Memoized Recursive Fibonacci However there is a way to improve the performance of the original recursive algorithm I mean without having to resort to a constant time algorithm using for instance Binet s formula The serious problem we have in the original algorithm is that we do too much rework So we could alleviate the problem by using memoization in other words by providing a mechanism to avoid repeated calculations by caching results in a lookup table that can later be used to retrieve the values of already processed arguments In Java we could try to store the Fibonacci numbers in a hast table or map In the case of the left branch we ll have to run the entire recursive process to obtain the corresponding Fibonacci sequence values but as we find them we update the hash table with the results obtained This way the right branches will only perform a table lookup and the corresponding value will be retrieved from the hash table and not through a recursive calculation again Some of the new methods in the class Map in Java 8 simplify a lot the writing of such algorithm particularly the method computeIfAbsent key function Where the key would be the number for which we would like to look up the corresponding Fibonacci number and the function would be a lambda expression capable of triggering the recursive calculation if the corresponding value is not already present in the map So we can start by defining a map and putting the values in it for the base cases namely fibonnaci 0 and fibonacci 1 private static Map Integer Long memo new HashMap static memo put 0 0L fibonacci 0 memo put 1 1L fibonacci 1 And for the inductive step all we have to do is redefine our Fibonacci function as follows public static long fibonacci int x return memo computeIfAbsent x n fibonacci n 1 fibonacci n 2 As you can see the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map this recursive process will be triggered entirely for the left branch

    Original URL path: http://blog.informatech.cr/category/programming-2/java/ (2015-08-19)
    Open archived version from archive