我是靠谱客的博主 心灵美啤酒,最近开发中收集的这篇文章主要介绍middleware中间件知识点总结Message-oriented MiddlewareJava Message ServiceJava Server PagesServletsJava SpringAspect Oriented ProgrammingConcurrencyJava Memory ModelThread SynchronizationSecurity Concepts for Middleware and Web VulnerabilitiesLayer of Securit,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Middleware

  1. Messaging

  • a method of communication between software components or applications.
  • distributed communication that is loosely coupled
  1. Types of Messaging Services

  • Short Message Service (SMS)
  • Instant Message Service (IMS)
  • Multimedia Message Service (MMS)
  • Google Cloud Messaging (GCM) Service
  • Oracle Messaging Cloud (OMC) Services
  • Java Messaging Service (JMS)

Message-oriented Middleware

  • MOM is a software or hardware that provides a communication channel between heterogeneous (/ˌhetərəˈdʒiːniəs/) applications platforms and systems by passing
    messages across between the communicating systems.

Advantages

  • Heterogeneous Integration

    从在不同的平台中实现的应用程序和系统调用服务

  • Reduce System Bottlenecks

  • Increase Scalability

Architecture

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cywXr7KC-1640202486664)(D:photophotolibraryimage-20211117095715025.png)]

MOM Client - Producer

  • is used by the client to produce a message
  • The message is then sent by the message producer
  • The message is usually sent to a physical destination which is written in the API using the destination object

Message Broker消息代理(Messaging Provider)

  • The broker is responsible for receiving and sending the message
  • The broker facilitates the connections between producers, administration services and consumers
  • The broker maintains a persistent data store to reliably send data
  • The broker provides secure connection using encrypted SSL authenticated connection.

MOM Client - Consumer

  • the message is automatically given to “Message Listener” object that is defined by the consumer

MOM Messaging Models

Point-to-Point

  • This is a model in which one sender sends a message to only one receiver at a time
  • It is a one-to-one relationship
  • Messages are sent to the particular address specified by the client

Publish/Subscribe

  • one sender sends one message that is received by many receivers or many messages are sent and are received by many receives

  • a one-to-many or many-to-many relationships

  • The sender and receiver of messages are decoupled

  • There is no need for the producer and consumers to be running at the same time


Types

  • Message Queuing
  • Publish / Subscribe

Types of Pub-Sub message

  • Topic-Based(基于主题)
    • It uses a hierarchical naming scheme(根据主题命名和分类)
    • It uses dedicated queues使用专用队列
    • It is too restrictive as it uses specific items
  • Content-Based(基于内容)
    • It does not use specific terms to describe the content(不像上面一样对information进行分类)
    • It is less restrictive as it does not use specific term s for subscriptions
  • Type-Based
    • Subscribers need to register for the type of message they want
    • It is also restrictive as subscribers need to register for the type of messages they want to subscribe

Types of Queuing Systems in MOM

  • FIFO(First-In-First-Out)
    • The first message sent will be the first to be received and the last will be the last to be received
  • FIFO with Priorities
    • It is the same as FIFO but the message sent/received depends on the priority set for the publisher and consumer
  • Journal Queue
    • The system keeps track and copy of all messages
  • Public Queue
    • It is open for access to all users
  • Private Queue
    • It requires authentication and authorization to use the queue
  • Connector / Bridge
    • This is a proxy to connect to commercial MOM’s queues

Java Message Service

What is JMS?

  • is a Java Application Programming Interface (API) that allows applications to create, send, receive and read messages
  • enables loosely coupled communication松散的通信 as well as Asynchronous communication异步通信
  • It is a Java API based on Java message-oriented middleware(M O M)

When to use JMS API

  • wants the components not to depend on information about components’ interfaces, so that components can be easily replaced (loose coupling)

    希望组件不依赖于有关组件接口的信息,可以被轻松替换

  • not all components are up and running simultaneously

    并非所有组件都同时启动并运行(即异步通信)

JMS API Architecture

JMS Provider

  • This is the messaging system which implements the JMS interfaces and provides administrative and control functionalities

    实现 JMS 接口

JMS Clients

  • These are Java programs or components that produce and consume messages

    产生和消耗消息的program

Messages

  • These are the objects that communicate information between JMS Clients

    这些是在 JMS 客户端之间传递信息的对象

Administered Objects

  • Preconfigured JMS objects created by an administrator for the use of clients

    由管理员为客户端使用而创建的预配置 JMS 对象

  • The two types of JMS administered objects are Destinations (D) and Connection Factories (CF)

    两类administered object, 目的地 (D) 和连接工厂 (CF)

JNDI Namespace(Java Naming and Directory Interface)

JNDI(Java Naming and Directory Interface,Java命名和目录接口)是SUN公司提供的一种标准的Java命名系统接口

  • This is a Java directory service API that allows Java program clients to discover and look up data and objects through a name.

JMS Messaging Domains(同MOM Message Model)

  • Messaging Domain信息定义域
    • Messaging domain is the concept of how message is published and consumed with regards to the systems used by the provider and clients.
  • Types of Java Messaging Domains
    • Point-to-point (PTP) messaging domain
      • based on the message queues, senders and receivers concept
    • Publish/Subscribe messaging domain
      • clients to address messages to a topic

Types of JMS Message Consumption

  • Synchronously
  • Asynchronously

JMS Programming Model

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ea6jhHqQ-1640202486670)(D:photophotolibraryimage-20211222170029784.png)]

Connection Factory

  • the object a client uses to create a connection with a provider
  • encapsulates a set of connection configuration parameters has been defined an administrator

Destinations

  • A destination is the object a client uses to specify the target of messages it produces and the source of message it consumes

Sessions

  • A session is a single threaded context for producing and consuming messages
  • use sessions to create message producers, message consumers and messages

Message Producers

  • A message producer is an object created by a session and is used for sending messages to a destination

Message Consumers

  • A message consumer is an object created by a session and is used for receiving messages sent to a destination
  • Use the receive method for both PTP and Pub/Sub to consume messages synchronously.

Message Listeners

  • A message listener is an object that acts as an asynchronous event handler for messages
  • onMessage method

Message Selectors

  • If your messaging application needs to filter the message it receives

Message

  • Message Header
    • A header consists of information about the message destination, message expiration time, message unique identification, message delivery mode (persistent or non-persistent) and message time stamp.
  • Message Properties
    • Consists of some information in the header
    • The properties are used to extend the functionality of the header
    • Programmers can create properties to describe the message they want to send or receive
  • Message Bodies
    • The body contents the message and how it will be sent and received

Example

  • Context -> Topic / Queue
  • Connection Factory -> Connection -> session -> sender / receiver / publisher / subscriber
Context ctx = new InitialContext();
//initialization
QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory)ctx.lookup("QueueConnectionFactory");

TopicConnectionFactory topicConnectionFactory = (TopicConnectionFactory)ctx.lookup(“TopicConnectionFactory”);
/产生ConnectionFactory/

//Using connectionFactory to lookup
QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();

TopicConnection topicConnection = topicConnectionFactory.createTopicConnection();
//create connection
/queueConnection/topicConnection创建成功/
    
    
Topic myTopic = (Topic) ctx.lookup(“MyTopic”);
Queue myQueue = (Queue) ctx.lookup(“MyQueue”);
/目的地的查找/

TopicSession topicSession = topicConnection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);
//create session
/会话创建成功/

QueueSender queueSender = queueSession.createSender(myQueue);//create sender
TopicPublisher topicPublisher = queueSession.createPublisher(myTopic);//create publisher
/发别创建QueueSender和TopicPublisher/

TextMessage message = queue/topicSession.createTextMessage();
queueSender.send(message);
topicPublisher.publish(message);
/分别向队列send消息和publish消息/

QueueReceiver queueReceiver = queueSession.createReceiver(myQueue);//create Receiver
TopicSubscriber TopicSubscriber = topicSession.createSubscriber(myTopic);//create Subscriber
/分别创建QueueReceiver和TopicSubscriber/

queueConnection.start();
Message m = queueReceiver.receive();
topicConnection.start(0);
Message m = topicSubscriber.receive(1000);
/启动connection,同步接收消息/

TopicListener topicListener = new TopicListener();
topicSubscriber.setMessageListener(topicListener);

TextMessage message = queueSession.createTextMessage();
Message.setText(msg.text);
queueSender.send(message);

package com.tgb.activemq;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * 消息的生产者(发送者) 
 * @author liang
 *
 */
public class JMSProducer {

    //默认连接用户名
    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL = ActiveMQConnection.DEFAULT_BROKER_URL;
    //发送的消息数量
    private static final int SENDNUM = 10;

    public static void main(String[] args) {
        //连接工厂
        ConnectionFactory connectionFactory;
        //连接
        Connection connection = null;
        //会话 接受或者发送消息的线程
        Session session;
        //消息的目的地
        Destination destination;
        //消息生产者
        MessageProducer messageProducer;
        //实例化连接工厂
        connectionFactory = new ActiveMQConnectionFactory(JMSProducer.USERNAME, JMSProducer.PASSWORD, JMSProducer.BROKEURL);

        try {
            //通过连接工厂获取连接
            connection = connectionFactory.createConnection();
            //启动连接
            connection.start();
            //创建session
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            //创建一个名称为HelloWorld的消息队列
            destination = session.createQueue("HelloWorld");
            //创建消息生产者
            messageProducer = session.createProducer(destination);
            //发送消息
            sendMessage(session, messageProducer);

            session.commit();

        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(connection != null){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    /**
     * 发送消息
     * @param session
     * @param messageProducer  消息生产者
     * @throws Exception
     */
    public static void sendMessage(Session session,MessageProducer messageProducer) throws Exception{
        for (int i = 0; i < JMSProducer.SENDNUM; i++) {
            //创建一条文本消息 
            TextMessage message = session.createTextMessage("ActiveMQ 发送消息" +i);
            System.out.println("发送消息:Activemq 发送消息" + i);
            //通过消息生产者发出消息 
            messageProducer.send(message);
        }

    }
}

Java Server Pages

JSP

  • JSP is used to implement the “View” part of MVC design pattern

Web

web server

  • The web server receives the request from clients
  • The web server looks for the resource that the client has requested for
  • finds the resource and sends back results of the request to clients

Client

  • The web client (Browser) allows the user to request for resources from the web server
  • displays the results of the resource obtained from the web server to the user

Tomcat

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CI19OgvG-1640202486671)(D:photophotolibraryimage-20211222113242577.png)]

Servlet

  • Controller

  • They take clients request and give back to clients response

  • use the HttpServletRequest and HttpServletResponse objects for serving clients

  • Servlets are managed by the Container

Java and Javabeans —model

  • Java/Java Beans 用于实现 Web 应用程序的业务逻辑

Web Container (Apache Tomcat)

  • Servlets are deployed in a container

这是因为 servlet 没有启动应用程序运行的main()方法

  • Functions

    • Support for JSP

      The container translates JSP codes to Java codes

    • Life-cycle management

      它控制 servlet 的启动和终止

    • Security

      它使用部署描述符(DD),即web.xml来声明身份验证和授权配置

    • Communication

      容器促进了 servlet/JSP 和 Web 服务器之间的通信

    • Multi-threaded support

      容器通过为每个 servlet 请求创建新线程来促进多线程通信和请求。

JSP Implementation

  • Java codes implemented within HTML is known as JSP
  • <% code %>

JSP Directives

  • @ page

    <%@ page import = "java.util.*" %>

  • @ include

    <%@ include file = "hello.jsp" %>

  • @ taglib

    <%@ taglib tagdir=“/WEB-INF/tags/foo” prefix=“foo” %>

    tagdir换成uri也可以

  • @ attribute

    <%@ attribute name=“<text>” required=“[Boolean]” rtexprvalue=“[Boolean]” %>

    rtexprvalue: 自定义标签属性(Run-time Expression Value)

    e.g. <%@ attribute name=“bookTitle” required=“true” rtexprvalue=“true” %>

JSP Expression

  • <%= new Date() %>等于<% out.printIn(new Date());%>
  • is converted to out.print(new Date());
  • 里面不要加;

JSP Declaration对象和变量的声明<%! %>

<%! Date myDate = new Date();
Date getDate() {
	System.out.println( "getDate() method" );
	return myDate;
}
%>

JSP Expression Language (EL)

  • EL always start with a $ followed by an open curly brace and the followed by an object or an attribute and then finally closed by a closing curly brace.
  • ${person[“name”]} / ${person.name}
  • EL handles “null” values by not printing them at all
  • 可能throw error
  • 无效值为0,可能出现infinity

For example ${man}will rint nothing

${89 + man}  <%-- will print 89 --%>
${89 / man} <%-- will print infinity--%>
{89 % man} <%-- will throw exception (error) --%>
${90 == man} <%-- will print false--%>

除了%(模)null不行,其他都可以!!!

Looping

<c:forEach var=“bookTitle” items=“${bookShelf}” >
${book}
</c:forEach>

Conditional Statements

<c:if test=“${studentNo le 2000} “ >
<jsp:include page =“student_bupt.jsp” />
</c:if>

<c:choose>/ <c:when> / <c:otherwise>

JSP-Configure Error Pages

<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/myErrorPage.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/myErrorPage.jsp</location>
</error-page>

这些JSP-Configure Error Pages 存在于deployment descriptor (DD)

JSP and Bean

  • JSP actions or tags are used with Bean to process forms
  • <jsp:useBean id=“ ” class=“” scope=“”/>
<jsp:useBean id=“student” class=“department.Student” 
scope=“session” />

使用JavaBean组件

  • <jsp:getProperty name=“student” property=“name” />
  • <jsp:setProperty name=“student” property=“Grade” value=“90%” />

Servlets

  • Are programs that run on web server acting as middle layer between HTTP request and databases or other applications.
  • Used to generate dynamic web pages in response to client.

Servlet Applications

  1. in conjunction with JSP to create clearer and simpler applications
  2. Providing web interfaces

What can servlets do

  • Read any data sent by the user
  • Look up info embedded in HTTP request

Calling servlet

  • executing a method of a servlet class instance, not looking at a page

Advantages of servlets

  • Efficient

    Servlets run in JVM. Each request is serviced using a thread rather than a new process

  • Convenient

  • Powerful

  • Portable

  • Secure

  • Inexpensive

Container

  • a program that receives requests to servlets from a web server application
  • manages the life cycle of its servlets

Servlet Life Cycle

  • Instantiates servlet
  • init()method is called
  • service()method is called (includingdoGet() doPost())
  • destroy()method is called

Deployment Descriptor (DD) Java web中为web.xml

  • Map servlet name with servlet class and URL pattern

更多知识

Servlet Lifecycle Methods

  • init()

    • Only once
  • service()

    • The container calls the method when it gets the request from a servlet.
  • destroy()

    • When the service method has finished

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5ksairlt-1640202486673)(D:photophotolibraryimage-20211222234220459.png)]

Config objects

  • ServletConfig对象
    • Each servlet has one ServletConfig每一个servlet都有一个ServletConfig对象
    • contains parameter’s from the server’s configuration file包含了server的配置文件的参数
    • Each servlet uses it to define deployment time information and parameters without hard coding them
    • It is used to access ServletContext
  • ServletContext
    • This is defined once for a whole single application
    • This is used to define web application parameters
    • It is configured in the DD and contains initialization parameters for the web application

e.g.

  • DD中有某个参数
// method 1
ServletContext ctx = getServletContext();
ctx.getParameter();
// method 2
out.println(getServletConfig().getInitParameter(“lecturersEmail”)
// method 3
public void init() throws ServletException {
	String initPath = getServletConfig().getInitParameter(“count_file”);
	System.out.println(initPath);
}

Output Objects

  • PrintWriter
    • This is used to print text to a character stream
PrintWriter pw = response.getWriter();  
pw.println(“My Test Servlet Output Text”);
  • OutputStream
    • This can print any output, text, html, bytes, etc
ServletOutputStream sos = response.getOutputStream();  
sos.write(“M Test Byte Array Outputs”);

Example

import javax.servlet.http.*;
import javax.servlet.*;
public class AnyHttpServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    response.setContentType("text/html");  
    PrintWriter out = response.getWriter();  
    out.println("<html>");     
}
    
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
};
}

Web Server:

Web server 是指能够接收,解析,处理HTTP请求,并将处理后的结果返回给合适的客户端(比如浏览器)的服务器。Example: Apache Web Server.

Web Container:

Web容器J2EE标准的实现,为servlet和jsp提供运行环境。例如,当一个HTTP请求通过要访问一个web组件(通常是一个servlet或者是jsp),通常是将这个请求转发给web container处理完毕后再返回到web serverTomcat是一个轻量级的web container

Java Spring

Functions

  • Supports all major application servers and JEE standards.
  • Handles the infrastructure so you can focus on your application.

Core container(核心容器)

  • The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.
  • The Bean module provides BeanFactory, which is a sophisticated implementation of the factory pattern.
  • The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module.
  • The SpEL module provides a powerful expression language for querying and manipulating an object graph at runtime

Data Access / Integration

  • he JDBC module provides a JDBC-abstraction layer that removes the need for tedious JDBC related coding.

Web

  • The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.

Why Spring

  • A primary purpose is to reduce dependencies and even introduce negative dependencies

Dependency Injection

  • An injection is the passing of a dependency (a service) to a dependent object (a client).

    注入是将依赖项(服务)传递给依赖对象(客户端) ,通过修改配置文件的方式给属性赋值

  • Dependency Injection helps to keep our classes as independent as possible.

    依赖注入有助于保持我们的类尽可能的独立

  • Increase reuse by applying low coupling

    增加了其低耦合性

Inversion of Control

  • Inversion of Control is a principle in software engineering by which the control of objects or portions of a program is transferred to a container or framework.

Bean

  • Two types
    • Singleton

      One instance of the bean created and referenced each time it is requested一次被创建后保存,可以再调用

    • Prototype

      New bean created each time每次都要重新创建

Bean Factory

  • Spring uses a BeanFactory to create, manage and locate “beans” which are basically instances of a class

    Spring 使用 BeanFactory 来创建、管理和定位“bean”,它们基本上是类的实例

  • Beans are created using constructors (mostly no-arg) or factory methods

    Bean 是使用构造函数(主要是无参数)或工厂方法创建的

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UbrLueq5-1640202486675)(D:photophotolibraryimage-20211219203043873.png)]

<ref bean=**>实现在一个bean中对另一个bean的引用

Examples

原本对象创建需要修改源代码↓:

public class ExampleBean {
	private AnotherBean beanOne;
	private YetAnotherBean beanTwo;
	private int i;
	public void setBeanOne(AnotherBean beanOne) {
		this.beanOne = beanOne; 
	}
	public void setBeanTwo(YetAnotherBean beanTwo) {
		this.beanTwo = beanTwo; 
	}
	public void setIntegerProperty(int i) {
		this.i = i; 
	}
}

现在只需要配置xml配置文件即可????:

<bean id="exampleBean" class="org.example.ExampleBean">
	<property name="beanOne"><ref bean="anotherExampleBean"/></property>
	<property name="beanTwo"><ref bean="yetAnotherBean"/></property>
	<property name="integerProperty"><value>1</value></property>
</bean>

Aspect Oriented Programming

  • AOP entails breaking down program logic into distinct parts called concerns.

    AOP将程序分割为很多关注点

  • The functions that span multiple points of an application are called cross-cutting concerns

    跨越应用程序多个点的功能称为横切关注点

Terminology

  • Aspect - Set of API for cross-cutting
  • Join point - A method invocation
  • Advice - Action to take at a join point
  • Point cut - A set of join points
  • Target - Object containing the join point

Types of Advices

  • before
  • after
    • after returning
    • after throwing
    • around
      • Run advice before and after the advised method is invoked

Examples

public class TrackOperation { // Aspect class
    @Pointcut("execution(* Operation.*(..))")
        public void k(){}//pointcut name
    @Before("k()")//applying pointcut on before advice
    public void myadvice(JoinPoint jp)//it is advice (beforeadvice)
    {
        System.out.println("additional concern");
    }
}

public class Operation {
	public void msg(){ System.out.println("msg method invoked");}
	public int m(){
        System.out.println("m method invoked"); 
        return 2;
    }
	public int k(){
        System.out.println("k method invoked");
		return 3;
    }
}

Concurrency

  • A process runs independently and isolated from other processes. It cannot directly access shared data in other processes.

    进程独立运行并与其他进程隔离。它不能直接访问其他进程中的共享数据。进程的资源,例如内存和 CPU 时间,通过操作系统分配给它

  • A thread is a so-called lightweight process. Each has its own call stack but can access shared data of other threads in the same process. Every thread has its own cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data

    线程是所谓的轻量级进程。每个都有自己的调用堆栈,但可以访问同一进程中其他线程的共享数据。每个线程都有自己的内存缓存。如果线程读取共享数据,它会将这些数据存储在自己的内存缓存中。一个线程可以重新读取共享数据

Life Cycle of a Thread

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XWxPoriJ-1640202486676)(D:photophotolibraryimage-20211223004405475.png)]

  • New
    • This is when the Thread instance is created using the “new Thread()” command. The thread is still not alive yet
  • Runnable
    • This is when the Thread instance variable invokes the “start()” method using the “t.start()” command, where t is the thread instance variable. The thread is now alive and has joined the queue of threads about to be executed
  • Running
    • This is when the Thread is now executing
  • Blocked / Waiting /Sleeping
    • This is when the Thread goes out of the execution or running mode when the wait, interrupt or sleep commands are executed
  • Dead
    • This is when the Thread completes its task terminates execution calling “t.destroy()” command for garbage collection.

Three concepts

  • Atomicity

    • An operation is said atomic when it cannot be interrupted.

      当一个操作不能被中断时,它被称为Atomicity,具有原子性

  • Visibility

    • This occurs when a thread must watch the actions of another thread(Whether the thread can be seen by others)
  • Order of execution

    • The order of execution is not guaranteed

Example

  • Method 1实现Runnable接口(可以再被继承下去)
class MyFirstRunnable implements Runnable 
{
	public void run() 
    {
        // in a thread
    }
}

public class MyFirstTest 
{
    public static void main () 
    {
        Thread thread = new Thread(new MyFirstRunnable());
        thread.start();
    }
}

使用隐式内部类的写法:

Thread t = new Thread(new Runnable() {
	public void run() 
    {
	
	}
} );
t.start();
  • Method 2继承Thread(不可以再被继承了)
public class MyThread extends Thread 
{
	public void run() 
    {
        
    }
    MyThread myThread = new MyThread();
    myThread.start();
}

Interrupt

  • An interrupt is an indication to a thread that it should stop what it is doing and do something else.

  • t.interrupt()

    A thread sends an interrupt (to another thread t) by invoking interrupt on the object to be interrupted

  • if the thread is sleeping or joining or waiting on another Thread

    • anInterruptedException is thrown.
    • and then the interrupted status of the Thread will be cleared
  • 用try catch 来 catch InterruptedException

Join等待被执行

  • Waiting for another thread to die
  • t.join();

Block被阻止运行了

  • A thread that is prevented from executing is said to be blocked.
    • It has been put to sleep for a set amount of time
    • It is suspended with a call to suspend()and will be blocked until a resume() message
    • The thread is suspended by call to wait(), and will become runnable on a notify or notifyAll message.

不同状态

  • If that thread is executing a low-level interruptible blocking method
  • Otherwise, interrupt() merely sets the thread interruption status.

InterruptedException是线程自己从内部抛出的,并不是interrupt()方法抛出的。对某一线程调用 interrupt()时,如果该线程正在执行普通的代码,那么该线程根本就不会抛出InterruptedException。但是,一旦该线程进入到 wait()/sleep()/join()后,就会立刻抛出InterruptedException

一个处于interrupt状态的thread

  • can be read with Thread.isInterrupted()
    • query other’s interrupt status
    • instance method
    • only looking
    • myThread.isInterrupted()
  • can be read and cleared in a single operation with Thread.interrupted()
    • static 只能 Thread.interrupted()
    • Only chech the current thread
    • and t**he interrupt status is cleared**

Terminate a Thread (3 ways)

  • The thread has finished the work it is designed to do, and exits the run()method naturally.
  • The thread has received an interruption signal, while doing its work.
    • It decides to not continue with work and exits the run() method.
  • The thread has been marked as daemon thread. When the parent thread who created this thread terminates, this thread will be forcefully terminated by the JVM.

线程安全

  • InterruptedException does not make your thread “interrupt safe”
  • 因为catch以后,线程状态不interrupt了,需要在catch block 里 Thread.currentThread().interrupt()
  • 可添加continue;

isAlive()

isAlive()returns true if the thread upon which it is called is still running - false otherwise.

You have no command to force a Thread to stop (in Java)

Daemon(保护措施,防止出现daemon)

  • setDaemon(false)
    • the Worker thread continues to run after main has finished.
  • setDaemon(true)
    • the Worker thread terminates when the main thread terminates

Java Memory Model

Stack

  • Not visible to other threads.
  • primitive types
  • may pass a copy of a primitive variable to another thread
  • local variable in object methods are on the stack

Heap

  • the object itself if stored on the heap
  • Static class variables are also stored on the heap

Some problems

Visibility

  • Visibility of thread updates (writes) to shared variables.
  • As long as the CPU cache has not been flushed back to main memory, the changed version of the shared object is not visible to threads running on other CPUs.
  • each copy sitting in adifferent CPU cache

Race conditions

  • A, B 读同一个, A改了,B也改了,A,B写回,不知道对方的修改
  • The variable has been incremented two times, once in each CPU cache.

Volatile

  • The value of this variable will never be cached thread-locally: all reads and writes will go straight to “main memory”;
  • += 不安全

Thread.yield()

  • yield stops the thread running continuously and gives some time back to the OS.

  • It just gives up the thread’s turn, and regains it in the next round.

    程序放弃执行, 下次再执行

如果一个thread在正常运行状态,interrupt不会throw exception

Critical sections关键区问题

  • The code segments within a program that access the same data from within separate, concurrent threads are known as critical sections
  • synchronized 关键字

Synchronized

  • 对method synchronized
  • 在method内 synchronized(this)
  • synchroniezed 某个 object
  • if 方法为static
    • the used lock is the Class object.
  • syn作用的对象是调用这个方法的对象,作用范围是函数

Fully Synchronizing objects

  • a class in which every method is synchronised

Thread Synchronization

Mutual exclusion

  • supported by object locks, enables multiple threads to independently work on shared data without interfering with each other.

Cooperation

  • supported by the wait and notify methods of class Object, enables threads to work together towards a common goal.

Monitor

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-SyoQ2i7p-1640202486678)(D:photophotolibraryimage-20211223034322750.png)]

Monitor has an entry set, a wait set and the owner

  • Suspended (sleeping) threads are shown as light grey circles.
  • If no other thread is waiting in the entry set and no other thread currently owns the monitor, the thread acquires the monitor and continues executing the monitor region.
  • When the thread finishes executing the monitor region, it exits (and releases) the monitor.
  • The only way a thread can move forward and execute the monitor region is by acquiring the monitor
  • The only way a thread can enter a monitor is by arriving at the beginning of one of the monitor regions associated with that monitor.

Active Thread

  • The active thread can release the monitor in either of two ways
    • it can complete the monitor region it is executing. If it completes the monitor region, it exits the monitor via the door five.
    • If it executes a wait command
      • releases the monitor and goes through door number three

流程

  • wait in the entry set
  • 等 owner完事
  • 如果owner没有指定notify,竞争
  • 进入owner
  • 若wait()
  • 进入wait set
  • 等待别人notify

Wait

  • If there is another thread currently claiming ownership of the monitor, the newly arrived thread must wait in the entry set, possibly along with other threads already waiting there.
  • wait() 让此线程 releases the monitor,进入monitor的wait set
  • a thread that currently owns the monitor can suspend itself inside the monitor by executing a wait command.

compete

  • If the (former) monitor owner did not execute a notify before it released the monitor (and none of the waiting threads were previously notified and were waiting to be resurrected), then only the threads in the entry set will compete to acquire the monitor.
  • If the former owner did execute a notify, then the entry set threads will have to compete with one or more threads from the wait set.
  • If a thread from the entry set wins the competition, it passes through door number two and becomes the new owner of the monitor.
  • If a thread from the wait set wins the competition, it exits the wait set and reacquires the monitor as it passes through door number four.

notify

  • When a thread executes a notify, it continues to own the monitor until it releases the monitor of its own accord, either by executing a wait or by completing the monitor region.
  • A notify command selects one thread arbitrarily from the wait set and marks it for eventual resurrection.

notifyall

  • marks all threads currently in the wait set for eventual resurrection.

Security Concepts for Middleware and Web Vulnerabilities

Security Concepts of middleware

  • Authentication mechanisms and credential management
  • Authorization and access control management
  • Shared data security and integrity
  • Secure one-to-one and group communication
  • Heterogeneous security/environment requirements support
  • Secure mobility management
  • Capability to operate in devices with low resources
  • Automatic configuration and management of these facilities

Loosely coupled connectivity

  • Using http
  • Multiple clients and servers interact independently
  • Distributed connections

Methods of securing web services

Authentication

  • Ensuring that it is the same person who she/he claims to be
  • Method
    • Something one has
      • Credentials issued by a trusted authority such as smart card
    • Something one knows
      • password
    • Something one is
      • Biometric information (fingerprint)
  • A strong authentication process consists of at least two of the above

Authorisation

  • Access control
    • Granting access to specific resources based on an authenticated user’s entitlements
    • Entitlements are defined by one or several attributes.
      • An attribute is the property or characteristic of a user
        • Admin role, quest role, authorisation request, etc

Confidentiality (保密)

  • Privacy
  • Keeping information secretive
    • reat web service request, email, identity of the sending and receiving parties in a confidential manner
    • To achieve confidentiality and privacy
      • Encrypt the content of a message
      • Do not reveal sending and receiving parties’ identities
      • Use public key infrastructures (PKI) for encryption

Integrity (一致性)

  • Message in transit should not be altered
    • Sender should digitally sign the message.
    • A digital signature is used to validate the signature.
    • The timestamp in the signature prevents anyone from replaying this message after the expiration.
    • Exchanging security tokens in a trusted environment

Layer of Security

Transport-layer security

  • Secure Socket Layer (SSL), also known as Transport Layer Security (TLS)
    • Authentication between communicating two trusted parties
    • Confidentiality through data encryption
    • Message integrity by checking that the data is not corrupted
    • Secure key exchange between client and server

Application-layer security

  • Application-level security complements transport-level security
  • Application-level security is based on XML frameworks defining confidentiality, integrity, authenticity; message structure; trust management and federation.
  • Data confidentiality is implemented by XML Encryption.
    • XML Encryption defines how digital content is encrypted and decrypted, how the encryption key information is passed to a recipient, and how encrypted data is identified to facilitate decryption.
  • Data integrity and authenticity are implemented by XML Signature.
    • XML Signature binds the sender’s identity (or “signing entity”) to an XML document. Signing and signature verification can be done using symmetric or symmetric keys.

Middleware-layer security

  • Middleware layer security ensures that the communicating security layers are secure
  • Single Sign-On (SSO) systems are used for authentication across the layers
  • Certificate-based SSO are common in middleware security systems
  • Virtual organisation membership services (VOMS) are used fore authentication/authorisation for different users belonging to different organisations

Web Security Vulnerabilities (脆弱点)

  • Web security Vulnerabilities are areas of weakness in web security that hackers or intruders exploit / access to systems

Vulnerabilities

  • Injection flaws
    • Injection flaws result from failure to filter untrusted input.
    • It can happen when you pass unfiltered data to the SQL server (SQL injection), to the Lightweight Directory Access Protocol (LDAP) server (LDAPInjection), etc.
    • The attacker can “inject” commands to these entities, resulting in loss of data and hijacking clients’ browsers.
    • Prevention
      • Adopting highly skillful programming and encryption techniques plus vigorous testing procedures
      • Updating browsers regularly
  • Broken Authentication
    • Password that is not encrypted
    • URL that exposes the session ID
    • Prevention
      • Use a tested framework (e.g. J2EE) or implement your code to prevent this happening
  • Cross Site Scripting
    • Simple input on a form that contains malicious links
    • Posting cookies to hackers
    • Prevention
      • Do a thorough data cleaning and sanitisation for all inputs
      • Do not return HTML tags to the client
  • Insecure Direct Object Reference
    • Resetting passwords from an insecure environment
    • Exposing codes during download to unauthorised users
    • Prevention
      • Secure source codes and password resetting environment
      • Virtual key-boards usage
  • Security Misconfigurations
    • Using default passwords and keys on production systems
    • Using outdated applications
    • Prevention
      • Automate security configurations
  • Sensitive data exposure
    • Not using SSL (Secure Socket Layer) in Tomcat security tag of deployment descriptor
    • Prevention
      • Enforce confidentiality and data integrity security features
      • Use SSL and encryption applications
  • Problem with access control level
    • Failure to implement correct authorisation system
    • Failure to implement correct authorisation system
      • Automate authorisation system
      • Ensure authorisation is always enforced on the server side
  • Cross Site Request Forgery (CSRF)
    • A third party browser that is not authentic can deceive you to enter sensitive details
    • This is some times called the “Confused Deputy” problem
    • Prevention
      • Do not click on URLs that are suspicious
  • Unvalidated Redirects and Forwards
    • Web programmers usually redirect URLs when a company changes its website or when working with third parties
    • Prevention
      • Do not redirect or forward URLs in your applications

IoT Protocols

Representational State Transfer (REST)

  • REST specification says that all interfaces must be uniform based on the concept of exchanging resources between the client and the server
  • Communication should be stateless and each request from client to server must contain all the information needed (data, metadata, etc)

IoT Protocols

HTTP

  • It’s major function is to implement the request and response functionalities of web applications

  • It is typically used in a client-server applications

  • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-45AkBERL-1640202486680)(C:UsersYuboAppDataRoamingTyporatypora-user-imagesimage-20201214003953278.png)]

TCP/IP

  • Set of computer networking communication protocols
  • It is used for internet communications
  • It is an end-to-end communication protocol
    • Internet layer
      • Sends packets of data from the source network to single or multiple destination networks
      • use IP Address
      • The concept of sending packets of data across is known as “packet routing
    • Transport Layer
      • It is a connection-oriented end-to-end message transmission layer
      • It provides reliable data transmission that
        • in the order
        • without error
        • failed, resent
        • flow control
        • no duplication
    • Application layer
      • This consists of other application specific protocols
      • FTP HTTP SMTP…

UDP

  • It is a connectionless-oriented communication transmission protocol
  • Not reliable
  • Transmitting data that accuracy and reliability are not necessary

SOAP

  • Simple Object Access Procotol
  • It is a specification for exchanging structured data across the web as web services
  • uses the application layer protocols
  • uses the XML syntax
  • good features
    • Neutrality
    • Non-platform dependence
    • Scalability and extensibility

FTP

  • File Transfer Protocol
  • is a standard network protocol used to transfer computer files from one host to another host over a TCP-based network

SSH-Secure Shell

  • It is the most popular communication and login protocol for UNIX (Linux) systems
  • It encrypts data and communication/login information
  • It uses the public key infrastructure (PKI) cryptography technology for authentication
  • port 22

MQTT

  • Message Queue Telemetry Transport
  • It is based on the publish-subscribe messaging service model
  • It uses brokers that publish messages

DDS-Data Distribution Service

  • This is a machine-to-machine (M2M) middleware standard
  • It enables reliable exchange of data between heterogeneous systems used by cloud service providers and subscribers
  • It works on a real-time basis to manage dynamic data exchange and communication in cloud systems

AMQP-Advanced Message Queuing Protocol

  • MOM middlware protocol
  • In enables heterogeneous clients and servers to communicate using point-to-point or publish-subscribe messaging methods

RTPSP – Real Time Publish-Subscribe Protocol

  • It is a message oriented protocol
  • It works on delivering real-time message exchange services using the publish-subscribe method
  • Cloud-based messages use RTPSP to exchange data between heterogeneous systems

SSL/TLS-Secure Socket Layer/ Transport Layer Security

  • These are cryptographic protocols for secure communication over the internet
  • They use digital certificates for authentication
  • They implement data confidentiality and data integrity

NTP-Network Time Protocol

  • It is a global networking protocol for synchronising time zone settings on computer systems
  • It stabilises the variations in network latency for distributed systems communicating with each other
  • Not secure

IMAP-Internet Message Access Protocol

  • This protocol enables users to retrieve their emails and also for data storage
  • It is an internet application layer protocol
  • allows multiple users to simultaneously access the same mailbox

LDAP-Lightweight Directory Access Protocol

  • It is an application layer protocol
  • It used for accessing distributed directory information services over TCP/IP network
  • most popular tools to share and use information records
  • Is used to manage large scale authentication and authorisation systems for distributed cloud systems

JavaScript

  • dynamic programming language

Data Types

  • Objects

    • They are written within curly braces ({})
    • var student = {surName:”Wang”, firstName:”Liu”, age:20};
    • Constructor
      • Creating objects with the “new” operator key word
      • The “new” key word must be followed by a function invocation
    • var arr = new Array(); / var obj = new Object();
  • typeof to get type

    • typeof 23

functions

function fName (para1, para2) {
    return v;
}

DOM

  • getElementById()
    • Use this property to get the contents of the element
    • 函数
  • innerHTML
    • This method access an HTML element via the id of the element
    • 属性
<html>
    <body>
        <p id="myElement"></p>
       	<script>
            document.getElementById("myElement").innerHTML="Hello World!";
        </script>
    </body>
</html>
  • Nodes
<div id="div1">
    <p id="p1">This is a paragraph.</p>
    <p id="p2">This is another paragraph.</p>
</div>
<script>
    var para = document.createElement("p");
    var node = document.createTextNode("This is new.");
    para.appendChild(node);
    var element = document.getElementById("div1");
    element.appendChild(para);
</script>
  • parent.removeChild(child);

  • appendChild(node) - 插入新的子节点(元素)

  • removeChild(node) - 删除子节点(元素)

  • Nodes List

    • getElementsByTagName()

    • var myNodeList = document.getElementsByTagName("p");

      document.getElementById(“myNodes").innerHTML = myNodeList.length;

Classes

  • JavaScript classes are based on JavaScript prototypes and inheritance
  • a class is a set of objects that inherit properties from the same prototype object
  • function as a constructor
<!DOCTYPE html>
<html>
    <body>
        <p id=“classExample"></p>
        <script>
            function Person(first, last, age) {
                this.firstName = first;
                this.lastName = last;
                this.age = age;
            }
            Person.prototype.nationality = “Chinese";
            var myFather = new Person(ZHANG", “Wang", 18);
            document.getElementById("classExample").innerHTML = "My father is " + myFather.nationality;
        </script>
    </body>
</html>

构造方式1:

person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";

构造方式2:

person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};

构造方式3:

function person(firstname,lastname,age,eyecolor)
{
    this.firstname=firstname;
    this.lastname=lastname;
    this.age=age;
    this.eyecolor=eyecolor;
}

var myFather=new person("John","Doe",50,"blue");
var myMother=new person("Sally","Rally",48,"green");

OOJSP(Object-Oriented JavaScript Programming)

JavaScript对象

  • userObject.lastLoginTime = new Date();
    alert(userObject.lastLoginTime);
    

    等于

    userObject["lastLoginTime"] = new Date();
    alert(userObject["lastLoginTime"]);
    

    .和用[]效果一样

  • 用 . 或者 [] 访问object的某个属性

  • Function as a constructor

    • var func = new Function("x", "alert(x);");
      func(“My Third Function");
      

IO in JS

  • Input

    • promot

      prompt() 方法用于显示可提示用户进行输入的对话框。

    • stdln

  • Output

    • alert
    • stdOut
  • e.g.

    • var strInput = WScript.StdIn.ReadAll();
      WScript.StdOut.Write(strInput)
      
 var name=prompt("Please enter your name","")
  if (name!=null && name!="")
    {
    document.write("Hello " + name + "!")
    }

Cookies

  • Cookies are functionalities in web-browsers that enable data and information about web activities to be saved for future reference

  • 3 types of cookies

    • Session cookies

      会话cookie

      • Created on the same browser that a user is using

        在用户使用的同一浏览器上创建

      • Created to last for that session

        创建为该会话持续

    • First party cookies

      第一方cookie

      • Created on the same browser that a user is using

        在用户使用的同一浏览器上创建

    • Third party cookies

      第三方cookie

      • Can be created by only a third party browser and not the current browser being used by the user

        只能由第三方浏览器创建,不能由用户当前使用的浏览器创建

jQuery

  • jQuery is an JavaScript cross-platform library and APIs

    jQuery 是一个 JavaScript 跨平台库和 API

  • It is used to simply client-side programming with HTML

    它用于使用 HTML 进行简单的客户端编程

  • consists

    • DOM element selections

      元素选择

    • DOM manipulation

      元素操作

    • Events

    • AJAX

    • JSON parsing

  • <script src="jquery.js"></script>

  • Basic syntax is: $(selector).action()

  • $(this).hide() - hides the current element.
    $("p").show() - show all <p> elements.
    $("p").fadein() - fade effects for all <p> elemens.
    

JSON

JSON: JavaScript Object Notation(JavaScript 对象表示法)

JSON 是存储和交换文本信息的语法,类似 XML。

JSON 独立于语言:JSON 使用 JavaScript语法来描述数据对象,但是 JSON 仍然独立于语言和平台。

  • JavaScript Object Notation
  • two structures
    • A collection of name/value pairs
    • An ordered list of values
<script type="text/javascript">
    var cart = {
        "orderID": 12345,
        "shopperName": "John Smith",
        "shopperEmail": "johnsmith@example.com",
        "contents": [
            {
                "productID": 34,
                "productName": "SuperWidget",
                "quantity": 1
            },
            {
                "productID": 56,
                "productName": "WonderWidget",
                "quantity": 3
            }
        ],
        "orderCompleted": true
    };
</script>

Create and read JSON Strings from JS

  • Create JSON string

    • JSON.stringify(jsonvar)

      使用 JSON.stringify() 方法将 JavaScript 对象转换为字符串。

      var obj = { "name":"runoob", "alexa":10000, "site":"www.runoob.com"};
      var myJSON = JSON.stringify(obj);
      document.getElementById("demo").innerHTML = myJSON;
      
  • Read a JSON string

    • JSON.parse(jsonstr)

      使用 JSON.parse() 方法将数据转换为 JavaScript 对象。

      var obj = JSON.parse('{ "name":"runoob", "alexa":10000, "site":"www.runoob.com" }');
      

Create JavaScript to Display Dates

<script>
    var currentDate = new Date(),
    day = currentDate.getDate(),
    month = currentDate.getMonth() + 1,
    year = currentDate.getFullYear();
    document.write(day + "/" + month + "/" + year)
</script>

JS attributes

  • Object Attributes

    • Every object has an associated prototype, class and extensible attributes
  • Prototype attributes

    • This specifies the object from which it inherits properties

    • var p={x:1}; // define a prototype object
      var o=Object.create(p); // create an object with that prototype
      p.isPrototypeOf(o); // => true: o inherits from p
      Object.prototype.isPrototypeOf(o); // => true: p inherits from Object.prototype
      

      !!! var a=Object.create(p)//以p为原型创建对象

  • Class Attributes

    • An object’s class attribute is a string that provides information about the type of of the object.

    • Classof(null); // => “Null”
      Classof(2); // => “Number”
      Classof(false); // => “Boolean”
      Function f(); //=> “Window”
      

RegExp

  • A regular expression (RegExp) is an object that describes a pattern of characters
  • var pattern=new RegExp(“t$”);
  • var re = /ab+c/;

rules

匹配

  • […] 任意一个
  • [^…] 非任意一个
  • . 任意, 匹配除换行符(n、r)之外的任何单个字符
  • d ASCII digit [0-9]
  • * 任意

重复

  • + 1或多个
  • {n, m} n到m次 闭
  • {n,} 大于等于n
  • {n} 等于n次
  • ? 可选

RegExp object

  • methods

    • exec()
      • execute on the string to match the pattern
    • test()
      • takes a string argument and returns true if the string is in the pattern else false
  • Modifier

    • pattern = /java/modifier;

    • /java/i

    • ModifierDescription
      gPerform a global match全局匹配
      iPerfoam case-insensitive matching不分大小写匹配
      mPerform multiline matching多行匹配

OSGI(Open Service Gateway Initiative)

。OSGI的解释就是Open Service Gateway Initiative,直译过来就是“开放的服务入口(网关)的初始化”,听起来非常费解,什么是服务入口初始化?

  • 我们对一个项目进行模块化分解之后,我们就可以把不同模块交给不同的开发人员来完成开发,然后项目经理把大家完成的模块集中在一起,然后拼装成一个最终的产品。
  • 但是我们在开发过程中,我们模块之间还要彼此保持联系,比如A模块要从B模块拿到一些数据,而B模块可能要调用C模块中的一些方法(除了公共底层的工具类之外)。所以这些模块只是一种逻辑意义上的划分。
  • 最重要的一点是,我们把最终的项目要去部署到tomcat或者jBoss的服务器中去部署。那么我们启动服务器的时候,能不能关闭项目的某个模块或功能呢?很明显是做不到的,一旦服务器启动,所有模块就要一起启动,都要占用服务器资源,所以关闭不了模块,假设能强制拿掉,就会影响其它的功能。
  • 我们做软件开发一直在追求一个境界,就是 模块之间的真正“解耦”、“分离”,这样我们在软件的管理和开发上面就会更加的灵活,甚至包括给客户部署项目的时候都可以做到更加的灵活可控。

现在我们的OSGI技术就可以满足我们之前所说的境界:在不同的模块中做到彻底的分离,而不是逻辑意义上的分离,是物理上的分离也就是说在运行部署之后都可以在不停止服务器的时候直接把某些模块拿下来,其他模块的功能也不受影响。

Definition: Modular specifications for the Java programming language

(Java 编程语言的模块化规范)

面向服务的平台(service-oriented platform),为 Java 规范实现动态和分布式组件模型(dynamic and distributed component model for Java specifications)

Terminologies术语

  • Component组件
    • A web resource, web service, module or software package that communicates with other interacting components using its **interface**使用其接口与其他交互组件进行通信的 Web 资源、Web 服务、模块或软件包
    • Modular and cohesive implementation of services服务的模块化和内聚实施
  • Bundles包--------一个模块
    • OSGi components implemented by OSGi developers Bundles是由 OSGi 开发人员实现的 OSGi 组件(component)
    • A complete component software that can operate on its own一个完整的组件软件,可以独立运行
    • An embedded software that is shipped with hardware or other applications硬件或其他应用程序一起提供的嵌入式软件
  • Modules模块
    • Comes from modular programming concept源自模块化编程理念
    • The implementation of a particular functionality of a program实现程序的特定功能
    • Other modules or parts of the program can call it using its interface if they implement acceptable interface rules to each other如果程序的其他模块或部分实现了彼此可接受的接口规则,则可以使用其接口调用它
  • Services
    • Comes from service-oriented programming concept源自面向服务的编程理念
    • Reusable functionalities of software instances using service-oriented architecture and interfaces使用面向服务的架构和接口实现功能的可重复使用
  • POJI
    • Plain Old Java Interface (POJI)
    • The native definition of java interface as used in J2SE (Java 2 Standard Edition)
  • POJO
    • Plain Old Java Object
    • The native definition of java objects as used in J2SE (Java 2 Standard Edition)

OSGI Architecture

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hZk2sUYG-1640202486682)(D:photophotolibraryimage-20211221200840832.png)]

  • It is based on a layered model是一个分层模型

  • Each layer is a bundle每一层是一个bundle

  • Each bundle implements interfaces that communicates and interacts with its neighboring bundles每个包都实现了与其相邻包进行通信和交互的接口

  • Bundles

    • They are the OSGI components written by Java developers based on the OSGI specifications

      , OSGI 核心组件

  1. Services

  • This layer connects each bundle dynamically through a publish-find-bind model for POJO s

    layer, 为POJO, 动态地连接每个包, 通过publish-find-bind模型

  1. Services Registry

  • This is the API for management services that register services and tracks down services based on their unique service references

    API,用于管理service. 等级注册服务并根据其唯一的服务引用跟踪服务

  1. Life-Cycle

  • The application programming interface (API) that allows bundles to be remotely installed, stopped, started, updated, uninstalled on the fly without restarting the services

    API,允许远程安装、停止、启动、更新和卸载包,而无需重新启动服务

  1. Modules

  • This layer defines how a bundle can import and export codes

    layer, 这一层定义了 bundle 如何导入和导出代码

  1. Security

  • The security layer that handles authentication, authorisation and protection of bundles

    layer, 处理bundle的身份验证、授权和保护

  1. Execution Environment

  • This layer defines the methods and classes that are available for a specific platform(JVM, OS, etc.)

    layer, 该层定义了可用于特定平台的方法和类

Types

  • There are commercial and open-source implementations of the OSGi specification framework

OSGi Deployment

  • Bundles are deployed on the OSGi Framework

    • OSGi Framework is the collaborative runtime environment of OSGi OSGI框架OSGI的协作运行时环境

    • The framework has imports and exports capabilities to start bundles without the need for them to load classes

      OSGI框架无需加载类class, 即有导入/导出启动包的能力

  • Bundles run on the same virtual machine (VM) during deployment, sharing codes coming from modules

    共享来自module的**代码和运行时环境**

Advantages of using OSGI

  • Reduces complexity for developers as bundles hide their implementation details and developers just need to use their APIs

    降低开发人员的复杂性,因为捆绑包隐藏了他们的实现细节,开发人员只需要使用他们的 API

  • Allow reuse of the modules and bundles which can save time

  • OSGi framework adopts a dynamic addition and removal of bundles, hence is a real-world model

    OSGi 框架采用动态添加和删除包,因此是一个**real-world model**

  • Ease of deployment and dynamic updates

    易于部署且动态更新

  • secure

    安全

  • It’s well supported by many companies like Oracle, IBM, etc.

Client Server Network Programming

  • Socket
    • 不是clientsocket!
  • ServerSocket

Java Client Code

public class NetworkClient 
{
    public static void main(String args[]) 
    {
        try {
            Socket s1 = new Socket("127.0.0.1", 999);
            BufferedReader br = new BufferedReader(new InputStreamReader(s1.getInputStream()));
            System.out.println(br.readLine());
            br.close();
            s1.close();
        } catch (ConnectException conExc) {
            System.err.println("Could not Connect to the server,");
        } catch (IOException e) {}
    }
}

Java Server Code

public class NetworkServer
{
	public static void main(String args[]) 
    {
        ServerSocket s2 = null;
        try 
        {
            s2 = new ServerSocket(999);
        } catch (IOException e) 
        {
            e.printStackTrace();
        }
        while (true) 
        {
            try 
            {
                Socket s3 = s2.accept();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s3.getOutputStream()));
                bw.write("Hello Network World!");
                bw.close();
                s2.close();
            } catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

Client and Server Middleware

Three-tier systems三层系统

image-20211219121314146
  • client
  • server
  • database

应用程序的交互方式

  • peer to peer communication

    点对点通信, 任一应用程序都可以发起通信

  • Publish subscribe

    e.g. AMQP- Advanced Message Queuing Protocol

    • 客户端和订阅者是**decoupled**[解耦]的 他们不需要知道他们是谁
    • MOM(Message-Oriented Middleware)处理他们之间的交互

Remote communication Models

  • TCP / UDP

  • RMI (Remote Method Invocation)

    远程方法调用

  • HTTP

    使用 HTTP 的客户端和 Web 服务器通信

  • Web Services

    Data structures passed over the wire

  • Publish Subcsribe Message Oriented Middleware

    • 异步 Asynchronous
    • 交付保证 Delivery assurances

File reading

  • File->FileInputStream->BufferedInputStream

  • File->FileReader->BufferedReader

  • File->FileWriter->BufferedWriter

  • BufferedOutputStream.flush()

    • forces any buffered output bytes to be written out to the underlying output stream

      强制写出任何缓冲的输出字节 到底层underlying输出流

    • suspends processing till the output is actually delivered

      暂停processing,直到实际交付输出

  • String line = theInput.readLine()

Socket reading

  • socket.getOutputStream() -> OutputStreamWriter -> PrintWriter / BufferedWriter

HTTP

Header请求头部

  • Accept-Encoding**接受的语言**
    • The web server then can send the HTML output in a compressed format.
  • Accept-Language**接受的编码方式**
    • This header displays the default language setting of the user. If a website has different language versions, it can redirect a new surfer based on this data.
  • Host**对象所在的主机。被 Web 代理高速缓存所需要。**
    • An HTTP Request is sent to a specific IP Addresses.
    • But since most servers are capable of hosting multiple websites under the same IP, they must know which domain name the browser is looking
      for.
  • User-Agent**告诉 Web 服务器,浏览器使用的类型**
    • Browser name and version.
    • Operating System name and version.
  • If-Modified-Since**是否已被缓存**
    • If a web document is already cached in your browser, and you visit it again, your browser can check if the document has been updated by sending this
    • If it was not modified since that date, the server will send a “304 Not Modified” response code, and no content - and the browser will load the content from the cache.
  • Authorization**如果要求验证, 浏览器会打开登录窗口**
    • When a web page asks for authorization, the browser opens a login window
    • 用户名和密码被加密
    • The data inside the header is base64 encoded
  • Status Codes**状态代码, 反映状态**
    • 200’s successful
    • 300’s are for redirections
    • 400’s are used if there was a problem with the request
    • 500’s are used if there was a problem with the server
  • Content-Length**内容长度**
    • This is especially useful for file downloads. That’s how the browser can determine the progress of the download.

Communication with remote objects

  • CORBA common object request broker

    普通对象访问代理,即通过代理访问对象

  • DCOM distributed component object model

    对象模型的分布组成,即对象为分布式,直接在局部寻找对象

  • RMI Remote Method Invocation

    RMI(Remote Method Invocation)为远程方法调用,是允许运行在一个Java虚拟机的对象调用运行在另一个Java虚拟机上的对象的方法。 这两个虚拟机可以是运行在相同计算机上的不同进程中,也可以是运行在网络上的不同计算机中。

    我们知道远程过程调用(Remote Procedure Call, RPC)可以用于一个进程调用另一个进程(很可能在另一个远程主机上)中的过程,从而提供了过程的分布能力。Java 的 RMI 则在 RPC 的基础上向前又迈进了一步,即提供分布式对象间的通讯。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vuPhxyeB-1640202486683)(D:photophotolibraryCenter.jpeg)]

  • Remote Method Invocations

  • Stub is a client that invokes a TCP connection to the skeleton

    Stub (桩)占位程序, 是调用 TCP 连接到skeleton(骨干网)的client

    占位程序扮演着远程服务器对象的代理的角色,使该对象可被客户激活。

    • present the same (remote) interface as S, so from the perspective of C the stub is equivalent to S.

      present the same interface from remote

    • work with JVM 1 & RMI system on machine 1 to serialize any arguments to the method calls and send this information to machine 2

      占位程序使用JVM 1, 经由RMI系统serialize函数调用参数, 发送给机器2(服务器 )

  • The skeleton is a server listening for TCP request

    skeleton(骨干网)是一个监听TCP请求的服务器

    • be able to receive remote method calls for S and their parameters, and with the JVM and RMI system on machine 2 deserialize them.

      获取函数调用的请求和参数, 使用骨干网的JVM和RMI系统deserialize传来的参数

    • Invoke the appropriate Methods on S with these arguments

      使用deserialize的参数调用对应的方法

Microservices

Definition

  • Microservices are software services that are small in size, messaging-enabled, autonomously developed, independently deployable, decentralized and built and released with automated processes.

    微服务是规模小、支持消息传递、自主开发、可独立部署、分散并通过自动化流程构建和发布的**软件服务。**

  • Microservice architecture is a variant of the service-oriented architecture (SOA) which arrange an application as a collection of loosely coupled services.

    Microservice 是 service-oriented architecture 的一种变体,它将应用程序安排为一组 loosely coupled 服务。

  • Microservices are an architectural and organizational approach to software development where software is composed of small independent services that communicate over well-defined APIs.

Microservice 由小型独立服务组成,他们通过well-defined API通信

  • These services are owned by small, self-contained teams.
  • Microservices architectures make applications easier to scale and faster to develop, enabling innovation and accelerating time-to-market for new features.

Benefits of Microservices

  • Modularity

    模块化

    • This makes the application easier to understand, develop, test, and become more resilient to architecture erosion.

      这使应用程序更易于理解、开发、测试,并且对架构侵蚀更具弹性。

  • Scalability

    可扩展性

    • Since microservices are implemented and deployed independently of each other, i.e. they run within independent processes, they can be monitored and scaled independently.

      由于微服务的实现和部署彼此独立,即它们在独立的进程中运行,因此可以独立监控和扩展。

  • Integration of heterogeneous and legacy systems

    异构heterogeneous和遗留legacy 系统的集成,也就是可以对老旧的异构、遗留系统集成改造

    • Microservices is considered as a viable mean for modernizing existing monolithic software application.
  • Distributed development

    分布式开发

    • it parallelizes development by enabling small autonomous teams to develop, deploy and scale their respective services independently.

      它使小型自治团队能够独立开发、部署和扩展各自的服务,从而实现并行开发。

Examples

  • Spring Cloud

    • Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, intelligent routing, global locks, leadership election, distributed sessions, cluster state).

      Spring Cloud 为开发人员提供了快速构建分布式系统中一些常见模式的工具

      • Coordination of distributed systems can be challenging and using Spring Cloud developers can quickly stand up services and applications that implement apps that are easy to manage.

        分布式系统的协调可能具有挑战性,使用 Spring Cloud 开发人员可以快速建立实现易于管理的应用程序的服务和应用程序。

  • AWS API Gateway

    亚马逊云计算

    • Amazon API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale.

      Amazon API Gateway 是一项完全托管的服务,可让开发人员轻松创建、发布、维护、监控和保护任何规模的 API。

      • APIs act as the “front door” for applications to access data, business logic, or functionality from your backend services.

        API 充当应用程序从后端服务访问数据、业务逻辑或功能的“前门”。

      • Using API Gateway, you can create RESTful APIs and WebSocket APIs that enable real-time two-way communication applications.

        使用 API Gateway,您可以创建支持实时双向通信应用程序的 Restful API 和 Web Socket API。

  • AWS Cloud9

    • AWS Cloud9 is a cloud-based integrated development environment (IDE) that lets you write, run, and debug your code with just a browser.

      基于云的集成开发环境integrated development environment (IDE)

      • It includes a code editor, debugger, and terminal.
      • Since your Cloud9 IDE is cloud-based, you can work on your projects from your office, home, or anywhere using an internet-connected machine.
      • 不需要配置环境,支持主流语言e.g.
  • AWS Lambda

    • AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume.

      AWS Lambda 让您**无需预置或管理服务器**即可运行代码。您只需为消耗的计算时间付费。

      • With Lambda, you can run code for virtually any type of application or backend service - all with zero administration.
  • AWS SQS**(Simple Queue Service)**

    • mazon Simple Queue Service (SQS) is a fully managed message queuing service that enables you to decouple and scale microservices, distributed systems, and serverless applications.

      AWS SQS 是一种完全托管的消息队列服务,使您能够解耦和扩展微服务、分布式系统和无服务器应用程序。

  • AWS SNS

    • Amazon Simple Notification Service (Amazon SNS) is a fully managed messaging service for both application-to-application (A2A) and application-to-person (A2P) communication.

      AWS SNS是一种完全托管的消息通知传递服务,适用于应用程序到应用程序 (A2A) 和应用程序到个人 (A2P) 的通信。

Spring Cloud

  • Spring Cloud focuses on providing good out of box experience for typical use cases and extensibility mechanism to cover others.

    Spring Cloud 专注于为典型用例和可扩展性机制提供良好的开箱即用体验good out of box experience以覆盖其他用例。

  • Spring Cloud has the following features

    • Distributed/versioned configuration

      分布式/版本化配置

    • Service registration and discovery

      服务注册和发现

    • Routing

      路由

    • Service-to-service calls

      服务到服务呼叫

    • Load balancing

      负载均衡

    • Circuit Breakers

      断路器

    • Global locks

      全局锁

    • Leadership election and cluster state

      领导选举和集群状态

    • Distributed messaging

      分布式消息传递

Spring Cloud Integrated with AWS Cloud

  • Spring Cloud for Amazon Web Services, part of the Spring Cloud umbrella project, eases the integration with hosted Amazon Web Services.

    Spring Cloud for Amazon Web Services 是 Spring Cloud umbrella项目的一部分,简化了与托管 Amazon Web Services 的集成。

    • It offers a convenient way to interact with AWS provided services using well-known Spring idioms and APIs, such as the messaging or caching API. Developers can build their application around the hosted services withouthaving to care about infrastructure or maintenance.

Spring Cloud Gateway

  • This project provides a library for building an API Gateway on top of Spring WebFlux.

    该项目提供了一个用于在 Spring WebFlux 之上构建 API 网关的库。

    • It uses familiar design patterns such as Spring MVC.

      它使用熟悉的设计模式,例如 Spring MVC。

  • Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such

    Spring Cloud Gateway 旨在提供一种简单而有效的方式来路由到 API 并为它们提供横切关注点,例如:

Service (SQS) is a fully managed message queuing service that enables you to decouple and scale microservices, distributed systems, and serverless applications.

<u>**AWS SQS 是一种完全托管的消息队列服务**</u>,使您能够解耦和扩展微服务、分布式系统和无服务器应用程序。
  • AWS SNS
    • Amazon Simple Notification Service (Amazon SNS) is a fully managed messaging service for both application-to-application (A2A) and application-to-person (A2P) communication.

      AWS SNS是一种完全托管的消息通知传递服务,适用于应用程序到应用程序 (A2A) 和应用程序到个人 (A2P) 的通信。

Spring Cloud

  • Spring Cloud focuses on providing good out of box experience for typical use cases and extensibility mechanism to cover others.

    Spring Cloud 专注于为典型用例和可扩展性机制提供良好的开箱即用体验good out of box experience以覆盖其他用例。

  • Spring Cloud has the following features

    • Distributed/versioned configuration

      分布式/版本化配置

    • Service registration and discovery

      服务注册和发现

    • Routing

      路由

    • Service-to-service calls

      服务到服务呼叫

    • Load balancing

      负载均衡

    • Circuit Breakers

      断路器

    • Global locks

      全局锁

    • Leadership election and cluster state

      领导选举和集群状态

    • Distributed messaging

      分布式消息传递

Spring Cloud Integrated with AWS Cloud

  • Spring Cloud for Amazon Web Services, part of the Spring Cloud umbrella project, eases the integration with hosted Amazon Web Services.

    Spring Cloud for Amazon Web Services 是 Spring Cloud umbrella项目的一部分,简化了与托管 Amazon Web Services 的集成。

    • It offers a convenient way to interact with AWS provided services using well-known Spring idioms and APIs, such as the messaging or caching API. Developers can build their application around the hosted services withouthaving to care about infrastructure or maintenance.

Spring Cloud Gateway

  • This project provides a library for building an API Gateway on top of Spring WebFlux.

    该项目提供了一个用于在 Spring WebFlux 之上构建 API 网关的库。

    • It uses familiar design patterns such as Spring MVC.

      它使用熟悉的设计模式,例如 Spring MVC。

  • Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such

    Spring Cloud Gateway 旨在提供一种简单而有效的方式来路由到 API 并为它们提供横切关注点,例如:

最后

以上就是心灵美啤酒为你收集整理的middleware中间件知识点总结Message-oriented MiddlewareJava Message ServiceJava Server PagesServletsJava SpringAspect Oriented ProgrammingConcurrencyJava Memory ModelThread SynchronizationSecurity Concepts for Middleware and Web VulnerabilitiesLayer of Securit的全部内容,希望文章能够帮你解决middleware中间件知识点总结Message-oriented MiddlewareJava Message ServiceJava Server PagesServletsJava SpringAspect Oriented ProgrammingConcurrencyJava Memory ModelThread SynchronizationSecurity Concepts for Middleware and Web VulnerabilitiesLayer of Securit所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(37)

评论列表共有 0 条评论

立即
投稿
返回
顶部