-
Notifications
You must be signed in to change notification settings - Fork 1
DataSource
Standalone Application stackpost
Here is a simple example of how to create and use a data source.
Web Application:
Tomcat provides a JNDI InitialContext implementation instance for each web application running under it, in a manner that is compatible with those provided by a Java Enterprise Edition application server. The Java EE standard provides a standard set of elements in the /WEB-INF/web.xml file to reference/define resources.
web.xmlweb-app_2_3.dtd configuration « Declare Your Resource Requirements
The following elements may be used in the web application deployment descriptor (/WEB-INF/web.xml) of your web application to define resources:
-
<env-entry>- Environment entry, a single-value parameter that can be used to configure how the application will operate. -
<resource-ref>- Resource reference, which is typically to an object factory for resources such as a JDBC DataSource, a JavaMail Session, or custom object factories configured into Tomcat. -
<resource-env-ref>- Resource environment reference, a new variation of resource-ref added in Servlet 2.4 that is simpler to configure for resources that do not require authentication information. Providing that Tomcat is able to identify an appropriate resource factory to use to create the resource and that no further configuration information is required, Tomcat will use the information in /WEB-INF/web.xml to create the resource.
Declaration of a reference to a JDBC connection factory that returns objects of type javax.sql.DataSource:
<resource-ref>
<description> Primary database </description>
<res-ref-name> jdbc/primaryDB </res-ref-name>
<res-type> javax.sql.DataSource </res-type>
<res-auth> Container </res-auth>
</resource-ref><res-type> is a fully-qualified class name of the resource factory. The variable can be assigned either Container or Application as a value.
If Container is specified, the web container handles the authentication before binding the resource factory to JNDI lookup registry. If Application is specified, the servlet must handle authentication programmatically. Different resource factories are looked up under a separate sub-context that describes the resource type, follows:
- jdbc/ for a JDBC javax.sql.DataSource factory
- mail/ for a JavaMail javax.mail.Session factory
- url/ for a java.net.URL factory
Naming References and Binding Information JNDI Lookups and Their Associated References
| JNDI Lookup Name | Associated Reference |
|---|---|
| java:comp/env | Application environment entries |
| java:comp/env/jdbc | JDBC DataSource resource |
| java:comp/env/mail | JavaMail Session Connection Factories |
| java:comp/env/url | URL Connection Factories |
context.xmlconfiguration « Configure Tomcat's Resource Factory
If Tomcat is unable to identify the appropriate resource factory and/or additional configuration information is required, additional Tomcat specific configuration must be specified before Tomcat can create the resource. Tomcat specific resource configuration is entered in the elements that can be specified in either $CATALINA_BASE/conf/server.xml or, preferably, the per-web-application context XML file (META-INF/context.xml).
Tomcat JDBC: As a Resource in context.xml.
| configuration | driverClassName | url |
|---|---|---|
| MySQL | com.mysql.jdbc.Driver |
jdbc:mysql://localhost:3306/javatest |
| Oracle 8i, 9i & 10g | oracle.jdbc.OracleDriver |
jdbc:oracle:thin:@127.0.0.1:1521:mysid |
| PostgreSQL | org.postgresql.Driver |
jdbc:postgresql://127.0.0.1:5432/mydb |
Code Your Application's Use Of This Resource
A typical use of this resource environment reference might look like this:
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/primaryDB");
Connection conn = ds.getConnection();
//etc.Web application xml configuration.
<!-- context.xml -->
<Context>
<Environment name="dev" value="jdbc/devdb" type="java.lang.String" override="false" />
<Environment name="qa" value="jdbc/testdb" type="java.lang.String" override="false" />
<Resource name="jdbc/devdb" type="javax.sql.DataSource" <!-- ... --> />
<Resource name="jdbc/testdb" type="javax.sql.DataSource" <!-- ... --> />
</Context>
<!-- web.xml -->
<!-- JDBC DataSources (java:comp/env/jdbc) -->
<resource-ref>
<description> Development database </description>
<res-ref-name> jdbc/devdb </res-ref-name>
<res-type> javax.sql.DataSource </res-type>
<res-auth> Container </res-auth>
</resource-ref>
<resource-ref>
<description> Testing database </description>
<res-ref-name> jdbc/testdb </res-ref-name>
<res-type> javax.sql.DataSource </res-type>
<res-auth> Container </res-auth>
</resource-ref>Initial Naming Context
The naming support in Sun Java System Web Server is based primarily on J2SE 1.3, with a few added enhancements.When an application component creates the initial context by using InitialContext(), Sun Java System Web Server returns an object that serves as a handle to the Web application’s naming environment. This object in turn provides sub-contexts for the java:comp/env namespace. Each Web application gets its own namespace java:comp/env name space is allotted to each Web application and objects bound in one Web application’s namespace do not collide with objects bound in other Web applications.
Strng JNDI_Lookup_Name = "java:comp/env/";
String ResourceName1 = "jdbc/devdb", ResourceName2 = "jdbc/testdb";
String env1 = "dev", env2 = "test";
InitialContext initContext = new InitialContext();
// context lookup "java:comp/env/jdbc/devdb"
DataSource ds = initContext.lookup(JNDI_Lookup_Name + ResourceName1);
// context environment lookup
Context envContext = (Context)initContext.lookup(JNDI_Lookup_Name);
DataSource ds = (DataSource)envContext.lookup(ResourceName1);
// Environment resource name lookup
String env_resourceName = (String)initialContext.lookup(JNDI_Lookup_Name + env1);
DataSource ds = (DataSource)initialContext.lookup(JNDI_Lookup_Name + env_resourceName);
Connection conn = ds.getConnection();Database URLs are strings. The complete URL syntax is:
jdbc:oracle:driver_type:[username/password]@database_specifier
jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName>
jdbc:oracle:thin:@localhost:1521:myDBName
jdbc:mysql://localhost:3306/myDBName
The first part of the URL specifies which JDBC driver is to be used. The supported driver_type values are thin, oci, and kprb.
-
Oracle Net connection descriptor support
thindriver.
String url="jdbc:oracle:thin:@(DESCRIPTION=
(LOAD_BALANCE=on)
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)(HOST=host1) (PORT=1521))
(ADDRESS=(PROTOCOL=TCP)(HOST=host2)(PORT=1521)))
(CONNECT_DATA=(SERVICE_NAME=service_name)))"- Thin-style service name
"jdbc:oracle:thin:scott/tiger@//myhost:1521/myservicename"SERVICE_NAME: Use the parameter SERVICE_NAME to identify the Oracle9i or Oracle8 database service to access. Set the value to a value specified by the SERVICE_NAMES parameter in the initialization parameter file.
SID: Use the parameter SID to identify the Oracle8 database instance by its Oracle System Identifier (SID). If the database is Oracle9i or Oracle8, use the SERVICE_NAME parameter rather than the SID parameter.
Embed this parameter under the CONNECT_DATA parameter.
Example
net_service_name=
(DESCRIPTION=
(ADDRESS=...)
(ADDRESS=...)
(CONNECT_DATA=
(SID=sales)))
<Resource name="jdbc/dbName" type="javax.sql.DataSource"
username="scott" password="tiger"
url="jdbc:oracle:thin:@(DESCRIPTION=(ENABLE=BROKEN)
(ADDRESS=(PROTOCOL=tcp)(PORT=1521)(HOST=host))(CONNECT_DATA=(SID=service_id_applets)))"
driverClassName="oracle.jdbc.driver.OracleDriver" maxTotal="20" maxIdle="10"
maxWaitMillis="5000" minEvictableIdleTimeMillis="300000"
timeBetweenEvictionRunsMillis="600000" validationInterval="600000"
validationQuery="select 1 from dual" testOnBorrow="true" auth="Container"
accessToUnderlyingConnectionAllowed="true" />If true the raw physical connection to the database can be accessed using the following construct:
Connection conn = ds.getConnection();
Connection rawConn = ((DelegatingConnection) conn).getInnermostDelegate();
...
conn.close()Default is false, because misbehaving programs can do harmfull things to the raw connection shuch as closing the raw connection or continuing to use the raw connection after it has been assigned to another logical connection. Be careful and only use when you need direct access to driver specific extensions.
NOTE: Do NOT close the underlying connection, only the original logical connection wrapper.
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. Basic, Refactoring Techniques
Method signature: It consists of method name and parameter list (number/type/order of the parameters). methodName(parametersList y). An instance method in a subclass with the same signature and return type as an instance method in the super-class overrides the super-class's method.
Java OOP concepts
Class - Collection of a common features of a group of object [static/instance Fields, blocks and Methods]
Object - Instance of a class (instance fields)
Abstraction - Process of hiding complex info and providing required info like API, Marker Interfaces ...
Encapsulation(Security) - Class Binding up with data members(fields) and member functions.
Inheritance (Reusability by placing common code in single class)
1. Multilevel - {A -> B -> C} 2. Multiple - Diamond problem {A <- (B) -> C} [Java not supports] 3. Cyclic {A <-> B} [Java not supports]
* Is-A Relation - Class A extends B
* Hash-A Relation - Class A { B obj = new B(); } - (Composition/Aggregation)
Polymorphism (Flexibility) 1. Compile-Time Overloading 2. Runtime Overriding [Greek - "many forms"]
int[] arr = {1,2,3}; int arrLength = arr.length; // Fixed length of sequential blocks to hold same data type
String str = "Yash"; int strLength = str.length(); // Immutable Object value can't be changed.
List<?> collections = new ArrayList<String>(); int collectionGroupSize = collections.size();
Map<?, ?> mapEntry = new HashMap<String, String>();
Set<?> keySet = mapEntry.keySet(); // Set of Key's
Set<?> entrySet = mapEntry.entrySet(); // Set of Entries [Key, Value]
// Immutable Objects once created they can't be modified. final class Integer/String/Employee
Integer val = Integer.valueOf("100"); String str2 = String.valueOf(100); // Immutable classes
final class Employee { // All Wrapper classes, java.util.UUID, java.io.File ...
private final String empName; // Field as Final(values can be assigned only once) Only getter functions.
public Employee(String name) { this.empName = name; }
} Native Java Code for Hashtable.h, Hashtable.cpp
SQL API.
You can check your current JDK and JRE versions on your command prompt respectively,
- JDK
javac -version [C:\Program Files\Java\jdk1.8.0_121\bin]o/p:javac 1.8.0_121 - JRE
java -version[C:\Program Files\Java\jdk1.8.0_121\bin]o/P:java version "1.8.0_102"
JAVA_HOME - Must be set to JDK otherwise maven projects leads to compilation error. [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? C:\Softwares\OpenJDK\, 7-zip
Fatal error compiling: invalid target release: JRE and JDK must be of same version
1.8.0.XXX
Disable TLS 1.0 and 1.1
security-libs/javax.net.ssl: TLS 1.0 and 1.1 are versions of the TLS protocol that are no longer considered secure and have been superseded by more secure and modern versions (TLS 1.2 and 1.3).
Core Java
-
Java Programming Language Basics
- Object, Class, Encapsulation, Interface, Inheritance, Polymorphism (Method Overloading, Overriding)
- JVM Architecture, Memory Areas
- JVM Class Loader SubSystem
- Core Java Interview Questions & Programs
- Interview Concepts
Stack Posts
- Comparable vs Comparator
- Collections and Arrays
-
String, StringBuffer, and StringBuilder
- String reverse
- Remove single char
- File data to String
- Unicode equality check Spacing entities
- split(String regex, int limit)
- Longest String of an array
-
Object Serialization
- Interface's Serializable vs Externalizable
- Transient Keyword
-
implements Runnablevsextends Thread - JSON
- Files,
Logging API- Append text to Existing file
- Counting number of words in a file
- Properties
- Properties with reference key