Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Java 7 Beginner's Tutorial (Third Edition) - Budi Kurniawan põhinev konspekt:
- ##################################################################################
- - constants have keyword of final, e.g. 'final int minuInt = 50;'
- - The result of a division using the / operator is always an
- integer. If the divisor does not divide the dividends equally,
- the remainder will be ignored. (java.lang.Math sisaldab mõistlikkemaid jagamisi)
- - some unary operators (+,-,tilde) and binary ops (+,-,*,/) cause automatic promotion,
- i.e. elevation to a wider type such as from byte to int;
- - empty statement (i.e lihtsalt ;) is legal;
- - statements can be grouped in a block; by definition, block is a sequence of the following
- programming elements:
- statements
- local class declarations
- local variable declaration statements
- - statement and a statement block can be labeled, e.g. sectionA: x = y + 1;
- või lable'dame blocki: start: { //statements }
- - The purpose of labeling a statement or a block is so that it
- can be referenced by the break and continue statements.
- - The break statement can be followed by a label. The
- presence of a label will transfer control to the start of the
- code identified by the label.(tähendab see ikka seda? imho näitab see millisest
- loopist breakida; revision: miks ma seda küll arvasin lol?
- - Java does not have a goto statement like in C or C++, and
- labels are meant as a form of goto.
- - As with break, continue may be followed by a label to
- identify which enclosing loop to continue to.
- - nagu C#-ski, peavad kõik elemendid klassides resideeruma;
- - if you declare a local reference variable within a method but
- do not assign an object to it, you will need to assign null to it
- to satisfy the compiler, e.g. Book minuBook = null; meetodiväliselt
- võib ka vist lihtsalt Book minuBook; deklareerida;
- - Class-level reference variables will be initialized when an
- instance is created, therefore you do not need to assign
- null to them.
- - When a program runs, some memory space is
- allocated for data. This data space is logically divided into
- two, the stack and the heap. Primitives are allocated in the
- stack and Java objects reside in the heap.
- - When you declare a reference variable, some
- bytes are also set aside in the stack, but the memory does
- not contain an object's data, it contains the address of the
- object in the heap.
- - javas jagatakse eri osad 'package'-itesse (i.e. java.lang.reflect etc); kui õigesti mõistan,
- siis on see pisut sarnane C# namespace'i kontseptsioonile;
- - by convention your package names should be based on your domain name in reverse, i.e. com.playtech
- - To group a class in a package use the keyword package followed by the package name.
- - A class that has no package declaration is said to
- belong to the default package.
- - It is a bad idea for a class to not have a package.
- - There are four access control modifiers in Java: public,
- protected, private, and the default access level.
- - class memberite puhul on protected ja defaulti vahe on see, et protected
- puhul saavad membereid accessida ka child klasside objektid, kuid default
- puhul mitte;
- - afaik siis saab child ka parenti defaultile ligi pääseda, kui nad asuvad
- samas package'is;
- - A Java source file can only contain one public class.
- However, it can contain multiple classes that are not
- public. (ehk vaid 1 public class per .java fail)
- - A public class must be saved in a file that has the same
- name as the class, and the extension must be java.
- - Classes with the default access level can only be used by
- other classes that belong to the same package.
- - Access levels to constructors
- are the same as those for fields and methods. Therefore,
- constructors can have public, protected, default, and private
- access levels.
- - import käib package'ite kohta, e.g. import java.io.File;
- - kui tahad kõiki package'i klasse, siis import java.io.*;
- - static keyword may come before or after the access modifier,
- kuigi üldiselt pannakse access mod ette;
- - static meetodist ei saa kutsuda non-static fielde ega meetodeid;
- - You can only declare a static variable in a class level.
- You cannot declare local static variables even if the
- method is static.
- - refrence vars võivad ka olla static; Static reference variables provide a good way of exposing
- the same object that needs to be shared among other
- different objects.
- - tihti on mõistlik final fieldid ka staticuna deklareerida;
- - nende naming convention näeb ette all caps ja sõnad underscore'iga eraldatud;
- - Static final reference variables are also possible.
- However, note that only the variable is final, which means
- once it is assigned an address to an instance, it cannot be
- assigned another object of the same type.
- - If a method declares a local variable that has the same
- name as a class-level variable, the former will ‘shadow’ the
- latter. To access the class-level variable from inside the
- method body, use the this keyword.
- - klassis olevate { } vahele lähevad ininialization koodid; staatilise initializationi
- jaoks (mida jooksutatakse vaid kord, i.e. java init ajal) kasut. static { //statements; }
- - another way to write initialization code is in the
- constructor. In fact, initialization code in a constructor is
- more noticeable and hence preferable.
- - kui on aga mitu konstruktorit, siis on mõistlikum init osa meetodisse wrappida
- ning igal konstruktoril seda kutsuda;
- - Unused objects are defined as objects that are no
- longer referenced or objects whose references are already
- out of scope.
- - kui õigesti mõistan, siis 'out of scope' tähendab seda, kui objekti enam
- mingil põhjusel ei kasutata, nt kui kasutati vaid for loopis, millest on väljutud;
- - nagu c#-s, on ka javas stringid reference type'i;
- - If you use the
- new keyword, the JVM will always create a new instance of
- String. With a string literal, you get an identical String
- object, but the object is not always new. It may come from a
- pool if the string “Java is cool” has been created before.
- - string literals on double quote'ide vahel olevad; neid deklareerides ei tohi rida vahetada,
- küll aga tohib concateante'ida + märgiga;
- - you can concatenate a string w/ a primitive or another object, nt stringi ja int-i võib liita;
- - If an object is concatenated with a String, the toString
- method of the former will be called and the result used in
- the concatenation.
- - calling method on String class returns always a new object !!!!!!;
- - StringBuffer on sama mis StringBuilder, kuid esimene on multithreaded envide jaoks;
- - StingBuilder:
- - You can pass a java.lang.CharSequence, a String, or an int.
- - default SB objekti capacity on 16chari, kuid võimalusel võiks instatnsieerimisel
- juba ära defineerida (nt new StringBuilder(100);)
- - meetodid returnivad sama objekti, millele sai meetod kutsutud, seega saab
- meetodeid chainida: sb.append("2 ").append("lol");
- - arrays are also objects
- - fun fact - java.lang.Array klassi pole olemas; arrayd on special Java objektid;
- - An array can also contain other arrays, creating an
- array of arrays.
- - deklareerimine: a) type[] arrayName; b) type arrayName[];
- - deklareerimisel veel array objekti ei luua, ega ruumi ei anta; compiler lihtsalt
- loob object reference'i;
- - üheks arr loomiseks on kasutada new keywordi, nt new int[4], int[] ints = new int[4];
- - teiseks võimaluseks on ilma new keywordi kasutamata, nt
- String[] names = { "mari", "jüri" };
- loob names[] array suurusega 2;
- - When an array is created, its components are either
- null (if the component type is an object type) or the
- default value of the component type (if the array
- contains primitives); nt int[] puhul oleks defaultis arr täis nulle (0);
- - arrayd laiendada ei saa; kui tahad, siis pead uue array looma:
- int[] newArr = Arrays.copyOf(vanaArr, 4); (kus 4 on uue array suurus)
- - sh. võib uue array pikkus olla ka väiksem kui original; sel juhul lihtsalt
- kopeeritakse uude esimesed original array elemendid;
- - igale objektitüübile vastab konkreetne Class objekt (inheritud), mis seda tüüpi kirjeldab.
- läbi selle on võimalik ka new keywordi kasutamata uusi instantse luua (miks? sest võib
- juhtuda, et sa ei tea loodava tüübi nime. seda tehakse Class klassi forName ning newInstance
- meetodite läbi);
- - inputi saab kas läbi System.in.read() või läbi Scanner klassi; (viimane eelistatum);
- - Conversion from primitive types to corresponding wrapper
- objects and vice versa can happen automatically. Boxing
- refers to the conversion of a primitive to a corresponding
- wrapper instance, such as an int to a java.lang.Integer.
- Unboxing is the conversion of a wrapper instance to a
- primitive type, such as Byte to byte.
- - et meetodile sööta muutuva nr-ga argse, võid kas signatuuris märkida parameetriks listi, või
- kasutada varargs-e, nt public void main(String... args); varargs on mosdef parem!
- - teksti format käib läbi %s tagide, mitte {0}, {1}... jne;
- - kas javas on sama nagu C-s, et %s käib Stringi kohta, %d int-ile jne????
- - In Java, by default all classes are
- extendible, but you can use the final keyword to prevent
- classes from being subclassed (inherited);
- - A consequence of the is-a relationship is that it is legal
- to assign an instance of a subclass to a reference variable
- of the parent type, e.g. Animal animal = new Bird(); (sest bird on alati animal, küll
- aga ei kehti vastupidine seaduspära);
- - Increasing
- the visibility of a method defined in a superclass from
- protected to public is allowed. However, reducing visibility
- is illegal.
- - What if you create a method that has the same
- signature as a private method in the superclass? It is not
- method overriding, since private methods are not visible
- from outside the class.
- - You cannot override a final method.
- - when you create a child object, all its parent
- classes are also instantiated. (hakataksegi kõige tipust instantsieerima);
- - You can explicitly call the parent's constructor from a
- subclass's constructor by using the super keyword, but
- super must be the first statement in the constructor. Using
- the super keyword is handy if you want another constructor
- in the superclass to be invoked, e.g. super(s);
- - super kerywordi kaudu saab ka pääseda ligi parenti overridden field'idele ja
- meetoditele
- - you can cast a child to parent class - that's called upcasting;
- - To upcast a Child object, all you need to do is assign the
- object to a reference variable of type Parent.
- - in that case you could also cast it back to child (downcasting); this requires
- child type in brackets, i.e. Child child2 = (Chiled) parentMisSaiCastitudChildist; //downcasting;
- - note: sulge ongi vaid downcastimisel tarvis;
- - instanceof keyword: nt if (s instanceof java.lang.Strint)
- - kui objekt on null, siis evalueerib false
- - if (child instanceof Parent) // evaluates to true, sest subclass is a type of its superclass;
- - final keyword klassi puhul preventib seda klassi extendimast, st seda klassi ei saa pärida;
- -
- + Err handling
- - ühes catch blockis võib olla mitu exceptionit; need tuleb eraldada pipe'iga,
- e.g. catch (ÜksExeption | TeineException e) { }
- - ressursside sulgemiseks etc on olemas try-with-resources statement;
- - ! not all resources can be automatically closed; only resource classes that implement
- java.lang.AutoCloseable can be closed that way;
- - All Java exception
- classes derive from the java.lang.Exception class.
- - If you have several catch blocks and the exception type
- of one of the catch blocks is derived from the type of
- another catch block, make sure the more specific
- exception type appears first. (vastasel juhul püütakse vale catchi poolt kinni; ps!
- siia alla kuuluvad ka child klassid)
- - meetodi signatuuris võid nii kirja panna: public String minuMeetod(String s) throws NullPointerException {....
- - kui mitu errorit, siis eralda signatuuris lihtsalt komadega;
- - kui nüüd meetodi sees on vaja throwida, siis: throw new NullPointerException("lel, err");
- - method caller selle kinni püüab, siis e.toString() väljastabki 'lel, err';
- - constructor can also throw an exception;
- - saad ka enda exceptioneid teha, kui extendid java.lang.Exception klassi;
- - PS! kui võimalik, siis testi konditsiooni; try blokk on ressursinõudlik.
- -
- + Number/date formatting, parsing and manipulation
- - numbrite formattimiseks on java.text.NumberFormat klass; tolle konstruktorit otse ei kutsu,
- vaid kasutad getInstance meetodit, millel on mitmeid overload'e (java.util.Locale,
- DecimalFormat, jne)
- - kui teed sellest instantsi, siis nt .format meetod formaadib numbrid sinu lokaali;
- - samal objektil on ka parse meetodid;
- - parse meetod returnib java.lang.Number instantsi, mis on Interger, Long jt klasside
- parentiks;
- - Math:
- - palju funktsioone (sin, asin, exp, log, max, min etc söövad parameetrina double'it; prolly on overloaditud tho);
- - Date:
- - manipuleerimiseks on java.util.Calendar, aegadega töötamiseks aga java.util.Date
- - paljud Date'i meetodid on deprecated, nt getDate, getMonth... selle aseme tuleks Calendar
- klassi meetodeid kasutada;
- - date parsing ja formatting tuleb java.text.DateFormat ja java.text.SimpleDateFormat klasside läbi;
- - DateFormat on getInstace meetoditega; SimpleDateFormat on DateFormati enda implementatisoon,
- mis on lithsalt lihtsam kasutada.
- - DateFormat - supports styles and patterns;
- - DateFormat df = DateFOrmat.getDateInstance(DateFormat.MEDIUM)
- - df.format(Date objekt) -> formattib Date vastavalt df-i formaadile;
- - df.parse(String date) -> stringi formaat peab vastama loodud DateFormat objekti formaadile;
- - leniency - whether of not a strict rule is applied at parsing; for isntance, if a DateFormat
- is lenient, it will accept string 'Jan 32, 2011, although it does not exist; it'll convert it
- to Feb 1, 2011 instead; if it isn't lenient, it won't accept dates that don't exist;
- - isLenient (bool) and setLenient(bool) saab küsida ja seada, kas DateFormat objekt on lenient;
- - (fyi: leniency - quality of mercy and forgiveness);
- - SimpleDateFormat on võimekam kui DateFormat, sest format objekti loomiseks saab
- vabamalt MM dd yyy etc mustreid ette anda, mitte ei pea .SHORT, .MEDIUM et al kasutama;
- -
- + Interface ning abstract class
- - all i/f members are implicitly public;
- - implementeeriv klass peab enda signatuuris kasutama 'implements InterfceNimi'
- - sarnaselt parent-child suhtele: an instance of the class is also an instance of the i/f; seega
- if (implementeerivaKlassiObjekt instanceof Interface) // evaluates to true
- - i/f can extend another i/f;
- - subinterfaces and superinterfaces;
- - fields in an i/f must be initialized and are implicitly public, static and final; (ning uppercase ofc)
- - all methods in an i/f are implicitly public and abstract;
- - BUT: methods in i/f must not be declared static, since static methods cannot be abstract!!!!!!
- - et kõik i/f-s defineeritud meetodid peavad implementeeritud saama, siis on suuretele i/f-dele
- hea teha generic/base class, mis selle töö ära teeb. õige implementeeriv klass siis extendib seda
- ning override'ib meid huvitavad meetodid;
- - abstract classes are similar to i/f-s, but all methods don't require to be overriden;
- - abstraktse klassi ja meetodi loomiseks kasuta lihtsalt abstract keywordi, st
- public abstract class DefaultMinuKlass {....
- - abstract klassis olevad non-abstract meetodid omavad body, seega implementatsiooni;
- - abstract meetodid on aga samuti lihtsalt deklaratsioonid ning need tuleb seega override'ida;
- - implementeeriv klass on lihtsalt klass, mis pärib abstrakse klassi ning implementeerib
- seal päritavas klassis deklareeritud abstract meetodit;
- -
- - (ei tea miks, aga) you should never cast to an abstract class!;
- + Enums
- - can be part of a class or declared outside as public enum MinuEnumType { ...
- - using an enum is similar to using a class or an i/f, nt public MinuEnumType yksEnum;
- - using value in an enum is like using a class's static member;
- - erineb static final fieldidest selle poolest, et enumile saab väärtuseks määrata vaid
- enumis endas defineeritud väärtusi; ühtlasi käitub enum nagu objekt, seega saab muu
- hulgas kasutada Map key'd.
- - (in general - enumid on ohutumad kui static finals)
- - for loopiga itereerimiseks on .values() method;
- - switchimisel ei tohi case XXX prefixida enumi tüübiga; piisab vaid väärtustest.
- - klassi alla kuuluva enum fieldile väärtuse andmine: klassiInstants.enumField = MinuEnumType.ENUMVÄÄRTUS;
- -
- + Collections FW (btw, nii List kui Set .add() meetod vist returnib booleani)
- - collection is an object that groups other objects. analoogne on generics, mida
- käsitleb järgmine teema.
- - kui millestki on unsychronized ja synchronized implementatsioon olemas, tuleks valida
- unsynchronized, kuna perform tollele parem; synchronized implementatsiooni kasutamist
- kaaluda vaid multi-threaded environmentide puhul;
- - aga multi-threaded envis saab ka ise synchronize'ida.
- - List is the most popular subinterface of Collection, and ArrayList is most popular
- implementation of List.(sarnaseks Listi implementatsiooniks on ka Vector, kuid
- see on synchronized, seega aeglasem)
- - üldiselt lood: List myList = new ArrayList();
- - for loopiga itereerimiseks: for (Object object : myList) {...
- - palju meetodeid... remove, add, set, indexOf, lastIndexOf...
- - Arrays klassil on asList meetod, mis lubab mitu elemeti korraga List'i lisada
- - Collection objekti itereerimiseks on kas Iterator või lihtsalt for loop;
- - Collection extendib Iterable, milles on iterator meetod; see meetod returnib
- java.util.Iterator, mida kasutades saab Collectioni objekti itereerida;
- - Iterator i/f omab meetodeid nagu hasNext, next, remove et al. nende meetodite
- aluseks on Iteratoris olev internal pointer, mis järgmise elemendile
- pointib.
- - põmst kui for'iga itereerid, siis kompileerija tasandil tõlgitakse see ikkagi
- List-ist tulevaks iterator objektis, millel rakendatakse for loopis
- .hasNext() meetodit for'i expressionis, lihtsal kujul olekski
- for (Object object : myList) {.... kuna Collection extendib Iterable'it.
- - List lubab lisada NULL väärtust, Set mitte.
- - set represents a mathematical set; unlike List, Set doesn't allow duplicates nor
- null values;
- - ! siiski! some implementations of Set allow at most one null element, e.g.
- HashSet
- - setidest tulekski eelistada HashSeti, sest see on kiirem kui Set, TreeSet ja LinkedHashSet;
- - Queue extens Collection by adding methods that support the ordering of elemetns
- in a FIFO basis;
- - Queuel hulka meetodeid, nagu add, offer, remove, poll, element, peek,,,
- - java.util.Stack behaves in a last-in-first-out (LIFO) manner;
- - Collectioni implementatsioonidel on tavaliselt ka konstruktorid, mis collection
- conversionit toetavad, nt public ArrayList(Collection c)
- - Map hold key to value mappings (dictionary vist)
- - cannot be duplicate keys;
- - adding pairs through .put method
- - .remove(key) to remove
- - .clear to remove all mappings
- - .size, isEmpty
- - value saad kätte .get(key)
- - .keyset - returns a Set containing all keys in teh Map
- - values - ...all values....
- - entrySet - returns Set containing Map.Entry objects, each representing a
- key/value pair. the Map.Entry i/f provides getKey method that returns the key
- part and the getValue which returns value;
- - several implementations of Map
- - most commonly used are HashMap and Hashtable (unsynchronized and synchronised
- accordingly);
- - Map map = new HashMap();
- map.put("1", "one");
- map.size(), map.get("1");
- Set keys = map.keySet();
- - objects are made comparable and sortable with java.lang.Comparable and
- java.util.Comparator i/f-s
- - Arrays.sort has a contract with itself and objects in a need of sorting;
- contract in a form of java.lang.Comaprable i/f;
- - objects needed to compare shall implement Comaprable;
- - (ehk compareTo() meetodi peab ise oma klassis ikkagi implementeerima)
- - kui compare on implementeeritud, siis saab ka Arrays.sort meetodit kasutada,
- mis kutsubki compareTo-d välja;
- - java.lang.String, java.util.Date, pirimitiivide wrapperklassid et al
- implementeerivad kõik java.lang.Comparable'i;
- - et sortida teiste omaduste põhjal, tuleb teha tolle klassi omaduse jaoks uus klass, mis
- implementeerib Comparator i/f-i; tolle omaduse põhjal sortimiseks tuleks siis callida:
- Arrays.sort(objektideList, new SoovitudOmaduseComparator());
- - kokkuvõte: java.util.Collection i/f-il on 3 sub-i/f-i: List, Set, Queue;
- - dictionary analoogiks on Map i/f, mille peamised implementatsioonid on HashMap
- ning Hashtable (millest esimene on kiirem, sest on unsynchronized)
- + Generics
- - generics on üsna sarnane olemuselt collections freameworkile, kuid mõne suure
- eelisega. nt oli coll frame'il see jama, et igast get/set meetodid returnisid
- Object type'i, mida pidid ise downcastima, et saada õige type; generics puhul
- seda pole
- - generic type can accept parameters; that's why it's called a parameterized type.
- - passing different lists of type vars to a generic type result in different types,
- meaning List<Object> refers to different type of object than List<String>;
- - see on probleemiks, kui meetod ootab vaid ühte tüüpi Listi; lahenduseks
- '?' wildcard: public static void minuMeetod(List<?> var) { }
- - analoogne probleem tekib, kui on vaja määrata aktsepteeritavate tüüpide piire;
- selle jaoks on upper bound definition:
- List<? extends Number> - sööb kõiki tüüpe, mis on Numberi subclassid
- (Number type ise kaasa arvatud loomulikult)
- ehk GenericType<? extends upperBoundType>
- - küll vähekasutatav, kuid saab ka lower classi defienerida super keywordiga:
- List<? super Integer>
- - legend of type variables:
- - E = type variable, st vairable that will be replaced by a type;
- used extensively by teh Collections framework);
- - K = map keys
- - V = map values
- - e.g. public interface Map<K, V>
- - T = type;
- - N = number
- - S,U,V etc - 2nd, 3rd, 4th types
- - generic type'ide kirjutamine on analoogne tavaliste type'ide loomisele:
- public class MinuGeneric<T> {.....
- - By convention, a type variable name consists of
- a single uppercase letter. (antud näites T siis)
- - A generic type used without parameters is called a raw
- type. see on backward compatibility jaoks; listist pullides on siis vaja down-
- castida.
- + IO
- - java.nio.file.Files on sobilik vaid väikeste failidega töötamiseks; suuremamahuliste
- failide jaoks on vaja juba streame kasutada (nt InputStream, OutputStream, Reader,
- Writer)
- - java.io.File on deprecated; java.nio.file.Path interface vahetas välja.
- - meetoditeks nt .getName(indx), getParent, getFileName, getRoot
- - Path klassiga füüsiliselt midagi ei loo; selleks on vaja Files klassi;
- - java.nio.file.Files
- - createFile(),
- - delete(Path path) -nii symlinkidele, failidele, diridele... dir peab olema tühi;
- deleteIfExists(Path filepath); endiselt - kui dir pole tühi, siis saad
- DirectoryNotEmptyException'i
- - et diris olevate elementide üle itereerida, on olemas Files klassi kuuluv
- newDirectoryStream() meetod;
- directorysteram returned must be closed after use. (miks ei tea???)
- - copying:
- copy; CopyOption (java.nio.file interface); StandartCopyOption enum on CopyOptioni
- üheks implementatsiooniks.
- - move()
- - reading-writing:
- readAllBytes(), readAllLines...
- write() on overloaditud nii stringide kui byte'ide jaoks; lisaks Pathile saab
- kaasa anda optional OpenOption ja Charseti overloadi; OpenOptioniks annad kaasa
- enum'i, nagu nt APPEND, CREATE, READ, SYNC, WRITE et al;
- - io streams
- (peamiselt kasut. Files.newinputStream & newOutputStream)
- - söödava data sortsu kutsutakse sink-iks; võib olla nt file, ntw socket või mem;
- - nagu write ja readAllLines puhul, on ka streamil omad abstract klassid nii
- characteride töötlemiseks (Reader ja Writer) kui ka binary data töötlemiseks
- (InputStream, OutputStream);
- - streamid teeb eriti heaks see, et source/dest pole oluline(kas fail v ntw näiteks);
- et konkreetsesse sinki ühenduda, siis pead lihtsalt vastava implementatsiooni-
- klassi ehitama;
- - output:
- - sarnaselt InputStreamile 3 overload meetodit: write(int b), write(byte[] data),
- write(byte[] data, int offset, int length)
- - on ka close ja flush meetodid; viimane forces any buffered content to be written
- out to the sink.
- - characterite kirjutamiseks on Writer abstract class.
- - Writer klass: sarnane OutputSreamile, aga tegeleb byte'ide asemel charidega;
- samuti 3 metod overloadi, write(int b), write(char[] text), write(char[] text,
- int offset, int length)
- - stringe aktsepteerivad write(String text), write(String text, int offset, int len);
- - kui õigesti mõistan, siis charide kirjutamiseks ongi esmalt vaja luua OutputStream
- (OutputStream os = Files.newOutputStream(path, openOption);
- ja seejärel OutputStreamWriter:
- OutputStreamWriter writer = new OutputStreamWriter(os, charset);
- - OutputStreamist on parem PrintWriter, sest tollel on method overloadid, mis
- võimaldavad suva java primitiive ja objekte otse faili kirjutada;
- - (ehk sitaks print ja println overloade sõltuvalt parameetri tüübist)
- - kuna PrintWriterit ei saa BufferedWriterisse wrappida, tuleks hoopis
- wrappida Writer, mis on PrintWriteri argumendiks;
- - (ehk kui õigesti mõistan, siis Writeri wrapid BufferedWriteri sisse, ning
- selle Writeri instantsi annad PrintWriteri loomisel argumendiks);
- - to read chars, you use Reader class;
- - logimiseks on hea PrintStream klass (lolei, Apache log4j on teh shite logimiseks);
- - System objekt lubab default PrintStreami asendada setOut meetodiga (System.out
- on a type of java.io.PrintStream, seega saad selle out'i mingi enda PrintSreamiga
- asendada, nt logid otse faili)
- - streamid on siis head, kui on vaja faili datat järjest kasutada (hence stream, st
- data jooksebki sisse/välja streamina) või nt network socketiga töötada; kui on aga
- tarvis muuta nt 1000ndat bitti igast failist, on mõistlikum kasutada
- java.nio.channels.SeekableByteChannel interface'i (enne jdk7-t kasutati
- java.io.RandomAccessFile klassi, kuid nüüdkseks on see deprecated);
- - SeekableByteChannel teostab nii readi kui write'i
- - SBC-ga lugemiseks või kirjutamiseks on lihtsalt vastavalt read() ja write()
- meetodid, mis võtavad parameetriks java.nio.ByteBuffer. = java.nio.Buffer
- üheks alamklassiks; nagu nimi ütleb, bufferdab byte'e.
- - ByteBuffer omab mitmeid put ja get meetodeid (eri datatüüpidele, offset, length
- jms võimalsued)
- - loomiseks kasuta .allocate meetodit (ByteBuffer bf = ByteBuffer.allocate(12);
- -
- - objekti state'i saab salvestata object serializationi läbi; selleks on nt
- ObjectOutputStream. konkreetse state'i retrieve'imiseks nimetatakse deserializationit,
- mida saavutatakse ObjectInputStreami läbi;
- - et objekt oleks serialiseeritav, peab ta implementeerima java.io.Serializable
- interface'i;
- - serialization is based on last in first out (LIFO);
- -
- - Nested & inner classes:
- - 2 types of nested classes: static inner classes and non-static nested casses;
- - non-static nested classes are called inner classes;
- - (static nested klasse saad luua ilma top-level klassi instantsieerides,
- kasutades OuterClassName.InnerClassName formaati;
- inner classi puhul saad initsieerida inner classi vaid läbi välimise klassi
- instantsi);
- - to top-lvl class, a nested class is just like other class members, e.g. methods
- and fields; nested class can have one of the four access modifiers, whereas a
- top lvl class can only have eithter public or default (vist package?);
- - inner classi instantsi saab luua läbi toplevel klassi instantsi kaudu:
- TopLevel toplvl = new TopLevel();
- TopLevel.Inner inner = toplvl.new Inner();
- - local inner class (or local class for short) = inner class that by definition is NOT
- a member class of any other class (sest declaration ei ole otse outer classi deklaratsioonis)
- - LC on defineeritav igasuguses code blockis ning tolle skoop langebki puhtalt
- sinna blocki (think if, while blocks etcetc);
- - LC on nt siis mõistlik, kui implementeerib mingit i/f-i ning seda implementatsiooni
- ei kasutata mujal kui konkreetses meetodis (kus LC on defineeritud);
- - Not only does a local class
- have access to the members of its outer class, it also has
- access to the local variables. However, you can only
- access final local variables. The compiler will generate a
- compile error if you try to access a local variable that is not
- final.
- - anonymous inner class:
- - enamasti i/f-ide implementeerimiseks; neil pole oma nime. nt on selline i/f
- nagu Printable; kuskil mujal klassis implementeerid seda anon klassiga:
- Printable minuPritner = new Printable () { implemeneerid ,};
- - pane tähele, et closing brace'i lõpus on semikoolon!; also, põmst toimib
- magic läbi 'new' keywordi;
- - anon inner klassi saab luua ka extendides abstract või concrete klassi;
- + swing & AWT
- - awt kasutab OSi native apit, et joonistada GUId, swing aga teeb kõike ise;
- java.awt core'iks on Component class;
- - Swing kasutab siiski AWT event modelit;
- - all swing components except JFrame, JDialog and JApplet reside in containers;
- JDialog is like a JFrame, but normally resides within a JFrame or another JDialog;
- - swingi komponentide eristamiseks AWT omadest prefixitakse need J-ga;
- -
- - (swingis palju asju... loe dokist lol)
- - default layout on BorderLayout (see N-S-W-E-center)
- -
- + java event model;
- - event is encapsulated in an envent object; there are 3 participants:
- - event source, which is the object whose state changes;
- - event object, ehich encapsulates state changes in the event source;
- - event listener, which is the object that wants to be notified of state changes in
- the event source;
- - ehk: when event occurs, the event source generates an event object and
- sends it to the event listener;
- + Polymorphism
- - A a = new b B;
- - a on complile ajal type A, aga runtime'il type B!
- - JVM otsustab runtime'il millist meetodit kasutada, ehk method calli ning
- method blocki bindimine toimub runtime'il, mitte compiletime'il; seda
- nimetatakse late bindinguks;
- - polym doesn't work with static and final methods (sest static methods are early-
- bound ning final meetodeid ei saa extendida);
- + Annotations (need @Deprecated, @AnnotationType(elementValuePairs) et al;
- - annotation type is a special interface type;
- - annotation is an instance of an annotation type;
- - they're in form of key-value pairs;
- - annotation types w/ no key/value pairs are called marker annotations;
- - annotation w/ one pair are ofter referred to single-value annotation types;
- - common annotations - mingi standardi järgi defineeritud annotatsioonid, nagu
- Generated.
- - meta-annotations - annotations that annotate annotations:
- - Documented
- - Javadoci vms kasutades dokumenteeritakse @Documented annotatsiooniga
- annoteeritud annotatsioonid (nt @Drprecated dokumenteeritakse seetõttu);
- - Inherited
- - sellega annoteeritud klassi sub-klassid pärivad parenti annotatsioonid;
- - Retention
- - näitab kaua @Retention-iga annoteeritud annotatsioone tuleks alles hoida;
- value'ks 1 kolmest enumist: SOURCE, CLASS, RUNTIME
- - Target
- - defineerib millised programmi element/did võivad saada annoteeritud selle
- metaga annoteeritud annotatsioonide instantside poolt;
- sellel samuti mitu enumi väärtusteks (raamatus lk 577);
- - enda annotatsiooni defineerimine on täpselt nagu interface'igi, ainult et @ märk
- on ees: public @interface MinuAnnotation { ... }
- -
- + i19n and l10n
- - internationalizationi võtmeks on java.util.ResourceBundle class (abstract), mis võimaldab
- lihtsalt lugeda locale'i spetsiifilist properties faili; sisaldab endas getBundle
- staatilist meetodit mis returnib konkreetse subclassi instantsi;
- - sellisel juhul on properties faili nimeks:
- basename_langCode_countryCode (basename on ResourceBundle enda base name)
- nt: MyResources_en_US.properties
- - kui vajalikku prop faili ei leita, fallbackitakse default prop failile, milleks
- on basename.properties;
- - value lugemiseks on getString meetod; passitakse key;
- - (ühesõnaga - ResourceBundle lubab mugavamalt failides sisalduvaid key-value
- pairidele ligi pääseda)
- + Applets
- - Applet klass on .Panel subclass...
- kuna on Panel, siis saab AWT komponente lisada.; siingi on JApplet olemas;
- - Appletil on omajagu funktsioone, nagu init, start, stop, destory, isActive, paint,
- showStatus, getParameter, getCodebase, getDocumentBase, getAudioClip, play,
- getImage, getAppletContext etc;
- - AppletContext i/f
- - AppletContext is created by the web browser (or applet viewer for that matter);
- - enamus siinseid meetodeid on duplikeeritud Appletis, v.a. showDocument meetodid,
- millega lihtsalt kuvatakse teisi URLide dokumente, kui see, millel Applet ise
- asub;
- - AppletStub i/f
- - when browser creates an applet, it also creates an AppleStub object that it passes
- to the applet by calling the setStub method on the Applet object; this stub
- acts as an i/f between an applet and the browser env or applet viewer env;
- !kui just ise applet viewerit ei loo, siis see meid ei huvita!
- - appletile söödad parameetreid param tagiga html-is, nt
- <param name="customer" value="Jane Goddall"/>
- - väärtusi küsid getParameter meetodiga;
- + Networking
- - application layer protocols (HTTP, FTP, telnet et al) use the protocols in the
- transport layer (e.g. TCP and UDP); transport layeri protocolid omakorda utiliseerivad
- neist allpool olevaid protokolle (IP);
- - HTTP - request-response protocol;
- - request consists of 3 components:
- - method -- uniform resource identifier (URI) -- protocol/version, e.g.
- POST /examples/default.jsp HTTP/1.1
- - request headers
- - contains info about client env and the body of the entity, i.e. browser
- lang, lenght of the entity body etc;
- - each header is separated by a carriage return/linefeed (CRLF) sequence;
- - between headers and the entity body there's a blank line (CRLF), which
- tells the HTTP server where the entity body begins;
- - entity body
- - response contains also 3 parts:
- - protocol -- status code -- description
- - response headers
- - entity body
- - üldine põhimõte sama mis requestigagi; body on mõistagi HTML content;
- - java.net.URLConnection
- - represents a connection to a remote machine;
- - URLC class doesn't have a public constructor, so you can't construct a URLC
- with the 'new' keyword;
- - to obtain an instance, call the openConnection method on an URL oject;
- -
- - by default, on enabletud read, aga mitte write; selle jaoks on URLconnectionil
- 2 booleani: DoInput ja doOutput; et kirjutada, tuleb latter trueks seada:
- connection.setDoOutput(true);
- - aga! kuigi sellega saab postida message'eid, siis tavalisetlt seda
- selleks otstarbeks ei kasutata; selle jaoks on olemas hoopis
- java.net.Socket ning java.net.ServerSocket;
- - java.net.Socket (btw, Socket on vaid kliendipoolne)
- - socket is an endpoint of a network connection; socket võimaldab networki IO-d;
- - et saata bytestreami, tuleb esmalt callida Socketi getOutputStream meetod et
- obtainida java.io.OutputStream object; et saata texti, tahad pigem constructida
- java.io.PrintWriter objecti (OutputStream objekti kaudu ofc);
- - btw - socketi konstruktoris tahab hosti saada mingil põhjusel ilma protokollita;
- - java.net.ServerSocket
- - sama mis Socket (idee tasandil), kuid serveri poolne;
- - kui ServerSocket saab connection requesti, loob Socket instantsi et suhelda
- kliendiga;
- - the IP addy the server socket is listening on is referred to as the binding
- address;
- - another important property of a server socket is its backlog, which is the
- maximum queue length of incoming connection requests before the server socket
- starts to refuse the incoming requests;
- - SS paned requesti kuulama accept meetodiga; requesti püüdmisel returnib
- Socket objekti, mille kaudu siis IO-d teostatakse; SS vist ongi pelgalt
- kuulamiseks?
- - e: jah, SS on kuulamiseks: Socket clientSocket = ServerSpcket.accept();
- -
- + DB
- - JDBC;
- - basically 4 types of JDBC drivers (type 1 to 4);
- - DB access has 4 steps:
- - loading the JDBC driver of the db to connect to;
- - obtaining a db conntection;
- - creating a java.sql.Statement instance that represents an SQL statement;
- - optionally reating a java.sql.Result to store data returned from the db;
- - closing JDBC objects to free resources; thanks to try-with-resources,
- no need to do this manually;
- - java.sql.Connection i/f is template for connection objects; obtained by
- java.sql.DriverManager's getConnection static method; parameetriteks enamasti
- kas url(stringina) või siis url, username passwd;
- - Connection objektist tehakse Statement või PreparedStatement (viimane on precompiled);
- Statement stat = connectionObject.createStatement();
- PreparedStatement pstat = connection.prepareStatement(String sql);
- mõlemaid kasutad executeQuery nin executeUpdate (erinevad signatuurid PS ning S
- puhul, kuna viimase puhul ei pea päringut kaasa andma, kuna on juba precompiled);
- - queryst tulnud tabelit esitab ResultSet;
- - itereerid seda next meetodiga, mis returning true v false olenevalt kas on
- järmine rida olemas või mitte;
- - data grepimiseks sitaks getXXX meetodeid, nagu geInt, getLong, getShort etc;
- - getXXX meetoditel tavaliselt 2 overload'i: int ja columnname;
- - closing:
- - resultSet.close();
- - statement.close();
- - connection.close();
- - korrektne on aga sulgeda finally klauslis (if (resultSet != null)... etc);
- - java7-st alates aga try-with-resources:
- - try (Connection con = getConnection();
- Prepared pstat = connection.preparedStatement(sql);
- ResultSet rset = pstat.executeQuery()) {
- while (result.next()) {
- // data mainpulation
- }
- }catch (SQLException e) { .....
- - et saada metadatat (nr of columns in ResultSet, name on type of each column etc),
- siis kutsud ResultSet-ile getMetaData meetodi;
- - saadava ResultSetMetaData objektil mitu meetodit, nagu
- getColumnCount, getColumnName, getColumnType...
- -
- + Thurds
- - thread is the smallest unit that can take processor time;
- - T is sometimes called a lightweight process or an execution context;
- - every java program has at least one thread; the thread that executes when you invoke
- the static main method;
- - Swing for instance has a thread for processing events in addition to the main thrd;
- - threadi loomiseks 2 meetodit;
- - extendi java.lang.Thread klassi; (enamasti tegelt Thread klassiga otse ei
- tegeleta);
- - (sellisel juhul override'itakse run() meetod, mida jooksutatakse, kui
- Thread objektile jooksutatakse start() meetod;)
- - implementeeri java.lang.Runnable i/f-i;
- - (siin on run meetod, mida tuleb implementeerida);
- - btw, Thread ise implementeeribki Runnable i/f-i;
- - Runnable kasutamiseks lihtsalt implementeerid Runnabe'i run() meetodit;
- main() meetodis lood uue instantsi endast, ning passid selle Thread-ile:
- Thread minuThurd = new Thread(minuRunnableImplementeerivObjekt);
- - threadil võib olla nimi; lisaks on tal state, mis saab olla 1 kuuest:
- - new (has not been started);
- - runnable (thread is executing);
- - blocked (thread is waiting for a lock to access an object);
- - waiting (waiting indefinitely for other thread to perform an action);
- - timed_waiting (sama mis eelmine, aga ootab kindla aja);
- - terminated (thurd has exited);
- - state'id on ...Thread.State enum'is encapsulated;
- - thread priority
- - teistele threadidele tekitatakse CPU aega sleep() välja kutsumisega;
- - vabanenud ressursi jagamist otsustatakse prioriteetide põhjal;
- - prio setimiseks on setPriority(int) meetod;
- - kõrgem int tähedab kõrgemat priot;
- - kui mitu threadi kasutavad samu ressursse, võib tekkida thread interference;
- et seda ei oleks, tuleb kasutada locke; selle jaoks on 'synchronized' modifier;
- (jällegi - see pole kõige parem meetod; nii threadide loomiseks-kasutamsieks kui
- ka mitme threadi manageerimiseks on parem Concurrency Utilities);
- - igal objektil on selline asi nagu intrinsic lock;
- - a synchronized modifier can be used to lock an object; the intrinsic lock is
- released when the method, holding the synchronized modifier, returns;
- - üldiselt kasutatakse non-static meetoditel, kuid on võimalik rakendada ka
- staatilistel meetoditel, mis juhul kasutatakse Class objekti lukku, mis on
- associated kutsutava meetodi klassiga;
- - the code segmets that guarantee only one thread at a time has access to a shared
- resource are acalled critical sections; in java critical sections are achieved
- using the synchronized keyword;
- - eelnev kirjeldab method synchronizationit, kuid on olemas ka block synchronization,
- mis lukustab terve koodibloki:
- synchronized(objekt) {
- // tee midagi kuniks see objekt on kinni
- }
- - sisuliselt on tegu ikkagi sama asjaga, sest
- syncronized(this) { }
- st: Synchronizing on the method is functionally equivalent to having a
- synchronized (this) block around the body of the method.
- - kui on palju lühikese elueaga thrade, on targem kasutada thread poole; ise leiutamise
- asemel kasuta pigem util.concurrent pakki, which includes mutexes, semaphores,
- collection classes like queues and hash tables that perform well under concurrent
- access and several work queue implementations;
- - poolide ohud: deadlock, resource thrasing and complexities of wait() and
- notify();
- - fyi: üks IBM'i artikkel thurd poolidest: http://www.ibm.com/developerworks/library/j-jtp0730/
- + Visibility
- - syncida tuleb ka siis, kui pole tegemist non-atomic operatsioonidega, sest multi-
- thurd programmides ei pruugi thread teise poolt teostatud operatsioondie tagajärgi
- näha (vari väärutse muutmine nt); see tuleneb java memory mudelist;
- - seda probleemi saab samuti synchronized asjaga parandada; kui on nt mingi var,
- mida üks thread loeb, teine muudab, siis lood lihtsalt 2 getter-setter meetodit,
- kumbki synchronized;
- - syncing nõuab aga overheadi, mistõttu kui mutual exclusion pole vajalik (vaid
- kõigest visibility), tuleks kasutada hoopis volatile keywordi;
- - volatile keywordi kasutad variable'i definitsioonil !!!
- -
- - thurdide coordinationi jaoks on mitmeid Object klassi meetodeid:
- - wait() - thread waits until another thread invokes notify or notifyAll method;
- - peab alati wait loopis asuma; põmst annab monitori ownershipi ära ning
- jääb teise threadi poolt callitavat notify() või notifyAll() ootama;
- - wait(long timeout) - sama mis eelmine, aga ootab kuni teine thurd saadab
- notify(All) VÕI timeout aeg on möödunud;
- - notify() - notifies a single thread that is waiting on this object's lock;
- kui on mitu thurdi ootamas, siis üks valitakse, kes saab teavitatud, ning
- see avlik on arbitraarne;
- - notifyAll() - kõiki ootavaid thurde teavitatakse;
- -
- + Timers
- - java.util.Timer provides alternative approach to performing scheduled or recurring
- tasks; first create a Timer, call its schedule() method, passing a
- java.util.TimerTask object. The latter contains code that needs to be executed by
- the Timer;
- - TimerTask class omab run meetodit, mis tuleb override'ida; erinevalt Runnable
- run() meetodist, ei pea seda override'i loopi enclose'ima;
- - Swingil on oma timerklass: javax.swing.Timer (swingi jaoks parem, muidu veits
- vähem võimekam);
- + Concurrency utils
- - parem/lihtsam kasutus thread and sychronization feature'ite kasutamiseks;
- - siin igast ägedad type'id (atomic package'is), nagu AtomicInteger, AtomicLong et al;
- nendega opereerimiseks meetodid nagu incrementAndGet, getAndIncrement jne;
- - kui võimalik, ära kasuta Threadi et exeda Runnable'i taski; mõislikum on kasutada
- java.util.concurrent.Executor või subinterface ExecutorService'it;
- - void execute(java.lang.Runnable task)
- - harva kui on tarvis endal implementeerida Executor v ExecutorService'it;
- pigem kasuta Executors klassis defineeritud staatilisi meetodeid: (kõik returnivad
- ExecutorService'i)
- - newSingleThreadExecutor()
- - newCacheThreadPool()
- - see loob ise rohkem threade, kui rohkem taske submittitakse;
- - newFixedThreadPool(int numOfThreads)
- - Runnable taske söödad Executorile ette nii:(kui lühike task, siis defineerigi
- anonüümselt nagu siin; kui aga pikem või vajab inputi, siis tee eraldi klass):
- Executor executor = Executors.newSingleThreadExecutor();
- executor.execute(new Runnable() {
- @Override
- public void run() {
- // do something
- }
- });
- - Callable is a task that returns a value (and may throw an exception);
- is similar ot Runnable, except that the latter cannot return a value nor throw an
- exception;
- - Callable defines a method, call:
- - V call() throws java.lang.Exception
- - põmst enda class lihtsalt implementeerib Callable'i, kus sees on call() override,
- mis returnib väärtust;
- - Callable (i/f) can be passed to an ExecutorService's submit method:
- - (ehk praktikas söödad ExecutorService instansi submit meetodile
- Callable i/f-i implementeeriva klassi intantsi ette)
- - Future<V> result = executorService.submit(callable);
- - the submit() mehtod returns a Future, which can be used to cancel the task or
- retrieve the return value of the Callable; to cancel a task, call the cancel
- method on the Future object:
- boolean cancel(boolean myInterruptIfRunning)
- (passing false allows an in-progress task to complete undistrubed; true
- cancels immediately);
- - to get a result from Callable, call get() method of corresponding Future:
- V get()
- blocks until task is complete;
- V get(long timeout, TimeUnit unit)
- waits until a specified time lapses;
- - to find if task has been cancelled or complete, call Future's isCancelled or
- isDone method;
- - lõpetamisel tuleb ExecutorService lõpetada: executorService.shutdownNow();
- + Swing Worker
- - javax.swing.SwingWorker abstract class is an utility class that helps you with
- time-consuming tasks in a Swing application; after you instantiate a subclass of
- SW, you can call its execute() method to start the worker. Calling execute in turn
- invokes the doInBackground method on a different thread; you should write your
- code in this method;
- - point selles, et swingis muidu käitab GUI-d ning eventhandlereid 1 thread;
- kui mingi event võtaks sitaks aega, muutuks GUI unresponsive'iks;
- - intermediate datat saab publishida publish() meetodiga; iga kord kui seda meetodit
- callitakse, invoke'ib SW process() meeotdi;
- - on ka done() ja cancel() meetodid;
- - (põmst siin ongi oluline publish meetodi kasutamine, process() meetodi overridemine;
- ei saa sellest päris täpselt aru; publishi parameetriks tulebki vist list... panna?
- ning processil argumentideks mingi... teadmata arv elemente vastu võtta? (stiilis
- process(Integer... chunks) { ... } ? dunno lol
- + Lock i/f pakub meetodeid synchronized limitatsioonidele (nagu nt see, et ressurssi
- ei saa vabastada muust meetodist, kui sellest mis lukustas; limiteeritud vaid
- meetoditele ning blokkidele;)
- - Lock tuleb nii lock kui unlock meetoditega;
- - hea tava on unlock'i kutsuda finally klauslis;
- - on veel tryLock(), tryLock(long time, TimeUnit timeUnit)
- (returns true, if lock available; kui false, siis ei blocki!);
- + Security
- - et java application oleks ohutu(m), tuleb teda jooksutada security manageriga;
- - the way to tell the SM what permissions are allowed is by passing a policy file;
- - To run a Java application with the security manager, invoke
- the java program with a −D flag.
- java -Djava.security.manager MyClass arguments
- - Here is the syntax for passing a policy file to the java tool.
- java -Djava.security.manager -Djava.security.policy=policyFile MyClass arguments
- - if no policy file is specified then default is used (mingi system security properties
- file - java.security);
- - policy failis on grant ning keystore entried;
- - grant - entry includes one or more permission entries, preceded by optional codeBase,
- signedBy and principal name-value paris.
- - principal value specifies a className/principalName pair which must be
- present within the executing threads principal set [wut lol ???];
- - grant entry consists of one or more permission entry;
- - permission entry syntax: permission permissionClassName target action
- - policyt saad defineerida kas lihtsalt txt failis või policy tooliga;
- - appletitele lisaõigusi saamiseks tuleb signida (JarSigner Tool)
- -
- - SSL certificate contains the following:
- - a public key;
- - information about the subject, ie. the owner of the public key;
- - the certificate issuer's name;
- - some timestamp to make the certificate expire after a certain period of time;
- - et kontrollida kas dokument on originaalsel kujul:
- - decrypt the digest accompanying the doc using the signer's public key;
- - create a digest of the doc;
- - compare them (they need to match);
- - FYI: digest takes a plain text and generates a hashcode which can be
- used to verify if the plain text is unmodified but wich CANNOT be used
- to decrypt the original text form the hash value
- (ehk siis lihtsalt hash/checksum)
- - To apply for a certificate, Bob
- has to generate a pair of keys and send his public key to a
- certificate issuer, who would later authenticate Bob by
- asking him to send a copy of his passport or other types of
- identification. Having verified Bob, a certificate issuer will
- sign the certificate using its private key. By ‘signing’ it
- means encrypting. Therefore, the certificate can only be
- read by using the certificate issuer's public key.
- - nüüd jagab Bob public key asemel sertifikaati;
- - saadud certe on samuti mõistlik hoida keystore'is
- keytool -importcert -alias minuAlias -file certMidaImpordin.cer
- -
- + java web applications
- - põmst on Servlet i/f contractiks servleti ning containeri vahel;
- - there are 3 official technologies for web dev:
- - servlet (core tech, millele teised toetuvad)
- - javaserver pgaes (JSP)
- - javaServer Faces (JSF)
- - a servlet application runs inside a servlet container, aka servlet engine;
- - a servlet/JSP (need käivad koos) container is a special web server that can process
- servlets as well as serve static contents;
- - Apache Tomcat and Jetty are the most popular servlet/JSP containers that are free
- and open-source.
- - Servlet and JSP are of Java EE tehcs (nagu on ka JMS, Enterprise JavaBeans (EJB),
- JSF, Java persistence..);
- - java EE appi jooksutamiseks on tarvis Java EE containerit, aga piisab ka
- servlet/JSP containerist;
- - (nt Tomcat ongi servlet containeriks);
- -
- - all servlets must implement javax.servlet.Servlet;
- - init, service & destroy are life cycle methods;
- - init: container invoke'ib first time the servlet is requested (hiljem mitte);
- - service: iga kord kui servlet on requestitud;
- - destroy: siis kui application is unloaded or container is being shut down;
- cleanup code läheb siia;
- - thread safety! container creates an instance of a servlet which is shared among
- all users, so class-level vars are not recommended, unless they are read-only
- or atomic vars;
- - nagu tavaks, pole ka siinkohal vist kõige mõistlikum Servlet-it ennast otse
- implementeerida; lihtsam on extendida nt GenericServlet'it või HttpServlet-it;
- -
- - failid asuvad kindlas dir-struktuuris (WEB-INF->classes/lib)
- - muud ressursid (pildid, HTMLs) organiseerid application diri (mis asub classes
- all);
- - deployimiseks paar võimalust:
- - kõige lebom on applicationi dir kogu pasaga kopeerida webapps diri Tomcati
- installatsioonis;
- - alternatiivina võib deployida ka .war failina (mis on sama mis jar, aga war
- extensioniga lol);
- - pärast loomist kopeeri war webapps diri, restarti Tomcat, ning ta pakib
- war-i automaatselt lahti;
- - veel on võimalus editida server.xml faili Tomcati conf/ diris või deployida
- spetsjomm XML fail;
- - invoke'imiseks: http:/localhost:8080/projekt/url-mis-sai-annotatsioonis-nimetatud
- - iga HTTP requesti jaoks loob servlet container ServletRequesti instantsi, mis
- encapsulate'ib requesti info ning passib selle servleti service meetodile;
- - ServletRequestil mitmeid meetodeid, millest kasutatavaim ehk getParameter
- (lisaks getParameterNames, getParameterMap, getParameterValues);
- - service meetodile antakse kaasa ka ServletResponse, mis peidab ära browserile
- vastuse saatmise keerukuse;
- - ServletResponse'i oulisim meetod on getWriter method, mis returnib
- java.io.PrintWriter objekti;
- - üldiselt vastad HTML-ina; enne HTML tagide saatmist oleks hea kutsuda
- setContentTYpe, passides "text/html" argumendina; (mõned browserid võivad ilma
- content type'i täpsustamata interpreteerida seda plain textina);
- - every piece of info for the ServletConfig object is called an initial parameter;
- initial param has 2 components: key and value;
- initial params are passed to a servlet by using an attribute @WebServlet or by
- declaring it in a configuration file called the deployment descriptor;
- - to retrieve initial param from within servlet, call getInitParameter on the
- ServletConfig; või getInitParameterNames (returnib stringi asemel
- enumerationi);
- - getServletContext - returnibki ServletContexti
- - represents servlet application; there's only one context per web application;
- - kui on distributed env ning sama app on deployitud mitmel konteineril, siis
- on üks ServletContext per JVM;
- - asja point on jagada common infot ressursside vahel applicationis ning
- to enable dynamic registartion of web objects (done by sorting objects
- in an internal Map within ServletContext); objects stored in SC are
- called attributes, and objects stored here can be accessed by any servlets
- in the application.
- - otse Servlet-it implementeerimise asemel on mõistlikum extendida GenericServlet
- abstract klassi, mis:
- - assignib ServletConfig objekti class lvl variks, mille saab getServletConfig
- - provideb default implemetnatsioonid Servleti i/f meetoditele;
- - overridida tuleb no-arg init() (kui on vaja sinna midagi üldse lisada, sest
- ServletConfig nagunii talletatakse ju class-lvl vari);
- -
- + HTTP servlets
- - enamasti töötad just nendega lol;
- - HTTP servlet class overrides GenericServlet (seega peaks abstract class olema)
- - service meetodide asemel override'id doGet() ja/või doPost() meetodeid (veel on
- 5 meetodit, mida kasutab harvem);
- - ServletRequest ja -Response'i asemel töötab HttpServletReq ja resp-iga;
- - ühe asjana on deploymenti juures tarvis mappida servlet pathiga; enne teostasime
- seda WebServlet annotation type'iga; teine võimalus on kasutada deployment des-
- criptorit;
- - the descriptor must be named web.xml and saved in the WEB-INF dir of the
- application;
- - deployment descriptor allows to override values specified in a servlet annotation;
- + JavaServer Pages (JSP)
- - servletitega see jama: HTTP vastus HTML-i näol on Stringidena; teiseks - HTML
- tagid on hardcoded;
- - JSP päästab; btw, jsp ei asenda Servleti, vaid lisab väärtust. Java web appid
- kasutavadki korraga nii servleteid kui ka JSP-d;
- - JSP page is essentially a servlet;
- - JSP pages are basically text files w/ jsp extension;
- - JSP pages run on a JSP container; a servlet container is normally aslo a JSP cont;
- - kui JSP page is requested, then container does 2 things:
- - translate JPS page into a JSP page inplementation class, which must implement
- the Servlet i/f (result is dependent on the JSP container);
- - if successful, JPS container compiles the implemetnation class and then loads
- and instantiate it and perform the normal lifecycle operations it does
- for a servlet;
- - kui tuleb uus JSP req ning JSP page pole modifitseeritud, siis ei toimu recompilationi;
- - et algest laadimisest üle olla, confi application nii et kõiki JSP page'e callitakse
- kohe alguses, või precompile'i JSP page'id ning deploy them as servlets;
- - JSP page contains template and syntactic elements;
- - nt <% ning %> on elemendid, sest tähistavad Java code blocki algust ja lõppu;
- - JSP ei pea registreeritud olema deployment descriptoris;
- - .jsp failid lihtsalt projekti kausta (samas kus asub ka WEB-INF dir);
- - .jsp failide lisamisel pole tarvis tomcati resada;
- - kui servletis olid init, service, destroy, siis JSP-s:
- - jspInit - sarnane init-ile; (see aga ei võta argumenti);
- - jspDestroy
- - jooksutatakse vist siis kui container (eg Tomcat) maha tapetakse?
- - meetodi definitsioon: <%! ning %>
- - Implicit Objects:
- - Servlet-is saad service meetodiga HttpServletReq ja Resp objektid, samuti ka
- ServerConfig ning ServletContext ning HttpSession objektid (viimase getSession
- meetodiga); JSP-s saad neid objkte JSP implicit objektiga; nt request implicit
- objekt esindab HttpServletReques objekti; seda võid kasutada justkui oleks see
- referents HttpServletRequest objktile; out on JspWriter objekti referents, mis
- on u sama mis PrintWriter mis tuleb getWriter meetodiga HttpServletResponse'i
- objektist. nt out.println("welcome to jsp page yo");
- - JSP syntax:
- - directives
- - scripting elements
- - actions
- - Directives
- syntax: <%@<directive_name> ....%>
- - instuctions for the jsp translator on how a jsp page should be translated into
- a servlet implementation class; nendeks on taglib, tag, attribute, variable
- ning 2 kõige olulisemat page and include;
- - page
- translatorile saab antud JSP kohta info anda, nt bufferi suurus, mida out
- implicit objektiga kasutada, mis content type'i kasutada, mis java type'i
- importida jne;
- - include
- to include the content of another file in the current JPS page; (JSP page
- code reuse'i jaoks vist, kui tõmbad mingit väga kasutatavat html osa nt
- sisse);
- - Scripting Elements
- to insert Java code into JSP page; 3 types of elements: scriptlets, declarations
- and expressions.
- - scriptlets
- block of java code within <% %> tags; variables defined in one block is
- visible to another below;
- - expressions
- is evaluated and its result is fed to the print method of the out implicit
- object; <%= %>
- ehk ei midagi muud, kui shortcut out-i söötmisel; btw, expressioni lõpus
- pole semikoolonit;
- - declarations
- <%! %>
- lihtsalt declare'id variable ning meetodeid mida saab JSP lehel kasutada;
- - error handling: try block toetatud; hea on teha error leht, kasutades isErrorPage
- attribute'i page direktiivis; teised lehed kasutavad seda lehte läbi errorPage
- attribute'i page direktiivis;
- + Javadoc
- - javadoc loob HTML faile mis kirjeldab kas package'it või type'i;
- - you can write doc comments for a class, an i/f, a method, constructor, and a field;
- - tags: @tag or inline tag: {@tag}
- - tage on sitaks yo
- - javadoc on põhiproge, kuid on võimalik vist eristada doclet'it mis reaalselt
- lõppfailid kokku paneb; default genereeribki javadoci outputist HTML failid;
- - javadoc generates html file for each java class;
- - Javadoc works by reading source files and generates
- document based on a doclet. The standard doclet in
- Javadoc generates HTML files.
- + Application Deployment
- - technology for Java application deployment is Java Web Start (JWS); it's a tool
- that runs on the Java Network Launching Protocol (JNLP).
- - in short, to deploy, you need to package it in a jar file and create a JNLP file
- that describes the jar file; may also include instructions for user on what to do
- to download and install the application;
- - typically you tell JWS what to do using a JNLP file:
- - if there's no JRE installed on comp, Java Web Start can download the latest ver
- of JRE and install;
- - if JRE is incorrect ver; downloaded JRE is only used to run this app and will
- not affect the old JRE;
- - if there is correct JRE, JWS will simply run the application;
- - JWS is installed as part of the JDK;(või on see typo ning tegelt JRE?)
- - JNLP file is a xml;
- - failis on lisaks igast muid tage, mis sisaldavad infot faili enda codebase'i kohta
- (url), min ver of JWS, desc of app etcetcetc;
- - lol, tuleb välja et jnlp faili loetaksegi browseriga;
- KÜSSID:
- - Integer Bitwise Operators & | ^
- - kui parentil on defieneritud 1 konstruktor, mis sööb 1 argumendi, siis
- selle parenti pärinud child failib, kui explicitly ei kutsu seda konstrukotrit välja.
- mis sellisel juhul automaatselt no-arg konstruktorit ei provide'ita?
- - mis maagia käib swingi alguses @ main method? (swingUtilities.invokeLater...
- seal mingi anonymous method?)
- - mida tähendab super(); meetodis enne teist meetodit (mitte alati vist?);
- - 24. pt jäi üsna segaseks (kuidas täpselt Callable ja Future kasutada nt;)
- - vaata Serializable üle
- - ehk serialization - wuts dat. üks artikkel sel teemal:
- http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html
- - SO-st üks seletus:
- "In other words, serializable objects can be written to streams, and hence files, object databases, anything really."
- - vaata reflection üle
- - Java reflection allows you to analyze a Java class and use the information contained in this class at runtime.
- - 13, punkt @ http://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html
- - miks on seal eraldi veel "public abstract String color() tarvis defineerida?; st miks ei piisa iga enumi color() override'ist?"
- + KASULIKUD LINGID:
- - spring web (get/post, data saatmine/kuvamine via .JSP, authorisation, login,
- ... : http://bitbybitblog.com
- - sama link viitab veel parema autentimiseni (LDAP serveriga) @ spring docs:
- http://docs.spring.io/spring-security/site/docs/3.0.x/reference/ldap.html
- - üks äge protokolli implementatsioon (see google proto):
- https://developers.google.com/protocol-buffers/docs/javatutorial
- + frameworks:
- - conteinerid (nagu spring) hivemind, picocontainer (mõlemad VIST samuti peamiselt
- dependency injectioniks)
- - testing: mockito, easymock, jmock;
- - boneCP - db connection pooling (btw, väidetavalt tomcatiga polegi endal vaja pooli tekitada: http://stackoverflow.com/questions/13792469/basic-db-connection-pool-with-java-and-tomcat-7
- btw2: boneCP conn pooliga pole endal vaja sünkroniseerida, kuna on juba seesmiselt
- lahendatud);
- btw3: boneCP pole enam kiireim, selle SO vastuse kohaselt:
- + randomit:
- - Dependency Inversion Principle (DIP):
- 1. HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.
- 2. ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS.
- - thread safety kohta lugemis:
- - http://www.javaworld.com/article/2072798/java-web-development/write-thread-safe-servlets.html
- - http://www.javaranch.com/journal/200603/Journal200603.jsp#a5
- - http://www.vipan.com/htdocs/usefulservlets.html
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement