JDK vs JRE vs JVM
-
JDK – Java Development Kit (in short JDK) is Kit which provides the environment to develop and execute(run) the Java program. JDK is a kit(or package) which includes two things Development Tools(to provide an environment to develop your java programs) JRE (to execute your java program). Note : JDK is only used by Java Developers.
-
JRE – Java Runtime Environment (to say JRE) is an installation package which provides environment to only run(not develop) the java program(or application)onto your machine. JRE is only used by them who only wants to run the Java Programs i.e. end users of your system.
- JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line hence it is also known as interpreter.
- JRE = JVM+Library classes, JDK = JRE+Development Tool
Java packages
- a package is used to group related classes. Think of it as a folder in a file directory.
- Why use it? To avoid name conflicts and to write a better maintainable code.
- Two categories of package:
- built-in packages (packages from Java API)
- user-defined packages
- The library is divided into packages and classes, meaning you can either import a single class (along with its methods and attributes), or a whole package that contain all the classes that belong to the specified package.
import <packagename>.<name>.<classname>; //import single class import <package>.name.*; //import the whole package
- Folder structure: to create user-defined packages, Java uses a file system directory to store them ``` root |_ mypackage |_MyPackageClass.java
// for all classes under within this package “mypackage”, in has “package” keyword, eg MyPackageClass.java
package mypackage;
class MyPackageClass { public static void main (String[] args){
} } ```
Java Classes/Objects
- create an object “myObj” of the class “MyClass”: `Myclass myobj = new MyClass();
Class Attributes
- access attributes by creating an object of the class, and using the dot syntax, e.g.,
myObj.x
.
Class Methods
- methods declared within a class
-
to call the method,
<method name>()
``` public class Main{ static void myMethod(){ // static method }public void myPublicMethod(str message){ //public method, must be called by creating objects // when it is called, it will print the argument
System.out.println("User message is: "+ message); } public static void main(String[] args){ myMethod(); Main myObj = new Main(); myObj.myPublicMethod(“hello world”); } }
* static vs non-static
* static method: can be accessed without creating an obj of the class
* public class: can only be accessed by objects
__Java Constructors__
* a constructor is a special method that is used to initialize objects. The constructor is called when an object of a class is created.
* the constructor name must match the class name, and cannot have a return type
* the constructor is called when the object is created
* all classes have constructors by default, if you don't create one yourself, java creates one for you, however, then you are not able to set initial values for object attributes.
* constructor parameters: it can take parameters used to initialize attributes.
public class Main{ int x; String modelName;
public Main(int y, String name){
x = y;
modelName = name;
}
public static void main(String[] args){
Main myObj = new Main(5, "Mustang");
System.out.println(myObj.x);
} } ``` * a class can have multiple constructors, we call it "constructor ovreloading" * Throwing Exceptions From a Constructor ``` public class Car {
public Car(String brand) throws Exception {
if(brand == null) {
throw new Exception("The brand parameter cannot be null!");
}
} } Car car = null; try{
car = new Car("Mercedes");
//do something with car object } catch(Exception e) {
// handle exception } ``` __Java Modifiers__ * void: show the method does not return any type. * modifiers are either: Access modifiers (controls the access level) or Non-access modifiers(do not control access level but provides other functionality) * Access Modifiers:
* for classes, either public or default
* public: accessible by any other class
* default: only accessiable by classes in the same package, used when you don't specify a modifier
* for attributes, methods, and constructors, "public", "private", "default", "protected"
* public: accessible by all classes
* private: only accessible within the declared class
* default: only accessible in the same package
* protected: accessible in the same package and subclasses * Non-accessible modifiers:
* for classes, either final or abstract
* final: cannot be inherited by other classes
* abstract: cannot be used to create objects
* for attributesand methods, "final", "static", "abstract", "transient", "synchronized", "volatile"
* final: attributes and methods cannot be overriden/modified
* static: attributes and methods belong to the class, rather than an object, it can be accessed without creating an object of the class.
Java Inner classes
- The purpose of nested classes is to group classes that belong together, which makes your code more readable and maintainable.
- One advantage of inner classes, is that they can access attributes and methods of the outer class
-
An inner class can also be static, which means that you can access it without creating an object of the outer class ``` class OuterClass { int x = 10;
class InnerClass { int y = 5; public int myInnerMethod() { return x; } } static class StaticInnerClass { int y = 5; } }
public class Main { public static void main(String[] args) { OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass(); System.out.println(myInner.y + myOuter.x); //access attributes and methods of the outer class System.out.println(myInner.myInnerMethod()); // static inner class OuterClass.InnerClass myStaticInner = new OuterClass.StaticInnerClass(); System.out.println(myStaticInner.y); } }
// Outputs 15 (5 + 10) // Outputs 10
__Java Interface__
* Why And When To Use Interfaces?
* used to specify interfaces without providing detailed content of the interface.
* To achieve security - hide certain details and only show the important details of an object (interface).
* An interface is a completely "abstract class" that is used to group related methods with empty bodies, To access the interface methods, the interface must be "implemented" (kinda like inherited) by another class with the implements keyword (instead of "extends"). The body of the interface method is provided by the "implement" class
// Interface interface Animal { public void animalSound(); // interface method (does not have a body) public void sleep(); // interface method (does not have a body) }
// Pig “implements” the Animal interface class Pig implements Animal { public void animalSound() { // The body of animalSound() is provided here System.out.println(“The pig says: wee wee”); } public void sleep() { // The body of sleep() is provided here System.out.println(“Zzz”); } }
class Main { public static void main(String[] args) { Pig myPig = new Pig(); // Create a Pig object myPig.animalSound(); myPig.sleep(); } }
__enum__
* a special class that represents a group of constant(unchangable variables)
__Documentation__
/**
- Returns an Image object that can then be painted on the screen.
- The url argument must specify an absolute {@link URL}. The name
- argument is a specifier that is relative to the url argument.
-
- This method always returns immediately, whether or not the
- image exists. When this applet attempts to draw the image on
- the screen, the data will be loaded. The graphics primitives
- that draw the image will incrementally paint on the screen. *
- @param url an absolute URL giving the base location of the image
- @param name the location of the image, relative to the url argument
- @return the image at the specified URL
- @see Image */ ```
WildCard
List<? extends MySuper>
then all I know about it is that every object in it implements the MySuper interface, and all the objects in that list are of the same type. it’s some subtype of MySuper. e.g., Person has subtype Teacher and Student, then Teacher and Student as well as Person items can be added to this defined listList<? super MySuper>
. Here we’re saying the collection is of a definite type which is a supertype of MySuper. e.g., MySuper=Student, then Student and Person items can be added to this list, but not Teacher.
HashMap
HashMap<String 1, String 2>
object called capitalCities that will storeString 1
keys andString 2
values
@Deprecated
- Deprecated tells other developers that the marked element should no longer be used.
web.xml
- it is the config file of web apps in java. It instructs the servlet container (e.g., tomcat) which classes to load, what params to set in the context and how to intercept requests coming from browsers.
pom.xml vs package.json, maven vs npm
- Common features:
-
both tools support dynamic fetch of dependencies (artifacts packages) based on (pom.xml package.json), and also allow you to (deploy publish) your own (artifacts packages)
-
- Differences:
- dependencies from a project build in maven are downloaded in
<homedir>/.m2
, with npm, they are downloaded in<projectdir>/node_modules
- building in
maven
is one-step process:mvn package (fetch deps and build)
, in npm it’s a 2-step process:npm install (fetch deps)
andnpm build (build)
. - in maven, setting-up the build process commonly involves editing the
pom.xml
. In npm, it involves writing code/config complementary build tooks likewebpack
. - in npm, start a project is
npm init
, with maven, you need to write a minimalpom.xml
. - adding deps in maven is done manually (or via IDE), while in npm via command line
- npm supports
dev, production builds
, in maven this needs to be defined throughprofile
.
- dependencies from a project build in maven are downloaded in
POM
- POM.xml contains info about the project and config details used by Maven to build the project
- Super POM: it is maven’s default POM. The config specified in the Super POM is inherited by the POMs you created f or your projects unless explicitly set.
- Minimal POM: the minimum requirement for a POM are ```
### Resources block
* By default, Maven will look for your project's resources under src/main/resources
Project
|– pom.xml
-- src
– main
`– resources
* However, all your resources may not be in src/main/resources. Thus, you'd have to specify those directories by adding the following to your POM. So if your resources resides in src/my-resources
* includes: A set of files patterns which specify the files to include as resources under that specified directory, using * as a wildcard. e.g., under `src/my-resources/ca/scam/common/<any folder>/` has many .xml files that specify the sensor data.
## WebService
### Web services components
* provider: defines a format for requests for its service and also the response
* client: makes the request for the web services
* web service: performs an action and sends a response back to the client
Service provider can write service in a langauge (e.g., PHP, Node.js) and service client can be written in another language (e.g., Python), and they can still communicate because they communicate through XML or JSON.
For example, our frontend uses javascript as a client to request services written in Python, and the interfaces are in JSON objects.
### Types of Providers defined by JAX-RS
* Entity: controls the mapping of data representations, e.g., XML, JSON, or CSV
* Context: resources can access via @Context annotation
* Exception: control the mapping of Java exceptions
### What is Java EE?
Java SE(Java Platform,Standard Edition),应该先说这个,因为这个是标准版本。Java EE (Java Platform,Enterprise Edition),java 的企业版本Java ME(Java Platform,Micro Edition),java的微型版本。JavaSE 可以开发和部署在桌面、服务器、嵌入式环境和实时环境中使用的 Java 应用程序。是EE,和ME的基础。一般就是指JDK。就是Java的基础语法(变量、方法、类之间的调用、关系,继承、接口、线程之类的),工具包(java.util.* ),或者其他的一些封装JavaEE,其实是一套规范,就是用java语言做企业开发(目前看来就是开发一些动态网站,或者对外提供调用服务的网站,或者其他没接触过的。。。)中的一整套规范,比如类怎么封装,网页的请求要用什么方法处理,语言编码一类的处理,拦截器啊什么的定义,请求返回得有什么信息。。。(具体看servlet的接口就知道了)
It has JAX-RS and JAX-WS, client-side API, aync capabilities, and servlet filters and interceptors.
### Types of web services
There are two types of web services.
1. SOAP: SImple Object Access Protocol. It is a XML based standard protocol for designing and developing web services. Since it is XML based, it's platform and language independent. So our server can be based on Java and client can be on .NET, PHP etc, or vice versa.
2. REST.
JavaEE is able to create both SOAP and REST web services.
1. JAX-WS: JAX-WS (Java API for XML Web Services) is a Java API for creating both SOAP and REST-style web services. There is a common misconception that JAX-WS is only for SOAP-based services, which is not true. Using JAX-WS you can create both SOAP and REST-style services
2. JAX-RS: JAX-RS (Java API for RESTful Web Services) is a Java API to write RESTful web services easily
JAX-RS can help users to easily build APIs using Java and REST.
// Example of JAX-RS package com.sun.jersey.samples.helloworld.resources;
import javax.ws.rs.GET; import javax.ws.rs.Produces; import javax.ws.rs.Path;
// The Java class will be hosted at the URI path “/helloworld” @Path(“/helloworld”) public class HelloWorldResource {
// The Java method will process HTTP GET requests
@GET
// The Java method will produce content identified by the MIME Media
// type "text/plain"
@Produces("text/plain")
public String getClichedMessage() {
// Return some cliched textual content
return "Hello World";
} }
### JAX-RS annotations
__@Path__
defines a RESTful web service resource, a relative PATH relative to the base URL
__@PathParam__
extracts params from the request URI for use in the resource
@Path(“{id}/{name}”) public Application getApplication(@PathParam(“id”) int id, @PathParam(“name”) String name){ return new Application(id, name: name+id, description:”description”+id) }
__@QueryParam__
extracts request URI query params for use in the resource
__@Consumes__
specifies the MIME media types a resource will consume or accept from the calling client.
__@Produces__
specifies the MIME media types a resource can produce and send back to the client, a MIME media type could be "application/json", or "image/jpeg"
__@Provider__
extends the JAX-RS runtime using application-supplied provider classes
__@ApplicationPath__
defines the URL mapping for the application, which is the base URL for all the RESTful resources specified by the @Path annotation, e.g., ApplicationPath is `/rest`, and @Path is `/applications`, then API endpoint is `localhost:8080/rest/applications`.
### Serilization and Deserilization
JAX-RS has a standard set of serilizers to handle different context types.
For example, for JSON, a standard serializer doesn't exist. Jackson (the most popular and high-performance JSON processor for Java) has a JAX-RS provider that has a serilizer and deserilizer.
__Add Jackson to Java app__
In POM.xml for the project, add a dependency block
### Maps to entities
### Test web services
in POM.xml, import JUnit dependency
public class ApplicationResourceTest{ @Test public void testGetAllApplications() throws Exception{ Client client = ClientBuilder.newClient(); Response response = client.target(“http://localhost:8080/javaee-7.0/rest”) .path(“applications) .request() .get(); asserNotNull(response); assertEquals(response.getStatus(), 200); } }
hover over the class "ApplicationResourceTest", and right click to select "Run Test"
### Authentication and Authorization
__AUthentication__
validate the identity of a client, typically with user credentials
* basic authentication: perform authentication over HTTP, base 64-coded username and password
__Authorization__
the next step after authenication, and determines what a client may have access to
__Interceptors and Filters__
* Interceptors and Filters sit between client and application. You can do several things within Interceptors and Filter:
* Logging: log specific information about requests
* Security: ensures requests are authenticated and authorized
* Encryption: want to encrypt/decrypt the request messages
* Interceptor gives developers access to ONLY the message body
* Filter gives developers access to all the messages that pass through (like query params, header, message body, etc.)
* it's possible to have multiple filters and interceptors.
// example of filter for authentication
@Provider
@PreMatching // means the filter will execute before the JAX-RS resource method is matched with the incoming HTTP request
public class BasicAuthenticator implements ClientRequestFilter{
public void filter(ClientRequestContext clientRequestContext) throws IOException{
MultivaluedMap<String, Object> headers = clientRequestContext.getHeaders();
final String basicAuthentication = getBasicAuthentication(); //calls the getBasicAuthentication method defined in this class
headers.add(“Authorization”, basicAuthentication);
}
private String getBasicAuthentication(){ String token = this.userName+”:”+”this.password; try{ return “Basic “+DatatypeConverter.printBase64Binary(token.getBytes()) }catch(UnsupportedEncodingException exception){ throw new IllegalStateException(“Unable to encode with UTF-8”, exception”); } } }
### Gson
Gson is a Java library that can be used to convert Java Objects into their JSON representation.
Add to Maven
Gson gson = new Gson(); // parses the JSON string into a Car object Car car = gson.fromJson(json, Car.class);
* How to run webservice locally without deploying it to Tomcat?
## Spring
__What is Spring?__
* open-source framework
__What is a Spring container and Spring Bean Factory and Spring XML and Dependency Injection__
* contains many objects, each object is called a bean. A bean is an object that is instantiated, assembled and managed by a Spring container.
* Dependency Injection: just mean connecting objects into other objects.
* What is instantiated? Say you have an object A outside of the spring container, and you have an object B inside the spring container, and object A depends on object B (it calls the object B), normally, within object A codebase, you would instant an object B by `new ObjectB object B`. Now, with spring container structure, you can instead instantiate an object B by calling the Spring Bean Factory. So to instantiate an object B, object B first calls the Spring Bean Factory, then Spring Bean Factory looks at the Spring XML file (this XML file is provided by you-the users) and returns the object B the bean. That is, in Spring container, dependency injection is done by an assembler rather than by the objects themselves.
// traditional programming public class Store{ private Item item; public Store(){ item = new ItemImpl1(); } }
// Using Dependency Injection in Spring Container public class Store{ public Item item; public Store(Item item){ this.item= item; } }
* Spring XML: it is the configuration metadata, consumed by the Spring container, provided by the app developers, that tells the Spring container how to instantiate, configure, and assemble the objects inside the Spring container.
__Spring @Service__
* @Service, @Controller, @Repository = {@Component+some more special functionality}
* Consider @Component as a Swiss kniff, it can act as a cutting knife, as an opener, as a scissor etc. Similarity, @Component can act as a Repository, as a controller, or as a business logic. Now, @Service is just one of the versions of @Component, say a knife. It is a good idea to use @Service over @Component in service-layer classes because it specifies intent better.
* Implementation of the service, often named "XXXServiceImpl"
@Service public class ProductServiceImpl implements ProductService{
} ```
Spring Boot
What is Spring Boot? just like “create-react-app” in React JS, Spring boot helps to quickly and easily create and maintain a spring application.
Set up VS IDE for Java and Tomcat
- install
java extension pack
, installtomcat server extension
- Add a Tomcat server and run/debug your .war on Tomcat Server