Cumulative QC Questions/ Possible Panel Questions

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Ribbon

Barracuda Citrix - Netscaler Ribbon - Provides the following functions for communicating with a cluster of servers: Multiple and pluggable load balancing rules Integration with service discovery Built-in failure resiliency Cloud enabled Clients integrated with load balancers Archaius configuration driven client factory

Babel

Babel is a JavaScript transpiler that converts edge JavaScript into plain old ES5 JavaScript that can run in any browser (even the old ones).

JPA

Java Persistence API A collection of classes and methods to persistently store the vast amounts of data into a database which is provided by the Oracle Corporation

JRE

Java Runtime Environment - Provides the minimum requirements for executing a Java application and consists of the JVM, core classes, and supporting files

JVM

Java Virtual Machine - Executes the java program line by line

Finally block

Java finally block is a block that is used to execute important code such as closing connection, stream etc. Java finally block is always executed whether exception is handled or not. Java finally block follows try or catch block. The only case it wont execute is with system.exit()

Collection methods

add addAll remove removeAll size clear containsAll Iterator toArray isEmply equals hashCode

Microservices

an architectural style that structures an application as a collection of loosely coupled services, which implement business capabilities. enables the continuous delivery/deployment of large, complex applications. It also enables an organization to evolve its technology stack.

application.yml vs bootstrap.yml

bootstrap.yml is loaded before application.yml. It is typically used for the following: When using Spring Cloud Config Server, you should specify spring.application.name and spring.cloud.config.server.git.uri inside bootstrap.yml some encryption/decryption information

break vs continue

break leaves a loop, continue jumps to the next iteration.

String Builder/Buffer methods

charAt() delete() insert() deleteCharAt() insert() ensureCapacity() indexOf() length(() replace() reverse() setCharAt() setLength() substring() trimToSize()

Cross site scripting

client side scripts are injected into web pages to trick the users of those web pages into surrendering information Angular protects against this by sanitizing and escaping untrusted values Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM

AJAX

web applications are able to make quick, incremental updates to the user interface without reloading the entire browser page. This makes the application faster and more responsive to user actions.

Can you have multiple constructors in TS?

yes, but only one constructor can be called

Angular Service examples

Location service Data service

Static keyword

Member belonging to the class instead of a specific instance

Front controller design patter

Request - Front controller - Model -Page Controller -Presenter(one of many) -view

Servlet init()

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.

Exception handling in soap

soap message

spring xml

using same words as in annotations

Non Access modifiers

Contextual Keywords any boolean constructor declare get module require number set string Strict Mode Reserved Words as implements interface let package private protected public static yield symbol type from of

TS Transpilation

Converts TS to JS (ECMAScript 5) so it can be used in applications

Using AJAX

Create an HTTP request using an XMLHttpRequest Object Set the onreadystatechange property of the object and naming it after the function to call when the request changes state Make the request by calling the open() and send() methods of the HTTP request object

ServletContext

Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.

Java Strings

Strings String Pool: special memory region where strings are stored by the JVM - Since Strings are immutable the JVM can optimize the amount of memory allocated to them by storing only one copy of each literal String in the pool

Status codes

1xx: information 2xx: Success 3xx: Redirect 4xx: Client side 5xx: Server side

Servlet XML configuration

<servlet> <description></description> <display-name>DispatcherServlet</display-name> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>com.thejavageek.servlets.DispatcherServlet</servlet-class></servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/DispatcherServlet</url-pattern> <servlet> <description></description> <display-name></display-name> <servlet-name></servlet-name> <servlet-class></servlet-class></servlet> <servlet-mapping> <servlet-name></servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>

Marker interface

An Interface with no methods. It is just used to classify as an instance of the class for something. Used to indicate something to the JVM RandomAccess is another marker interface. Ex: Serializable clonnable

TS Variable types

Boolean Number String Array Tuple Enum Any

Types of Dependency injection Modes of dependency injection

Constructor-Based - when the container of invokes a constructor with a number of arguments, each of which represents a dependency Setter-Based - when the container calls setter methods on your beans after it has invoked a no-argument constructor or no-argument static factory method to instantiate the bean 5.3. Field-Based Dependency Injection In case of Field-Based DI, we can inject the dependencies by marking them with an @Autowired annotation: public class Store { @Autowired private Item item; } Wiring allows the Spring container to automatically resolve dependencies between collaborating beans by inspecting the beans that have been defined. no: the default value - this means no autowiring is used for the bean and we have to explicitly name the dependencies byName: autowiring is done based on the name of the property, therefore Spring will look for a bean with the same name as the property that needs to be set byType: similar to the byName autowiring, only based on the type of the property. This means Spring will look for a bean with the same type of the property to set. If there's more than one bean of that type, the framework throws an exception. constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments

CORS

Cross-origin resource sharing - a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served

Serializable

Marker interface that can be implemented to serialize and deserialize data Serializing an object converts it into a byte stream so it can be stored

getting user input from front side

ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(new File("c:\\user.json"), user); Convert JSON to Java object ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(new File("c:\\user.json"), User.class); Note Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

Single page application

Single-Page Applications (SPAs) are Web apps that load a single HTML page and dynamically update that page as the user interacts with the app.

Forwarding servlets

String nextJSP = "/searchResult.jsp" RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP) dispatcher.forward(request,response) Information is sent directly to another servlet without the client side being aware of anything happening

union vs join

Union combines rows Union all - will not eliminate duplicate rows join - combines columns

Wrapper Class

Used to convert primitive to object and object into primitive Object representation of primitive data We need them for... - Convert primitive data types to objects. Int -> Integer. - For Generics. string parsed to int

Iterator

Used to pass through the elements in a collection

Shadowing

Using two variables with identical names in overlapping scopes. The scope with the higher level scope is hidden because the variable with the lower scope overrides it

npm commands

install ls cd update ng generate (ng g) ng serve ng build

Commonly used thread methods

start(): java.lang.Thread.start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread yield(): java.lang.Thread.yield() A hint to the scheduler that the current thread is willing to yield its current use of a processor join(): java.lang.Thread.join() Waits for this thread to die getState(): java.lang.Thread.getState() Returns the state of this thread

Collections

useful class with static methods .sort .shuffle .reverse

let vs var

var is scoped to the nearest function block and let is scoped to the nearest enclosed block, which can also e smaller than a function block Both are global if outside of any block

Default constructor

Automatically generated constructor created when no other constructor is declared. Different from a regular no-args constructor

Creating a component without using CLI

Create a folder with component name create name.component.html create name.component.ts - use @Component decorator - selector - templateUrl - styleUrls - import component module create name.component.css import the component inside the app.module.ts file and include it in the declarations section

Servlet Mapping

<web-app> <servlet> <servlet-name>myinputservlet</servlet-name> <servlet-class>InputServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myinputservlet</servlet-name> <url-pattern>/in</url-pattern> </servlet-mapping> </web-app>

ServletConfig

An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.

Angular Service

Components shouldn't fetch or save data directly and they certainly shouldn't knowingly present fake data. They should focus on presenting data and delegate data access to a service. import { Injectable } from '@angular/core'; @Injectable export class exampleClass{ }

Scopes of a variable

Member Variables/Instance Variables (Class Level Scope) - Declared inside of the class but outside of any methods Parameter Variables Only the method where the parameter appears can access these variables. This is how information is passed to the object. Local Variables (Method Level Scope) - Declared inside of a method and cant be accessed outside of it Loop Variables (Block Scope) - A Variable declared inside a pair of brackets

Pipes in Angular

Used to display information in a different way than it is stored Takes in an input and changes that information into a desired format for display

Servlet destroy()

Used to indicate to a servlet that it is being taken out of service. This method is only called once all threads within the serlet's service method have exited or after a timeout period has passed

enhanced for loop

Used to iterate through all the elements of a collection, array, enum, or any object implementing the iterable interface. for (Sttring aString : arrayOfStrings) { }

Webpack

Webpack is a build tool that puts all of your assets, including Javascript, images, fonts, and CSS, in a dependency graph. Very useful for building complet front end applications

TypeScript access modifiers

public: available on instances everywhere private: not available for access outside of class protected: available on child classes but not on instances directly

Redirecting servlets

response.sendRedirect("http://example.com"); 2 step process: The web app instructs the browser to fetch a second url, which differs from the first A browser reload of the second URL will not repeat the original request but will rather fetch the second url More in debth: - When dispatcher service executes the code response.sendRedirect(...) the process starts - Http Response sent by dispatcher servlet has status code 301 and a header called location with the new url - The browser receives this response and recognizes 301 status code which is used to redirect a request - The browser finds the header called location and retrieves its value - The browser makes a new request according to the value of location header as specified in the previous response

How to handle an exception

throws: tells the programmer that this method has the potential of throwing the included exception Java throws keyword is used to declare an exception. Checked exception can be propagated with throws. Throws is followed by class. Throws is used with the method signature. throw: used to throw an exception for code that causes a problem Java throw keyword is used to explicitly throw an exception. Checked exception cannot be propagated using throw only. Throw is followed by an instance. Throw is used within the method. You cannot throw multiple exceptions. try-catch logic if it is an unchecked exception

npm commands

- ng generate component comp_name ls prune update clean -f install config cd touch

AMI

An Amazon Machine Image (AMI) provides the information required to launch an instance, which is a virtual server in the cloud.

Porject 3

- Spring Data - Spring Boot - H3 database - REST - Jasmine and Karma for front end testing - Agile environment - AJAX - Swagger - Strong emphasis on microservices

Web App vs Web Service

*** They are essentially the same but Web apps are primarily for users while web services are mainly Program to Program Web applications are run by users in the browser and have the following characteristics: - User interface - Runs in client - Client runs it with help of web browser - Server process the data based on client request and provide response Web Service - API that runs on the server and provide data to the client over http through standardized messaging system

Project 1

- Angular - Bootstrap - Servlets - Ajax - JSON - PostgreSQL - JDBC - Apache Tomcat Server

Project 2

- Angular 4 - Bootstrap - Java - Hashing Encryption - PostgreSQL - Spring MVC - S3 to deploy with AWS - Spring Tokens as cookies

Installing and running Jenkins

- Jenkins is installed on a server where the central build will take place - Install the Jenkins war file - \>Java -jar Jenkins.war to extract the war file - Access Jenkins by going to http://localhost:8080 - \>Java -version to verify Java installation, open the console and execute the following java command - Download Tomcat - \>startup.bat Start up Jenkins on Tomcat at localhost:8080 - Install the GIt, Slack, and Maven plugins - Give access to the plugins - Configure global tools - Configure Git - Create a project: --- Choose new item --- Select GitHub hook trigger for GitSCM polling and add location of POM file under "Build/Root POM" --- Add Maven version in global tool settings by --- Add slack notifications under "Post build actions" --- Povide context path for local deployment ---- Add Tomcat 8 as a container and provide the manager-script credentials

Benefits of Hibernate

--- In hibernate if we save the derived class object, then its base class object will also be stored into the database, it means hibernate supporting inheritance --- Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One --- Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.

load() vs get()

--- Only used the load() method if you are sure that the object exists but use get if you are not sure that the object exists --- load() method will throw an exception if the unique id is not found in the database but get will return null if the unique id is not found --- load() returns a proxy by default but get() will hit the database to get information

Hibernate Fetching strategies

1. SELECT - fetch = "select" or @Fetch(FetchMode.SELECT) This is the default fetching strategy 2. SELECT with BatchSize - @Fetch(FetchMode.SELECT) @BatchSIze(size=25) Loads the batch size per query 3. JOIN @Fetch(FetchMode.JOIN) Tries to load the data from both tables in the same query. Always triggers an EAGER load 4. SUBSELECT @Fetch(FetchMode.SUBSELECT) Two seperate queries, one for the parent table and one for corresponding data in a child table

normalization

1NF - Atomized data 2NF - must be in 1NF and: must not have any partial dependency If proper subset of candidate key determines non-prime attribute, it is called partial dependency. *Columns must be related to the composite key as a whole apposed to the individual 3NF -must be in 2NF and: have not transitive dependency for non-prime attributes *Fields in the same table cannot have values based on other fields in the same table ***One field cannot be determined by observing the value in another field ex: Country and international dialing code

Hibernate xml file

<class entity-name="Account" table="ACCOUNTS" node="account"> <id name="id" column="ACCOUNT_ID" node="@id" type="string"/> <many-to-one name="customerId" column="CUSTOMER_ID" node="customer/@id" embed-xml="false" entity-name="Customer"/> <property name="balance" column="BALANCE" node="balance" type="big_decimal"/> ... </class>

Servlet mapping

<web-app> <servlet> <servlet-name>Asha</servlet-name> <servlet-class>First</servlet-class> </servlet> <servlet-mapping> < servlet-name>Asha</servlet-name> <url-pattern>Krishna</url-pattern> </servlet-mapping> </web-app>

Advice Types

@Before @After @AfterReturning @AfterThrowing @Around

JUnit annotations

@BeforeClass - Run once before any of the test methods in the class @AfterClass - Run once after all the test in the class have been run @Before - Run Before @Test @After - Run After @Test @Test - Identifies the test method to run

Controller vs restcontroller

@Controller is used to mark classes as Spring MVC controller @ResponseBody - converts object into JSON, XML or text @RestController - Adds both the @Controller and @RespoinseBody annotations

Eureka

@EnableEurekaServer 8761 A REST (Representational State Transfer) based service that is primarily used for location services for he purpose of load balancing and failover the middle-tier serversws3

Feign Client

@EnableFeignClients @FeignClient("stores") Feign aims at simplifying HTTP API clients. Simply put, the developer needs only to declare and annotate an interface while the actual implementation will be provisioned at runtime.

Zuul

@EnableZuulProxy Zuul serves as a front controller for the gateway service. It's going to contact the discovery service for routing information and then we go into our services. It also serves as a filter for requests for the microservices. Zuul is a gateway service that provides dynamic routing, monitoring, resiliency, security, and more.

Hibernate Mapping

@Entity - Marks a class as an entity bean, so it must have no-argument constructor that is visible with at least protected scope. @Table - Allows you to specify the details of the table that will be used to persist the entity in the database @Id - used to annotate a primary key, can be a single field or a combination of multiple fields depending on your table structure @GeneratedValue - overrides the @Id annotations primary key determination @Column - Used to specify the details of the column to which a field or property will be mapped. @OneToMany - Maps tables to eachother using foreign keys @JoinTable - Used for entities linked through an associated table @JoinColumn - used to identify where the foreign key is when joining tables @OrderBy - Sorts all of your data in order @Transient - used when you don't want to persist the value in your database

Hystrix

@Hystrixcommand annotation and @circuitbreaker a way to prevent cascade failure, utilize fall-back methods and An implementation of the circuit breaker pattern Set up - Put the dependency in the pom file HystrixCommand.Setter config = HystrixCommand.Setter.withGroupKey() HystrixCommandPropperties

How do you inject a component to a view

@Injectable @Component NgModule TemplateRef - used to reuse DOM elements in views accross the app

Angular Component Declaration

@NgModule ***declarations components imports modules providers services

doGet method declaration

@Override protected void doGet(HttpServletRequest request, HttpServletResponse response)

Application Context

A child of the bean-factory interface Has all of the functionality of bean factory + : Messaging source Access to resources such as URL's and files Event propagation Loading of multiple contents

DockerHub

A cloud-based registry service which allows you to link to code repositories, build your images and test them, stores manually pushed images, and links to Docker Cloud so you can deploy images to your hosts.

Docker Registry

A registry is a storage and content delivery system, holding named Docker images, available in different tagged versions.

Web Service

A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. Web services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. A web service is a collection of open protocols and standards used for exchanging data between applications or systems.

Dockerfile keywords

ADD Copies a file from the host system onto the container CMD The command that runs when the container starts ENTRYPOINT ENV Sets an environment variable in the new container EXPOSE Opens a port for linked containers FROM The base image to use in the build. This is mandatory and must be the first command in the file. MAINTAINER An optional value for the maintainer of the script ONBUILD A command that is triggered when the image in the Dcokerfile is used as a base for another image RUN Executes a command and save the result as a new layer USER Sets the default user within the container VOLUME Creates a shared volume that can be shared among containers or by the host machine WORKDIR Set the default working directory for the container ADD copies new files, directories or remote file to container. Invalidates caches. COPY copies new files or directories to container. EXPOSE informs Docker that the container listens on the specified network ports at runtime. CMD provide defaults for an executing container. FROM initializes a new build stage and sets the Base Image for subsequent instructions SHELL changes the default shell that shell commands are run in. RUN execute any commands in a new layer on top of the current image and commit the results. ENV sets environment variable. WORKDIR sets the working directory for any RUN, CMD, ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. ARG defines a build-time variable. LABEL apply key/value metadata to your images, containers, or daemons. ENTRYPOINT configures a container that will run as an executable. VOLUME creates a mount point for externally mounted volumes or other containers. USER sets the user name for following RUN / CMD / ENTRYPOINT commands. ONBUILD adds a trigger instruction when the image is used as the base for another build. STOPSIGNAL sets the system call signal that will be sent to the container to exit. HEALTHCHECK tells Docker how to test a container to check that it is still working.

Software development methodologies

Agile Software Development Methodology

Container Orchestration

Allows us to not worry about what server will host a particular container or how that container will be started, monitored, and killed

Docker images

An instance of an image is called a container. You have an image, which is a set of layers as you describe. If you start this image, you have a running container of this image. You can have many running containers of the same image.

Angular Providers

An instruction to the DI system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide declarations: [ AppComponent, ItemDirective ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [], bootstrap: [AppComponent] @Component({ providers: [x, y, z] })

Hibernate

An object-relational mapping tool that provides a framework for mapping an object-oriented domain model to a relational database. Hibernate handles object-relational impendance mismatch problems by replacing direct persistent database accesses with high-level object handling functions

Angular

Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection, end to end tooling, and integrated best practices to solve development challenges. Angular empowers developers to build applications that live on the web, mobile, or the desktop

Truthy Falsey

Any value can be resolved to either true or false " " || "Cat" => "Cat" " " && "Cat" => " "

Spring AOP core concepts

Aspect - Implements enterprise application concerns that cut across multiple classes Join Point - a specific point in the application such as method execution, Exception Handling Advice - Actions taken for a particular Join point pointcut - expressions matched with join points to determine whether advice needs to be executed or not Target Object - Object on which the advice are applied Weaving - Linking aspects with other objects to create the advised proxy objects

AOP

Aspect Oriented Programming - a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns.

ACID

Atomicity. In a transaction involving two or more discrete pieces of information, either all of the pieces are committed or none are. Consistency. A transaction either creates a new and valid state of data, or, if any failure occurs, returns all data to its state before the transaction was started. Isolation. A transaction in process and not yet committed must remain isolated from any other transaction. Durability. Committed data is saved by the system such that, even in the event of a failure and system restart, the data is available in its correct state.

Error vs Exception

Both subclasses of throwable Error - mainly caused by the environement in which the application is running Impossible to recover from errors Exception - primariy caused by the application itself

Constructor chaining

Calling one constructor from another constructor with respect to the current object Can be done using this keyword if in the same class or using super() in a base class Person(int age){ this.age = age; } Person(){ this(5); }

Eureka

Client-side service discovery allows services to find and communicate with each other without hard coding hostname and port. The only 'fixed point' in such an architecture consists of a service registry with which each service has to register. With Netflix Eureka each client can simultaneously act as a server, to replicate its status to a connected peer. In other words, a client retrieves a list of all connected peers of a service registry and makes all further requests to any other services through a load-balancing algorithm. yml - eureka: client: registerWithEureka: false fetchRegistry: false server: waitTimeInMsWhenSyncEmpty:

Docker Swarm

Clustering and scheduling tool for Docker containers. With Swarm, IT administrators and developers can establish and manage a cluster of Docker nodes as a single virtual system.

Hibernate Interfaces

Configuration - used to configure hibernate. The application uses a Configuration instance to specify the location of mapping documents and Hibernate-specific properties and then create the SessionFactory Transaction - A transaction represents a unit of work. Application uses transactions to do some operations on DB. Within one transaction you can do several operations and can commit transaction once after successfully completed all operations. --- The advantage is that you can rollback on all operations in a transaction if one fails SessionFactory - The application obtains instances from a Session Factory. One application is created for the whole application. If the application access multiple databases, it needs one per database Session - A persistence manager that manages operations like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. .They are not thread safe. Session holds a mandatory first-level cache of persistent objects taht are used when navigating the object graph Criteria HQL Criteria vs HQL - ---Criteria are ideal for dynamic queries. It makes that task of adding ordering, leaving some parts out depending on some parameter ---HQL is ideal for static and complex queries ---Criteria is ideal for dynamic queries. It is very simple to add restrictions and ordering as well as pagination ---Criteria can only perform select operations ---Criteria is safe from SQL injection. HQL is not

What exception do you get from trying to run Eureka Client before Eureka Server

ConnectionTImeoutException - The Client is trying to connect to a non-existent server

CD

Continuous Delivery is the ability to get changes of all types—including new features, configuration changes, bug fixes and experiments—into production, or into the hands of users, safely and quickly in a sustainable way.

CI

Continuous integration is a DevOps software development practice where developers regularly merge their code changes into a central repository, after which automated builds and tests are run.

Spring MVC exception handling

Controller Based - use @ExceptionHandler Global Exception Handler - use @ControllerAdvice for cross-cutting exception handling HandlerExceptioResolver - An interface we can implement to create a global exception ahandler

Exposing a REST service

Create the service that you want to be defined Define endpoints to consume and produce JSON objects using @RequestMapping or @Get,Post,Put,EtcMapping within a @Controller or @RestController class. Spring 4.3.0.RELEASE jackson-databind 2.7.5 jackson-dataformat-xml 2.7.5 Maven 3 JDK 1.7 Tomcat 8.0.21

Criteria vs HQL

Criteria vs HQL - ---Criteria are ideal for dynamic queries. It makes that task of adding ordering, leaving some parts out depending on some parameter ---HQL is ideal for static and complex queries ---Criteria is ideal for dynamic queries. It is very simple to add restrictions and ordering as well as pagination ---Criteria can only perform select operations ---Criteria is safe from SQL injection. HQL is not

DDL

Data Definition languae - DROP - CREATE - ALTER - TRUNCATE

DML

Data Manipulation Language - DELETE - UPDATE - INSERT - (SELECT)

DQL

Data Query Language -SELECT

Orchestration

Deploying complex multi-container apps on many machines. Docker provides its own built-in orchestration via their services such as Docker Swarm, Dockerhub, DockerCompose, DockerImage.

How Jenkins works

Developers check their source code Jenkins will pick up the changed source code and trigger a build and run any tests if required The build output will be available in the Jenkins dashboard. Automatic notifications can also be sent back to the developer

DI

Direct injection - A type of IoC Classes using functionality of other classes w/out having the developer rewrite code - Setter injection - Constructor injection - Field injection - ByName, ByType, no, @Autowiring

Docker

Docker is an open-source project for automating the deployment of applications as portable, self-sufficient containers that can run on the cloud or on-premises. Docker is also a company that promotes and evolves this technology. Uses shard operating systems. This means that it is much more efficient than a virtual machine. Containers also lend themselves more effectively to CI and CD

Dockerfile

DockerImages are defined by Dockerfiles. Dockerfiles are the definitions for our Images. The Dockerfile is simply just a list of steps to perform to create that image.

DNS

Domain name system

JDBC interfaces

DriverManager - manages database drivers, loads database specific drivers and selects the most appropriate database specific driver from the previously loaded drivers when a new connection is established Connection - standard abstraction to access the session established with a database server Statement - Provides standard abstraction to execute SQL statements and return the resulting using the ResultSet objects PreparedStatement - sub interface of statement interface and are pre-compiled making their execution much faster and are not succeptible to query injection CallableStatement - Extends PreparedStatement to include methods that are only appropriate for stored procedure calls and hence CallableStatement is used to execute SQL stored procedures whereas PreparedStatement gives methods for dealing with IN paraameters CallableStatement provides methods to deal with OUT parameters as well SQLException

EC2

EC2 - Elastic Cloud Compute - is a web service that provides secure, resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers.

L2 caching plugins

EHcache - strengthens the distributed caching capabilities via improved support for cache resiliency when operating in less stable environments. **Used only for Java Apache Ignite - Ignite In-Memory Data Fabric can be used as Hibernate Second-Level cache (or L2 cache), which can significantly speed-up the persistence layer of your application. ** Used for more than just Java

Load Balancing vs Auto Scaling

Elastic load Balancing - Adds and removes EC2 instances and traffic for application is distributed across EC2 Auto Scaling - insatanceScales load balancer as scale of traffic changes over time

Angular Routing

Enables navigation from one view to the next as users perform application tasks Ways to route ----------------------------------------- <base href = "/"> ----------------------------------------- Import { RouterModule, Routes} from '@angular/router'; const appRoutes: Routes = [ { path: ' ', componenet } ] ----------------------------------------- Router links - directives on an anchor tag <a routerLink = "/home-page">

Spring Actuator endpoints

Endpoints: /metrics - Shows 'metrics' information for the current application /info - Displays arbitrary applciation info; not sensitive by default /trace - displays trace information /health - shows application health information Configuring endpoints: id enabled - true = accessible sensitive - true = need auth create a custom endpoint using @component and implementing Endpoint interface

SOAP message

Envelope - root element of the XML document representing the message. IT defines the framework for how the message should be handled and by whom Header - Generic mechanism for adding features to a SOAP message. It can contain any number of child elements that define extensions to the base protocol Body - a container for mandatory information intended for the ultimate recipient of the message Fault

Setting up Eureka and Zuul

Eureka - Put dependecnies in update application.yml eureka: client: registerWithEureka: false fetchRegistry: false server: waitTimeInMsWhenSyncEmpty: add @EnableEurekaServer to app mark each client with @Client Zuul add dependency configure the yml with int bootstrap.yml spring: application: name: zuul cloud: config: uri: http://localhost:8888 @EnableZuulProxy in application

Eureka Client vs server vs instance vs service

Eureka Client: it can be a microservice that is ready to work so it registers itself to the Eureka server e.g. an API for some app, or some application that goes to the server and asks for directions to a specific microservice. Eureka Instance: a single instance of a microservice (you can add more instances of the same microservice as your load grows i.e. horizontal scaling). Eureka Service: looks like when you register a microservice as an Eureka Client, you obtain an Eureka Service registered by an ID. Eureka Server: a server where microservices can register themselves so others can discover them.

Mandatory Dockerfile commands

FROM - tells what instance to use ADD - copies local files to instacne EXPOSE - opens the desired port to use ENV - defines environment variables CMD - defines command to be executed

Serialization syntax

FileInputStream FileOutputStream

Idempotent

From a RESTful service standpoint, for an operation (or service call) to be idempotent, clients can make that same call repeatedly while producing the same result. In other words, making multiple identical requests has the same effect as making a single request

Zuul

Gateway server: Applies filters to data coming from the front side of an application PRE Filters execute before routing to the origin. Examples include request authentication, choosing origin servers, and logging debug info. ROUTING Filters handle routing the request to an origin. This is where the origin HTTP request is built and sent using Apache HttpClient or Netflix Ribbon. POST Filters execute after the request has been routed to the origin. Examples include adding standard HTTP headers to the response, gathering statistics and metrics, and streaming the response from the origin to the client. ERROR Filters execute when an error occurs during one of the other phases. Configured in the pom and yml

Http Request methods

Get Head Post Put Delete Connect Options Trace Patch

servlet response

HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>

Kafka

Has 3 key capabilities: --- Publish and subscribe to streams of records, similar to a message queue or enterprise messaging system --- Store streams of records in a fault-tolerant durable way --- Process streams of records as they occur

hashmap vs hashtree

Hashmap returns unordered values while hashtree returns values in ascending orderof keys by default The performance of hashmap is faster than hashtree

Automatic dirty checking

Hibernate has a feature of checking all managed entity properties . Whenever an entity is loaded through hibernate, it makes an additional copy of that whole entity object along with the all entity's property values. By entity, we mean each persistent object of that entity type. A transaction is performed with the help of the session. Session object helps in fetching the transaction object. So while a session remains open and if a persistent object is modified, its data is kept synchronized with database. The data will be synchronized but will not be committed, till session's flush() method is called. Both synchronization and committing of code will happen together when the code is committed. It will also be synchronized at some other points too. For example, if hibernate performs some queries on database.

REST Error Handling

Http Status Codes 1XX Informational 2XX Success 3XX Redirection 4XX Client Error 5XX Server Error

What service in AWS is used to allow and restrict access to users?

Identity access management

IaaS, PaaS, and SaaS

Infrastructure as a Service You manage: - applications - data - runtime - middleware - o/s they manage: - virtualization - servers - storage - networking Platform as a service you manage: - applications - data they manage - runtime - middleware - o/s - virtualization - servers - storage - networking Software as a Service You manage: - applications - data - runtime - middleware - o/s - virtualization - servers - storage - networking

Life Cycle of a spring bean

Instantiate Populate Properties setBeanName() - sets the name of the bean in the bean factory setBeanFactory() - supplies the owning bean factory instance to the bean setApplicationContext() - supplies the owning application context instance to the bean Pre-Initialization InitializingBeans.afterPropertiesSet() Custom init Method Post initialization Bean is ready Destroy() Call custom destroy method()

Thread exceptions

Interupted Exception - Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity.

IoC

Inversion of Control

Inversion of control

Inversion of control (IoC) is the principle where the control flow of a program is inverted: instead the programmer controls the flow of a program, the external sources (framework, services, other components) take control of it. As the name implies Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it's the responsibility of container to create object as required.

SOAP web service technologies

JAX-WS - API that allows us to more smoothly deploy web services Apache cxf - Allows JAX-WS to communicate and work over a variety of transports such as HTTP, JMS or JBI.

SOAP annotation

JAX-WS annotations @WebService - Used to define either a Service Implementation Bean SIB or a Service Endpoint Interface SEI @SOAPBinding - Used to specify the soap messaging format which can either be RPC or document @WebMethod - specifies that the method represents a web service operation @WebResult - Used to help determine what the generated WSDL shall look like @ResponseWrapper - Used to annotate methods in the Service Endpoint Interface with the response wrapper bean to be used at runtime

Exposing a SOAP web service

JAXWS Java API for XML Web Services (JAX-WS) is one of a set of Java technologies used to develop Web services. Apach CFX Apache CXF™ is an open source services framework. CXF helps you build and develop services using frontend programming APIs, like JAX-WS and JAX-RS. These services can speak a variety of protocols such as SOAP, XML/HTTP, RESTful HTTP, or CORBA and work over a variety of transports such as HTTP, JMS or JBI. Map Request XML to Request Objects Design business logic Map the object to a response XML Send Response @Endpoint @PayloadRoot @ResponsePayload Receive Request @EnableWS @Configuration @Bean

JPQL

JPA's query language which has similar syntax to SQL When you execute such a query, your persistence provider interprets the JPQL statement and generates any SQL query for it. .By doing that, the persistence provider adapts the query to the database-specific SQL dialect and improves the portability of your application

JCBC

Java Database Connection DriverManager Connection Statement PreparedStatement CallableStatement ResultSet

Jenkins

Jenkins offers a simple way to set up a continuous integration and continuous delivery environment for almost any combination of languages and source code repositories using pipelines as well as automating other routine development tasks

Jenkins Job

Jenkins seems to use these terms interchangeably. They all refer to runnable tasks that are controlled / monitored by Jenkins.

L1 caching

L1 Cache is the cache that exists per Hibernate session, and this cache is not shared among threads. This cache makes use of Hibernate's own caching.

L2 caching

L2 Cache is a cache that survives beyond a Hibernate session, and can be shared among threads. For this cache you can use either a caching implementation that comes with Hibernate like EHCache or something else like JBossCache2 L2 caching is external of Hibernate and requires a plugin

Common Hibernate Exceptions

LazyInitializationException - Hibernate throws a LazyInitializationException if you try to access a not initialized relationship to another entity without an active session. OptimisticLockException - Hibernate throws it when you use optimistic locking and detects a conflicting update of an entity. That most often happens for one of two reasons: 2 users try to update the same entity at nearly the same point in time. 1 user performs 2 updates of the same entity, and you didn't refresh the entity representation in the client so that the version value wasn't updated after the first update. DataException - Implementation of JDBCException indicating that evaluation of the valid SQL statement against the given data resulted in some illegal operation, mismatched types or incorrect cardinality.

Lifecycle hooks of an angular component

Lifecycle hooks allow us to take a look at key points in a programs lifecycle, methods are prefixed with ng Ex. ngOnInIt() ngOnChanges() ngDoCheck() ngAfterContentInit ngAfterContentChecked() ngOnDestroy()

List vs set

List is an ordered sequence of elements Set is a distinct list of unique elements which is unordered

Ribbon

Load balancing

Map methods

Map <k,v> size() isEmply() containsKey(Obj key) containsValue(Obj val) get(Obj key) put(K key, V val) remove(Obj Key) putAll(Map<>) clear() equals

Messaging Queues

Messaging queues allow applications to communicate by sending messages to each other. Provides a temporary message storage when the destination program is busy or not connected A message queue provides an asynchronous communications protocol, a system that puts a message onto a message queue does not require an immediate response to continuing processing. Imagine that you have a web service that receives many requests every second, where no request is afford to get lost and all requests needs to be processed by a process that is time consuming.

Spring MVC Annotations

Model, View Controller @Controller @RequestMapping @PathVariable @RequestParam @ModelAttributes @SessionAttributes Other useful annotations @Service @Repository @Component @Autowired - allows Spring to auto-wire other beans into your class @Transactional - Propagational @Scope

Spring actuator

Monitors our app, gathers metrics To get started: - Place dependency in pom - Expose endpoints through spring MVC /health - Shows application health information (a simple 'status' when accessed over an unauthenticated connection or full message details when authenticated); it's not sensitive by default /info - Displays arbitrary application info; not sensitive by default /metrics - Shows 'metrics' information for the current application; it's also sensitive by default /trace - Displays trace information (by default the last few HTTP requests)

get vs post

Post is not stored in browser history but get is Post cannot be bookmarked Post can transfer larger amounts of data, Get is limited to request line Get is Less secure Get is visible to everyone, post is not displayed in the URL

multithreading

Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area. They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process.

Spring Propagation

NESTED - makes nested Spring transactions to use the same physical transaction but sets savepoints between nested invocations so inner transactions may also rollback independently of outer transactions. MANDATORY - states that an existing opened transaction must already exist. If not an exception will be thrown by the container. NEVER - an existing opened transaction must not already exist. If a transaction exists an exception will be thrown by the container. NOT_SUPPORTED - execute outside of the scope of any transaction. If an opened transaction already exists it will be paused. SUPPORTS - will execute in the scope of a transaction if an opened transaction already exists. If there isn't an already opened transaction the method will execute anyway but in a non-transactional way.

Thread states

NEW - Thread instance has just been created RUNNABLE - the thread can be run BLOCKED - blocked waiting for a monitor lock WAITING - Thread is temporarily inactive TIMED WAITING - when a thread calls a method with a timed out parameter TERMINATED - The thread has exited

SQL constraints/clauses

NOT NULL - Ensures that a column cannot have a null value UNIQUE - Ensures that all values in a column are different PRIMARY KEY FOREIGN KEY CHECK - Ensures that all values in a column satisfies a specific condition DEFAULT - Sets a default value for a column when no value is specified INDEX - Used to create and retrieve data from the database very quickly CLAUSES FROM Clause List tables and join information WHERE Clause Filter results ORDER BY Clause Sort query results GROUP BY Clause Group by one or more columns HAVING Clause Restrict the groups of returned rows

zuul filter types

PRE Filters execute before routing to the origin. Examples include request authentication, choosing origin servers, and logging debug info. ROUTING Filters handle routing the request to an origin. This is where the origin HTTP request is built and sent using Apache HttpClient or Netflix Ribbon. ERROR Filters execute when an error occurs during one of the other phases. POST Filters execute after the request has been routed to the origin. Examples include adding standard HTTP headers to the response, gathering statistics and metrics, and streaming the response from the origin to the client.

Central Configuration

Pattern of configuration used with the configuration server The configuration load list contains one or more ConfigServer elements that tell the agent how to connect to a central configuration server. Central configuration servers contain a repository of files that are served to the monitoring agents using HTTP.

PLPSQL

Procedure Language Postgre SQL ---Functions ---Refc ---$$ - delimiter CREATE OR REPLACE FUNCTION show_states() RETURNS refcursor AS $$ DECLARE refc refcursor; BEGIN OPEN refc FOR SELECT id, name, abbreviation fROM states; RETURN refc; END; $$ LANGUAGE plpgsql;

Binding

Property Binding - Allows you to change the value of a certain variable in a component and display it in view <img [src]="angularLogo"> <img bind-src="angularLogo"> Event Binding - Sending the value of a certain variable from the presentation layer to the component after a certain event occurs Interpolation - {{xxxxx}} Two way binding - allows us to receive and send info to view simultaneously,( typing in text box changes text on page ) *** uses [(ngModel)]

RDS

RDS - Relational Database System - A database provided by AWS. Build inside of an EC2

SOAP vs REST

REST operates through a solitary, consistent interface to access named resources. It's most commonly used when you're exposing a public API over the Internet. SOAP, on the other hand, exposes components of application logic as services rather than data. REST accesses data while SOAP performs operations through a more standardized set of messaging patterns. REST allows a greater variety of data formats, whereas SOAP only allows XML. REST provides superior performance, particularly through caching for information that's not altered and not dynamic. SOAP is highly extensible through other protocols and technologies.

SQL Joins

RIght Join Left Join Inner Join - all data that exists in both tables in terms of rows Full Join Cross Join Natural Join

SOAP document vs RPC

RPC - Remote Procedure call 1.SOAP has more complicated designs compared to XML-RPC 2.For XML-RCP, the order is more relevant than the procedure. For SOAP, it is the other way around. 3.SOAP is more powerful in terms of capabilities compared to RPC. 4.RPC, on the other hand, has more python support than that of SOAP.

Types of Messaging Queue's

RabbitMQ - Traditional messaging queue In the case of RabbitMQ the broker makes sure the messages are delivered to the consumers and dequeue them only when it gets acknowledgement from all the consumers that need that message. It also keeps track of consumer state. Kafka does not keep track of "which messages were read by consumers". The Kafka broker keeps all messages in queues for a fixed duration of time and it's the responsibility of the consumer to read it from the queue. It also does not have this overhead operation of keeping track of consumer state

REST

Representational State Transfer - Web service communication protocol an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other. REST-compliant systems, often called RESTful systems, are characterized by how they are stateless and separate the concerns of client and server. - JSON or XML - Mostly Bound to Http/Https - No Contract Necessary - Only end to end security

Throwable

Root interface of all exceptions

Components of a load balancer

Rule - a logic component to determine which server to return from a list Ping - a component running in background to ensure liveness of servers ServerList - this can be static or dynamic. If it is dynamic (as used by DynamicServerListLoadBalancer), a background thread will refresh and filter the list at certain interval

Route 53

S3 - A storage mostly for static files and they are persisted in their own space, isolated. A scalable and highly available Domain Name System, It is part of Amazons cloud computing platformIn addition to being able to route users to various AWS services, including EC2 instances, Route 53 also enables AWS customers to route users to non-AWS infrastructure. Route 53's servers are distributed throughout the world.

Feign

Send messages to other microservices Pretends to be a client and sends messages through an http message

Serializable

Serialization is the process of turning an object in memory into a stream of bytes so you can do stuff like store it on disk or send it over the network. implement serializable interface FileInputStream and FIleOutputStream inside of ObjectInputStream and ObjectOutputStream readObject

What happens when the client sends a request to a web application

Server takes request and maps it to a file on the file system and then sends that file back to the client

SOA

Service-Oriented Architecture Business to Business services are provided by application components through a communication protocol over a network 4 Basic Principles 1. It logically represents a business activity with a specified outcome. 2. It is self-contained. 3. It is a black box for its consumers. 4. It may consist of other underlying services.[3]

Servlet API structure

Servlet ServletRequest ServletResponse RequestDispatcher ServletConfig ServletContext SingleThreadModel Filter FilterConfig FilterChain ServletRequestListener ServletRequestAttributeListener ServletContextListener ServletContextAttributeListener

Servlet Hierarchy

Servlet Interface GenericServley Abstract class Http Servlet User defined Servlet

Session vs cookie

Session - used to store per-user information for the current Web session on the server. It supports using a database server as the back-end store. Lost when the browser is closed Cookie - should be used to store per-user information for the current Web session or persistent information on the client, therefore client has control over the contents of a cookie. Stored in browser until deleted

SessionFactory vs Session

SessionFactory - The application obtains instances from a Session Factory. One application is created for the whole application. If the application access multiple databases, it needs one per database Session - A persistence manager that manages operations like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. .They are not thread safe. Session holds a mandatory first-level cache of persistent objects taht are used when navigating the object graph

SOAP`

Simple Object Access Protocol Web service communication protocol - Bound to XML - Protocol Flexible - Contract Based - Provides Better Security -Developed by Microsoft - Contract First vs. Contract Last Advantages -- Security -- Standard HTTP protocol makes it easier for it to operate across firewalls and proxies without modifications to the SOAP protocol itself -- If you need ACID-compliant transactions, SOAP is the way to go -- offers built-in retry logic to compensate for failed communications

S3

Simple Storage System S3 - A storage mostly for static files and they are persisted in their own space, isolated.

Config server

Spring Cloud Config is Spring's client/server approach for storing and serving distributed configurations across multiple applications and environments. This configuration store is ideally versioned under Git version control and can be modified at application runtime. While it fits very well in Spring applications using all the supported configuration file formats together with constructs like Environment, PropertySource or @Value, it can be used in any environment running any programming language. Spring Cloud Config Server provides an HTTP resource-based API for external configuration (name-value pairs or equivalent YAML content). The server is embeddable in a Spring Boot application, by using the @EnableConfigServer annotation. Consequently, the following application is a config server:

Common errors

StackOverflowError OutOfMemoryError

Statement, PreparedStatement, CallableStatement

Statement - Provides standard abstraction to execute SQL statements and return the resulting using the ResultSet objects PreparedStatement - sub interface of statement interface and are pre-compiled making their execution much faster and are not succeptible to query injection CallableStatement - Extends PreparedStatement to include methods that are only appropriate for stored procedure calls and hence CallableStatement is used to execute SQL stored procedures whereas PreparedStatement gives methods for dealing with IN paraameters CallableStatement provides methods to deal with OUT

Variables in an interface

Static and final by default Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

Communicating between Services

Synchronous - using the same strategy as you would to communicate with a client using REST Asynchronous - Using a lightweight message broker such as rabbitMQ or Kafka

Referential integrity

Table relationships must always be consistent Any foreign key field must agree with the primary key that is referenced by the foreign key Any primary key changes must be applied to the foreign key of corresponding tables

@Path

The @Path annotation identifies the URI path template to which the resource responds, and is specified at the class level of a resource. The @Path annotation's value is a partial URI path template relative to the base URI of the server on which the resource is deployed, the context root of the WAR, and the URL pattern to which the Jersey helper servlet responds.

Docker Daemon

The docker daemon strives to keep a project in a "container". It is the core of Docker. "You could describe Docker as a client <-> server application. The daemon is the server, and the CLI is 1 of many clients." - this guy

REST Resource

The fundamental concept in any RESTful API is the resource. A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it. It is similar to an object instance in an object-oriented programming language, with the important difference that only a few standard methods are defined for the resource (corresponding to the standard HTTP GET, POST, PUT and DELETE methods), while an object instance typically has many methods.

Why is hibernate portable

The hibernate queries still work no matter what kind of database you are using to persist

what is a local variables default value

The local variables are not initialized to any default values. We should not use local variables with out initialization. Even the java compiler throws error.

Bean factory

The root interface for accessing a Spring bean container. This is the basic client view of a bean container The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves.

implementing sleep with threads

Thread.sleep(time in ms)

Servlet Exception handling

Throws ServletException or IOException Sends a 500 http status code back to the client to indicate an issue on the service side of the application

TCL

Transaction Control Language - BEGIN - END -ROLLBACK - SAVEPOINT - RELEASE

States of objects in Hibernate

Transient - An object is not associated with a hibernate session and does not represent a row in the database. An object that is created for the first time using the new() operator is in transient state. When the object is in transient state then it will not contain any identifier. You have to use save, persist, or saveOrUpdate methods to persist the transient object Persistent - An object that is associated with the hibernate session. When the object is in persistent state, then it represents one row of the database and consists of an identifier value. You can make a Transient value Persistent by associating it with a Session Detached - Object that has just been removed from the hibernate session. Any changes made to the detached object are not saved to the database. The detached object can be reattached to the new session and saved to the database using update, saveOrUpdate, and merge methods

SOAP Tools

Used for testing a web service so that it works when deployed

Static keyword

Variable - used when referring to a common property of all objects Method - belongs to the class rather than an instance of the class Block - used to initialize static data member. Executed before main method at the time of classloading Nested Class - A class defined within another class can be static. Nested static class does not require reference of outer class while not static nested classes do

Overloading Constructors

Very common, each constructor takes in different parameters

WSDL

Web Service Description Language Definition Types- Data type definitions Message - definition of data Operations - description of action Port Type - Possible operations Binding - Data format specs Port - single endpoint definition Service - collection of endpoints

SOAP Error Handling

defines a standard, platform-independent way of describing the error within the SOAP message using a SOAP fault. In general, a SOAP fault is analogous to an application exception. SOAP faults are generated by receivers to report business logic errors or unexpected conditions. <envelope> <header> <body> <faultCode> - indicates class of error <faultString> - explains error <faultActor> - who's fault it was <detail> - message about error SOAP-ENV:VersionMismatch SOAP-ENV:MustUnderstand SOAP-ENV:Client SOAP-ENV:Server

Docker commands

docker build docker runn -d -p docker login docker image push docker image pull docker container ls docker images -all docker stop docker logs docker run swarm mvn deploy

DOM manipulation

document.getElementById(id) document.getElementsByTagName(name) document.createElement(name) parentNode.appendChild(node) element.innerHTML element.style.left element.setAttribute() element.getAttribute() element.addEventListener() window.content window.onload window.dump() window.scrollTo()

equals vs hashcode

equals - a method provided by Object class that indicates whether some other object passed as an argument is equal to the current instance hashcode() - a method provided by Object class that returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance

When to use a for loop vs while loop

for - good when you know the number of repetitions or user inputs number of repetition while - good for when you are waiting for a certain condition to be met

Hystrix

hystrix: command: myusers-service: execution: isolation: thread: timeoutInMilliseconds: ...

Creating a thread

implement runnable interface extending thread class Annonymous lambda

Consuming a REST service

import HttpClient Configure component using HTTP method Connect to the API through by defining the Api url and server Use an observable to collect incoming data public getAll<T>(): Observable<T> { return this.http.get<T>(this.actionUrl); }

unix commands

ls mv cp rm diff wc chmod gzip gunzip gzcat lpr lpq lprm gensript dvips mkdir cd man cmp

Update() vs Merge()

merge(): Used primarily to persist a detached object. Will allow an identifiable detached object to be updated with new data, returning an updated persisted object. Note: The origin object may or may not be persisted and should probably be discarded. If used on a transient object it will return a newly persisted object. Cascades for all relations with cascade=MERGE or cascade=ALL update(): Update is intended for updating the values of an object which is either persisted or detached. Update works in place transitioning the object to a persistent state. ***If used on a transient object it will throw a PersistenceException.

Instantiate a Bean Container

new ClassPathXmlApplicationContext(new String[]{"services.xml","doas.xml"});

What methods can you implement with threads

run() - introduces a concurrent thread into your program *start() - causes the JVM to spawn a new thread and make the new thread execute run() sleep(int time) - suspends thread yield() - current thread pauses for another thread join() - queues up the thread in execution isAlive() - check if thread is still alive

Consuming a SOAP web service

same as rest for Http use angular-soap for others, similar layout to http

Common exceptions

unchecked: - NullPointerException - ClassCastException - ArrayIndexOutOfBoundsException checked: - SQLException - IOException

Can something be abstract and final

a final abstract object or method would never do something because it could not be extended

Exception and examples

checked: compiler alerts you that they exist before runtime - Most common for external resources unchecked: compiler does not alert you that they exist before runtime Examples: Checked: NoSuchFieldException, IOException, SQLException Unchecked: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException ClassCastException

Ways of manipulating the latter of flow

for while do while if if else else switch

excpetion handling in rest

http error codes

Java Thread

independent path of execution though program code start() - begins execution

Attribute directive

ngModel - Creates a FormControl instance from a domain model and binds it to a form control element. The FormControl instance will track the value, user interaction, and validation status of the control and keep the view synced with the model. If used within a parent form, the directive will also register itself with the form as a child control. ngStyle - The NgStyle directive lets you set a given DOM elements style properties. ngClass - The NgClass directive allows you to set the CSS class dynamically for a DOM element.

exception handling in jdbc

try catch

Exception handling in spring

try catch entity manager Exceptionhandler separate controllerAdvice

Exception handling in hibernate

try catch lazy init object not found

What are modules in Angular

NgModules consolidate components, directives, and pipes into cohesive blocks of functionality, each focused on a feature area, application business domain, workflow, or common collection of utilities. Modules can also add services to the application. Such services might be internally developed, like something you'd develop yourself or come from outside sources, such as the Angular router and HTTP client. @NgModule({ imports:[ modules ], declarations[ components, pipes ], providers[ services ], exports[], bootstrap[entryComponents] })

How do we send data from our servlet to the front end

Jackson using ObjectMapper to write Java code to JSON Send information in response body

JDK

Java Development Kit - A software development environment used for developing Java applications and applets,

Java

Java is a programming language and computing platform first released by Sun MIcrosystems in 1995. most popularly used for Android and web applications

@Injectable

Lets angular know that a class can be used with the dependency injector. Any class such as a service that is going to be injected must have this decorator

HttpClient syntax

*Imported and instantiated in constructor parameter getData() { this.http.get(this.url).subscribe(res => { this.posts = res; }); }

Structural Directives

*ngIf *ngFor [ngSwitch]

creating a thread

1. Implement Runnable - great way to do it 2. Extend Thread - not so great 3. Anonymous/lambda - also great Runnable runnable = () -> { // your code here ... }; Thread t = new Thread(runnable); t.start();

Servlet

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

Servlet session management

A session is conversional state between client and server and can consist of multiple request and response between client and server. Each user is not assigned a new servlet object Servlets can be instantiated when the web app starts using the load-on-startup tag in the web.xml How many times are each lifecycle method of a servlet called? init once, service once per request, destroy once

4 pillars of OOP

APIE Abstraction - only show essential features of an object (A car is viewed as a car, not as its parts) Bike is a subclass of vehicle abstract class Polymorphism: Changing the behavior of like-methods Override: methods in different classes Overload: methods in the same class Inheritance: A child class gaining methods from a parent class Encapsulation: Restricting access to certain data. Access modifiers private fields public getters and setters

Observable

An array of objects brought in by the client side of an application that can be listened in on by a subscriber const simpleObservable = new Observable((observer) => { // observable execution observer.next("bla bla bla") observer.complete() }) // subscribe to the observable simpleObservable.subscribe()

is an array a collection

Arrays are simple constructs with linear storage of fixed size and therefore they can only store a given number of elements. Arrays are built into the core of Java language Not a collection

Switch statement

Better for comparing a single variable against many values switch(variableName) { case: 1: case: 2 case: 3 x=5 break default: x=0; }

Collection

Collection (interface) -> extends Iterable interface - List - Maintians insertion order - ArrayList - LinkedList - set - Unique Elements only - Tree Set - Hash Set - queue

Angular Component

Components are basically classes that interact with the .html file of the component, which gets displayed on the browser. We have seen the file structure in one of our previous chapters. The file structure has the app component and it consists of the following files − app.component.css app.component.html app.component.spec.ts app.component.ts app.module.ts

Injecting service

Declare as a parameter of the constructor list as an import

Thread Lifecycle

New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task. Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing. Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs. Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Error Handling

Servlet will return the error code if something goes wrong. If we are able to predict this then we can solve some problems with logic or provide custom feedback to make our application more user friendly

ServletConfig vs ServletContext

ServletConfig is specified for a particular servlet and are known to other servlets ServletContext is specified for an entire application outside of any particular servlet and are available to all the servlets within that application

Dependency Injection

The process in which one object provides the dependencies of another object Used to create loosely coupled classes

What is true of every service in angular

They have the @Injectable and do not display any information (are not formatted in html and css)

Servlet service()

This is the entry point of all servlet handling HttpServlet is an abstract class which implements this method by delegating to the appropriate doGet, doPost, etc. methods depending on the HTTP method used in the request Called each time a new request comes in from the client

Multi-threading

Threading can be useful in a single-processor system by allowing the main execution thread to be responsive to user input, while the additional worker thread can execute long-running tasks that do not need user intervention in the background. Threading in a multiprocessor system results in true concurrent execution of threads across multiple processors and is therefore faster. However, it requires more careful programming to avoid non-intuitive behavior such as racing conditions, deadlocks, etc.

TypeScript

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

Why are string immutable

Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed. Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues. Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object). Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

Spring Boot

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration. Features Create stand-alone Spring applications Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files) Provide opinionated 'starter' POMs to simplify your Maven configuration Automatically configure Spring whenever possible Provide production-ready features such as metrics, health checks and externalized configuration Absolutely no code generation and no requirement for XML configuration

Difference between an abstract class and an interface

Type of methods: Abstract classes can have abstract and not abstract methods while interfaces can only have abstract methods unless declared default Final Variables: Variables are declared in a java interface are by default final an abstract class may contain non-final variables Implementation: you can only extend one abstract class but can implement multiple interfaces Class extends Class (only 1) ConcreteClass extends AbstractClass AbstractClass extends ConcreteClass Class implements Interface, Interface (many) Interface extends Interface, Interface (many)

Upcasting and downcasting

Upcasting: casting a subtype to a supertype upwards in the inheritance tree Dog dog = new Dog(); Animal anim = (Animal) dog; anim.eat(); Dog -> Animal Downcasting: casting a supertype to a subtype Animal anim = new Cat(); Cat cat = (Cat) anim; Animal -> Cat

xml servlet tags

<servlet> <servlet-name></servlet-name> <servlet-class></servlet-class> </servlet> <servlet-mapping> <servlet-name></servlet-name> <url-pattern></url-pattern> <servlet-mapping> Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. It maps url patterns to servlets. When there is a request from a client, servlet container decides to which application it should forward to. Then context path of url is matched for mapping servlets.

Linter

A program that will strictly scrutinize code for potential errors

Concrete vs Abstract methods

An abstract method does not have an implementation in the abstract class definition. It is implemented in a concrete class concrete methods have a method body and are declared in a concrete class

Angular Directives

AngularJS directives are extended HTML attributes with the prefix ng- In Angular 4, directives allow you to attach behaviors to elements in the DOM Structural Directive: change the DOM layout by adding and removing DOM elements E.g. *ngIf Attribute Directive: change the appearance or behavior of an element, component, or another directive Component Directive: Think MyFirstComponent, components are component directives

AJAX

Asyncronous JS and XML Update a web page without reloading the page Request data from a server - after the page has loaded Receive data from a server - after the page has loaded Send data to a server - in the background

HttpClient

http-client lets you compose HTTP clients using JavaScript's fetch API. This library has the following goals: Preserve the full capabilities of the fetch API Provide an extendable middleware API Use the same API on both client and server https://github.com/mjackson/http-client http-client simplifies the process of creating flexible HTTP clients that work in both node and the browser. You create your own fetch function using the createFetch method, optionally passing middleware as arguments. Returns a status code

NPM

node package manager npm is a package manager for the JS programming language. It is the default package manager for the JS runtime environment Node.js it consists of a command line client, also called npm The npm registry can be accessed via the client and the available packages can be browsed and searched via the npm website made aware of which libraries are needed through the use of imports and NgModule

Data Binding

Data-binding in Angular apps is the automatic synchronization of data between the model and view components. Data binding lets you treat the model as the single-source-of-truth in your application. The view is a projection of the model at all times. If the model is changed, the view reflects the change and vice versa. Interpolation {{}} - Binds value directly to the view Property Binding[] - binds a property, given some predicate Event Binding() - Binds an expression to an event 2-way data binding [(ngModel)] - bind data in two directions

doGet vs doPost

DoGet 1)In doGet Method the parameters are appended to the URL and sent along with header information 2)Maximum size of data that can be sent using doget is 240 bytes 3)Parameters are not encrypted 4)DoGet is faster if we set the response content length since the same connection is used. 5)Thus increasing the performance 6)DoGet should be idempotent. i.e. doget should be able to be repeated safely many times 7)DoGet should be safe without any side effects for which user is held responsible DoPost 1)In doPost, parame ters are sent in separate line in the body 2)There is no maximum size for data 3)Parameters are encrypted 4)Dopost is generally used to update or post some information to the server 5)DoPost is slower compared to doGet since doPost does not write the content length 6)This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online 7)This method does not need to be either safe

Servlet lifecycle

Servlet class loading - the point where static data (if any) in your servlet are initialized Servlet instantiation - the point where instance data (if any) in your servlet are initialized, and the no-argument constructor (if present) is called. The servlet must be loaded and instantiated before the first request for it is processed. init() - the initialization method called when a servlet instance is created. service() - the method called to perform the work. The service() method convert HTTP requests into appropriate doXXX() method calls. destroy() - When a servlet instance is taken out of service, the destroy() method is called—only once for that instance. https://javajee.com/servlet-class-hierarchy-and-life-cycle

Scopes of a servlet

ServletRequest Duration of the request HttpSession While the client is active ServletContext The life of the web application

String vs StringBuilder vs StringBuffer

StringBuilder: allows the manipulation of a String but is not syncronized (not thread safe) - More efficient StringBuffer: allows the manipulation of a String but is syncronized (thread safe) - Can only be accessed by one method at a time - Less efficient than StringBuilder, more efficient than String

Angular Environments

The overall framework in which the angular application is constructed

doGet() / doPost() method signatures

public void doGet(HttpServletRequest req, HttpServletResponse resp) { doPost(req,resp); } public void doPost(HttpServletRequest req, HttpServletResponse resp) { //process the incoming request }


Kaugnay na mga set ng pag-aaral

Texas Government Chapter 1: The Political Culture, People, and Economy of Texas

View Set

Comm. The Essentials of Human Communication

View Set

science atmospheric pressure test

View Set