Upload
others
View
5
Download
0
Embed Size (px)
Citation preview
Architectural patterns
Open Source & DOTNET platform
Understanding architectural designpatterns (like MVC, MVP, MVVM etc.) isessential for producing a maintainable,clean, extendable and testable sourcecode.
- G.P.singh (STD)- Mukul Saxena (PSA)
Open Source Technologies
Frame Work (Struts, Spring)
2
Open Source
In general, open source refers to anyprogram whose source code is madeavailable for use or modification asusers or other developers see fit. Opensource software is usually developed asa public collaboration and made freelyavailable.
3
Open Source
Open Source is a certification markowned by the Open Source Initiative(OSI). Developers of software that isintended to be freely shared andpossibly improved and redistributed byothers can use the Open Sourcetrademark if their distribution termsconform to the OSI's Open SourceDefinition.
4
Basic Requirement
• The software being distributed must beredistributed to anyone else without anyrestriction.
• The source Code must be made available (sothat the receiving party will be able toimprove or modify it).
• The license can require improved versions ofthe software to carry a different name orversion from the original software.
5
Definition
• Free Redistribution
• Source Code
• Derived Works
• Integrity of The Author's Source Code
• No Discrimination Against Persons or Groups
• No Discrimination Against Fields of Endeavor
• Distribution of License 6
Definition
• License Must Not Be Specific to a Product
• License Must Not Restrict Other Software
• License Must Be Technology-Neutral
7
Open Source Initiative
• The Open Source Initiative (OSI) is anorganization dedicated topromoting open-source software.
• The organization was founded in lateFebruary 1998
• https://opensource.org
8
• Open Source OS – Linux, FreeBSD, OpenBSD, OpenSolaris, Ubuntu
• Open Source Languages – Python, Ruby, Perl, Java
• Open Source Frame Work- Bootstrap, Angular JS
• Open Sourec Web Frame Work –Spring, Struts, SOFIA……..60+
9
What is a Frame Work
• Frame Works are large bodies (usually many classes) of prewritten code to which you add your own code.
• Very Common examples are GUI frame works-
SWINg, AWT (Abstract Windowing Toolkit),
JFrame, JButton
10
Difference between Library and Frame Work• Library – reusable piece of code
Library Library fn.
Control Returns
Your Code Library fn. call
• Frame Work is apiece of code which dictates thearchitecture of your project will follow. You have to followframe works code and methodologies.
• Frame Work will provide you with hooks and callbacks, sothat you built on it – it will then call your plugged in codewhen it wishes – A phenomenon called Inversion of Control
11
Struts FrameworkThe Struts Framework is a standard fordeveloping well-architected Web applications, Based on theModel-View-Controller (MVC) designparadigm.
- By Apache Foundation
- https://struts.apache.org/
- Apache Struts 2.5.10 GA has been releasedon 3 February 2017. (General Availability)
12
MVC
MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
• Model - Model represents an object or JAVA POJO carryingdata. It can also have logic to update controller if its datachanges.
• View - View represents the visualization of the data thatmodel contains.
• Controller - Controller acts on both model and view. Itcontrols the data flow into model object and updates the viewwhenever data changes. It keeps view and model separate.
13
MVC
14
Components
• Java Scripts
• Java Applet
• Java Servlet
• JSP
• Java Beans
• JVM
• Java Plugins
15
AppletAn applet is a Java program that runs in a Web browser. An applet canbe a fully functional Java application because it has the entire Java APIat its disposal.
• An applet is a Java class that extends the java.applet.Applet class.• A main() method is not invoked on an applet, and an applet class
will not define main().• Applets are designed to be embedded within an HTML page.• When a user views an HTML page that contains an applet, the code
for the applet is downloaded to the user's machine.• A JVM is required to view an applet. The JVM can be either a plug-in
of the Web browser or a separate runtime environment.
16
Example
AppletName.java −
import java.applet.*;
import java.awt.*;
public class AppletName extends Applet { public void method1 ……. {
……..
……..
}
}
Invoking Applet
• <html>
• <title>………….</title>
• <hr>
• <applet code = “AppletName.class" width = "320" height = "120">
• ……………………………..
• </applet>
• <hr>
• </html>
17
Servlet
• Java Servlets are programs that run on a Web orApplication server and act as a middle layer betweena request coming from a Web browser or other HTTPclient and databases or applications on the HTTPserver.
• Servlets are Java classes which service HTTP requestsand implement the javax.servlet.Servlet interface.Web application developers typically write servletsthat extend javax.servlet.http.HttpServlet, anabstract class that implements the Servlet interfaceand is specially designed to handle HTTP requests.
18
19
Example
ServletName.java –
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
Public class ServletName extends HttpServlet { ..}
Web.xml<servlet>
<servlet-name> ServletName </servlet-name><servlet-class> ServletName </servlet-class>
</servlet>
<servlet-mapping><servlet-name> ServletName </servlet-name><url-pattern>/ AnyName</url-pattern>
</servlet-mapping>
http://localhost:8080/AnyName
20
Java Plug-in
The Java Plug-in software is a component of the Java RuntimeEnvironment (JRE). The JRE allows applets written in the Javaprogramming language to run inside various browsers. TheJava Plug-in software is not a standalone program and cannotbe installed separately.
Difference Between Applet and PluginThe Java Plugin is a special way to run Applets. It tells your browser to use a specified program to run downloaded Java Applet class files instead of using the JVM embedded in your browser. Plugins use the Object tag to run your Applet... if you used the normal Applet tag the browser would use it's own built in JVM
21
Java Bean
A Java Bean is a java class that should follow following conventions:
• It should have a no-arg constructor.
• It should be Serializable.
• It should provide methods to set and get the values of the properties, known as getter and setter methods.
22
Example//secureAccountLogin.java
package secure.account.loginCheck;
import com.opensymphony.xwork2.ActionSupport;
import account.view.encript_passwoard;
import account.view.Conn;
import account.view.service;
import org.apache.struts2.ServletActionContext;
public class secureAccountLogin implements java.io.Serializable{
private String user_login;
private String login;
private String paswrd;
private String msgLogin="";
public secureAccountLogin(){}
public void setLoginId(String login) {
this.login = login;
}
public String getLogin() {
return login;
}
public void setmsgLogin(String msgLogin) {
this.msgLogin = msgLogin;
}
public String getMsgLogin() {
return msgLogin;
}
23
Constructor• Constructor in java is a special type of
method that is used to initialize the object.• Java constructor is invoked at the time of object
creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructorThere are basically two rules defined for the
constructor.• Constructor name must be same as its class name• Constructor must have no explicit return type
24
JVM (Java Virtual Machine)JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).
What is JVM
It is:
1.A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
2.An implementation Its implementation is known as JRE (Java Runtime Environment).
3.Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.
What it does
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JVM provides definitions for the:
• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting
Writing code using struts2
JDK
IDE
1. J-Developer
2. Net Beans
3. Eclipse
Struts2 support files (http://struts.apache.org/download.cgi)
Web Server - Apache Tomcat (tomcat.apache.org), Weblogic (oracle.com)
26
Writing Struts2 Code Using JDeveloper
• Open with “Default Role”
• New Application - “JavaEE Web Application”
• ApplicationName-ProjectName-Default Package
• Copy Struts2 jar files in WEB-INF/lib
or include it through project properties
• Create your .jsp and .java files
• Make entries in web.xml and struts.xml
27
Advantages and Disadvantages of Struts
Advantages of Struts• Centralized File-Based Configuration.
Rather than hard-coding information into Java programs, many Struts values are represented in XML or property files. This loose coupling means that many changes can be made without modifying or recompiling Java code, and that wholesale changes can be made by editing a single file.
• Form Beans.
• Bean Tags.Apache Struts provides a set of custom JSP tags (bean:write, in particular) that let you easily output the properties of JavaBeans components. Basically, these are concise and powerful variations of the standard jsp:useBean and jsp:getProperty tags.
• HTML Tags.Apache Struts provides a set of custom JSP tags to create HTML forms that are associated with JavaBeans components. This bean/form association serves two useful purposes:
• It lets you get initial form-field values from Java objects.• It lets you redisplay forms with some or all previously entered values intact.• Form Field Validation.
Apache Struts has built-in capabilities for checking that form values are in the required format. If values are missing or in an improper format, the form can be automatically redisplayed with error messages and with the previously entered values maintained.This validation can be performed on the server (in Java), or both on the server and on the client (in JavaScript).
• Consistent Approach.Struts encourages consistent use of MVC throughout your application.
• Easy to learn and implement• Struts makes it easier to develop large web apps
Large user base• The dominant (by far) framework - developers available, advice
available, books, etc• Open Source.
Open source, freely usableAll components subclassable or replaceable!Includes powerful JSP Tag librariesSupported by third-party packages
28
Disadvantages of Struts• · Less Transparent.
With Struts applications, there is a lot more going on behind the scenes than with normal Java-based Web applications. As a result, Struts applications are:– Harder to understand– Harder to benchmark and optimize
• Rigid Approach.
The flip side of the benefit that Struts encourages a consistent approach to MVC is that Struts makes it difficult (but by no means impossible) to use other approaches.
Sometimes MVC is not needed. It depends on what your application is, how many people you will have working on it, and most importantly what the skill level is of the people coding your application.
29
Securityhttps://struts.apache.org/docs/security.html
• Security tips– Restrict access to the Config Browser– Don't mix different access levels in the same namespace– Never expose JSP files directly– Disable devMode– Reduce logging level– Use UTF-8 encoding– Do not defined setters when not needed– Do not use incoming values as an input for localization logic
• Internal security mechanism
struts.excludedClasses - comma-separated list of excluded classesstruts.excludedPackageNamePatterns - patterns used to exclude packages struts.excludedPackageNames - comma-separated list of excluded packages
30
Struts.xml• The core configuration file for the framework is the default (struts.xml) file
and should reside on the classpath of the webapp (generally /WEB-INF/classes).
• Values in struts.xml1. Constant –
Constants provide a simple way to customize a Struts application bydefining key settings that modify framework and plugin behavior.
https://struts.apache.org/docs/constant-configuration.html<struts>
<constant name="struts.devMode" value="true" />
...
</struts>
31
2. Package
Packages are a way to group actions, results, result types etc.
<package name="default" extends="struts-default">
3. Result-type
The Result Type manages the view. Tiles, Json, Jasper
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
32
4. Interceptors
• Interceptors can execute code before and after an Action is
invoked
• Interceptors "set the stage" for the Action classes
<interceptors>
<interceptor name="clear-cache" class="SuperAdmin.ClearCacheInterceptor"/>
5. Interceptor-ref - calling interceptors
<interceptor-ref name="clear-cache" />
33
6. interceptor-stack - we can bundle Interceptors
<interceptor-stack name="strutsfilter">
<interceptor-ref name="requestWrapperInterceptor"/>
<interceptor-ref name="defaultStack" />
</interceptor-stack>
7. Action
Actions are the core of the Struts2 framework, as they are for any MVCframework. Each URL is mapped to a specific action, which provides theprocessing logic necessary to service the request from the user.
34
8. Result
the <results> tag plays the role of a view in the Struts2 MVC framework. The action is responsible for executing the business logic. The next step after executing the business logic is to display the view using the <results> tag.
<action name="secureLogin" class="secure.account.loginCheck.secureAccountLogin" method="accountValidateByProcd">
<interceptor-ref name="clear-cache" />
<result name="suresuccess">/layout/auth1.jsp</result>
<result name="firstloginflag">/layout/FirstLoginPage.jsp</result>
<result name="invalid.token">/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
35
<form id="proAss" method="post" action="secureLogin.action">
<table width="100%">
<tr>
<td align="center">
<img src="<s:url value='/images/loading.gif'/>" />
</td>
</tr>
</table>
</form>
When This form is submitted ----Action=‘SecureLogin’----secureAccountLogin.java ---- method="accountValidateByProcd”----
36
37
upkosh.up.nic.in/UPKAP/APP/
/UPKAP/APP/ ----Context Root
Index.jsp<META HTTP-EQUIV="Refresh" CONTENT="0;URL=homePage.action">
struts.xml<action name="*Page" method="{1}" class="account.view.layout">
“home” is matched so method=”home” will be called in layout.java
38
Layout.java• public String home() {•
• Map session = ActionContext.getContext().getSession();• HttpServletResponse response = ServletActionContext.getResponse();• HttpServletRequest request = ServletActionContext.getRequest();• // String url = request.getHeader("referer");• // if(url==null)• // {• // return "csrfprevent";• // }•
• Conn con=new Conn();• String user_type11="81";• Connection conid=con.getC3(user_type11);• try• {• layout l;• String query1="Select TREA_CODE,TREA_NAME from ACCOUNT.TREA_INFO order by TREA_NAME asc";• PreparedStatement pre1=conid.prepareStatement(query1);• ResultSet rs1=pre1.executeQuery();• while(rs1.next()) {• l =new layout();• l.setTrea_code(rs1.getString("TREA_CODE"));• l.setTrea_name(rs1.getString("TREA_NAME"));• trea_dt.add(l);• }• rs1.close();• pre1.close();• }• catch(Exception ex) {• System.out.println(ex.toString());•
• }• finally {• try {• if(conid!=null) {• conid.close();• }• }• catch(Exception ex) {• System.out.println(ex.toString());• }• }•
• return "home";• }
39
40
Sample Struts.xml
<!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN""http://struts.apache.org/dtds/struts-2.0.dtd">
<struts><constant name="struts.custom.i18n.resources" value="global" /><constant name="struts.enable.DynamicMethodInvocation" value="false" /><constant name="struts.multipart.maxSize" value="10485760" /><constant name="struts.i18n.reload" value="true" /><constant name="struts.devMode" value="false" /><!--<constant name="struts.action.extension" value=","/>-->
<package name="default" extends="struts-default">
<result-types><result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<interceptors><interceptor name="clear-cache" class="SuperAdmin.ClearCacheInterceptor"/><interceptor name="requestWrapperInterceptor" class="account.filter.RequestWrapperInterceptor"></interceptor>
<interceptor-stack name="strutsfilter"><interceptor-ref name="requestWrapperInterceptor"/><interceptor-ref name="defaultStack" />
</interceptor-stack></interceptors>
<global-results><result name="Exception">/errorPage.jsp</result>
</global-results>
<global-exception-mappings><exception-mapping exception="java.lang.Exception" result="Exception"/>
</global-exception-mappings>
<action name="*Page" method="{1}" class="account.view.layout"><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/><interceptor-ref name="strutsfilter"/><interceptor-ref name="params"><param name="excludeParams">dojo\..*,^struts\..*,^session\..*,^request\..*,^application\..*,^servlet(Request|Response)\..*,parameters\...*</param>
41
*************************************
<result name="main" type="tiles">main</result><result name="home" type="tiles">main</result><result name="csrfprevent" >/untitled1.jsp</result>
<result name="empDetailReport" type="tiles">AdminSearch</result><result name="bulkdatauplaod" type="tiles">bulkdatauplaod</result><result name="input1" type="redirect">/logout.action</result></action>
<action name="secureLogin" class="secure.account.loginCheck.secureAccountLogin" method="accountValidateByProcd">
<interceptor-ref name="token" /><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/><interceptor-ref name="strutsfilter"/><result name="suresuccess">/layout/auth1.jsp</result><result name="firstloginflag">/layout/FirstLoginPage.jsp</result><result name="invalid.token">/index.jsp</result><result name="input">/index.jsp</result></action>
42
<action name="secureLogin1" class="secure.account.loginCheck.secureAccountLogin" method="accountValidate1"><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/><interceptor-ref name="strutsfilter"/><result name="suresuccessddo" type="tiles">ddohomedsc_mid</result><result name="suresuccess1" type="tiles">newhome</result><result name="suresuccess82" type="tiles">newhome82</result><result name="suresuccess83" type="tiles">newhome83</result><result name="suresuccess84" type="tiles">newhome84</result><result name="input">/index.jsp</result></action>
<action name="logout" class="secure.account.loginCheck.secureAccountLogin" method="logout"><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/><interceptor-ref name="strutsfilter"/><result name="csrfprevent" >/untitled1.jsp</result><result name="logout" >/index.jsp</result></action>
<action name="hometrea" class="secure.account.loginCheck.secureAccountLogin" method="newhomePage"><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/><interceptor-ref name="strutsfilter"/><result name="suresuccess1" type="tiles">newhome</result><result name="suresuccess82" type="tiles">newhome82</result><result name="suresuccess83" type="tiles">newhome83</result><result name="suresuccess84" type="tiles">newhome84</result><result name="input1" type="redirect">/logout.action</result></action>
<action name="accntinfo" class="secure.account.loginCheck.secureAccountLogin" method="accntdetails"><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/><interceptor-ref name="strutsfilter"/><result name="success" type="tiles">acctdet</result><result name="input1" type="redirect">/logout.action</result></action>
<action name="accntchngPas" class="secure.account.loginCheck.secureAccountLogin" method="chngePassdetails"><interceptor-ref name="clear-cache" /><interceptor-ref name="basicStack"/>
43