The post Connecting a database and creating a console Java program appeared first on Asjava.
]]>There are several types of DBMSs according to the way they organize data storage:
Hierarchical. Data is organized as a tree structure. An example is a file system that starts from the root of the disk and then grows with branches of different types of files and folders of varying degrees of nesting.
Networking. A modification of the hierarchical one, each node can have more than one parent.
Object-oriented. Data is organized in the form of classes/objects with their attributes and principles of interaction in accordance with the OOP.
Relational. Data of this type of DBMS is organized in tables. Tables can be linked to each other, and the information in them is structured.
External programs form queries to the DBMS using the Structured Query Language. What is SQL and how does it differ from other programming languages? One of the features of SQL is its declarative nature. That is, SQL is a declarative language. This means that when we enter commands, i.e., create queries to the SQL server, we describe what we want to get, not how we want to get it. By sending the server the SELECT * FROM CUSTOMER query (approximate translation from SQL into Russian: “make a selection from the COSTUMER table, the selection consists of all rows in the table”), we will get the data for all users. It doesn’t matter how and from where the server downloads and generates the data we are interested in. The main thing is to formulate the query correctly.
What is a SQL server and how does it work? Interaction with a DBMS is based on the client-server principle. Some external program sends a query in the form of SQL statements and commands, and the DBMS processes it and sends a response. For the sake of simplicity, let’s assume that SQL Server = DBMS.
If you know how to drive a car of one brand, you will most likely be able to drive others without any problems. The basics of driving are the same everywhere, except for small details. It is the same for SQL servers from different manufacturers – each of them has its own version of SQL, but it meets the specified standards (SQL92, SQL2003…). We will use SQL92 operators and commands. The main SQL operators are divided into the following groups:
In the 80s of the last century, personal computers such as PC XT/AT conquered the market. This was largely due to the modularity of their design. This means that a user could simply change one or another component of his or her computer (processor, video card, disks, etc.). This remarkable feature has been preserved to this day: we change the video card and update the driver (sometimes it updates itself automatically). Most often, nothing bad happens with such manipulations, and existing programs will continue to work with the system without reinstallation. The same is true for working in Java with a DBMS. To standardize work with SQL servers, you can interact with it through a single point – JDBC (Java DataBase Connectivity). It is an implementation of the java.sql package for working with DBMSs. Manufacturers of all popular SQL servers provide JDBC drivers for them. Consider the diagram below. The program uses class instances from java.sql . Then we provide the necessary commands to get/modify the data. Next, java.sql interacts with the DBMS through the jdbc driver and returns the finished result.
The post Connecting a database and creating a console Java program appeared first on Asjava.
]]>The post What is jdbc in Java? appeared first on Asjava.
]]>Use DriverManager to get a connection to a database. Make sure that you have the appropriate JDBC driver for your database.
String url = "jdbc:mysql://localhost:3306/database_name";
String user = "user";
String password = "password";
Connection connection = DriverManager.getConnection(url, user, password);
Use the Statement object to create SQL queries.
Statement statement = connection.createStatement();
String sqlQuery = "SELECT * FROM table";
Use the executeUpdate methods to execute queries that change data.
String updateQuery = "UPDATE table SET field = 'new value' WHERE condition";
int rowsAffected = statement.executeUpdate(updateQuery);
Use the executeQuery methods to execute SELECT queries and get the results.
ResultSet resultSet = statement.executeQuery(sqlQuery);
Use the next methods to iterate over the results and retrieve data.
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
// Data processing
}
Important: Always close resources (connection, statement, resultSet) after use to avoid memory leaks. They can be closed using the close() method.
The post What is jdbc in Java? appeared first on Asjava.
]]>The post What is XML Parser? appeared first on Asjava.
]]>Dom Parser – parses an XML document by loading the entire contents of the document and creating its complete hierarchical tree in memory.
SAX Parser – parses an XML document by event-based triggers. Does not load the full document into memory.
JDOM Analyzer – analyzes XML document similarly to DOM Analyzer, but in a simpler way.
StAX Parser – analyzes XML document similarly to SAX analyzer, but in a more efficient way.
XPath Analyzer – analyzes an XML document based on an expression and is widely used in conjunction with XSLT.
DOM4J Parser – a Java library for analyzing XML, XPath and XSLT using the Java Collections Framework. It provides support for DOM, SAX, and JAXP.
Dom Parser – analyzes an XML document by loading the entire contents of the document and creating its full hierarchical tree in memory.
SAX Parser – parses an XML document by event-based triggers. Does not load the full document into memory.
JDOM Analyzer – analyzes XML document similarly to DOM Analyzer, but in a simpler way.
StAX Parser – analyzes XML document similarly to SAX analyzer, but in a more efficient way.
XPath Analyzer – analyzes an XML document based on an expression and is widely used in conjunction with XSLT.
DOM4J Parser is a Java library for analyzing XML, XPath and XSLT using the Java Collections Framework. It provides support for DOM, SAX and JAXP.
JAXB and XSLT APIs are available to handle XML parsing in an object-oriented manner. We will look at each parser in detail in later chapters of this lesson.
The post What is XML Parser? appeared first on Asjava.
]]>The post What is XML? appeared first on Asjava.
]]>Before proceeding to describe it, it seems appropriate to discuss the reasons for its emergence and subsequent rapid development. To do this, let’s try to look at the problems of the WWW that must be solved by means of the new generation of Web technologies.
XML is an attempt to solve these problems by creating a simple markup language that describes arbitrary structured data. To be more precise, it is a meta-language in which specialized languages are written that describe data of a certain structure.
Such languages are called XML vocabularies. Unlike HTML, XML does not contain any instructions on how the data described in an XML document should be displayed. The way data is displayed for different devices is specified by the XSL style sheet language, which plays a similar role for XML as CSS does for HTML.
Another fundamental difference between it and HTML is that XML can contain any tags that the creators of an XML vocabulary deem necessary.
Here is a list of just a few specialized XML-based languages that are currently in various stages of development by W3C working groups: MathML is a language for mathematical formulas; SMIL is a language for integrating and synchronizing multimedia; SVG is a language for two-dimensional vector graphics; RDF is a language for meta-descriptions of resources; XHTML is a reformulation of HTML in terms of XML.
The process of processing an XML document is as follows. Its text is analyzed by a special program called an XML processor. An XML processor does not know anything about the semantics of the data in the document; it only performs parsing of the document text and checks its correctness in terms of XML rules. If the document is well-formed, the XML processor passes the parsing results to the application program that performs meaningful processing; if the document is incorrectly formatted, i.e. contains syntax errors, the XML processor must inform the user about them. HTML does not express the content of documents.
The HTML language was created to describe the structure of documents (titles, headings, lists, paragraphs, etc.) and, to some extent, the rules for their display (bold, italic, etc.). It is in no way intended to describe the meaning of the documents written on it, and in many cases it is the data that makes up the body of the document, whether it is a stock exchange report or a scientific publication.
That’s why there was a need for a language to describe data, and data organized in hierarchical structures. HTML is cumbersome and inflexible. In recent years, HTML has turned into an accumulation of tags that often duplicate each other and do not make the text of the document clear.
If you add to this the non-standard HTML extensions that all browser developers are guilty of, then creating small, complex HTML documents becomes a serious task. On the other hand, a set of tags that has been fixed once and for all is often not flexible enough to express the content we need.
The concept of a Web browser is too limited. With the advent of Java applets, scripting languages, and ActiveX elements, Web browsers are no longer simple “visitors” to HTML documents; today they are more like programs that run specific applications.
Nevertheless, the concept of a browser imposes unnecessary restrictions on the user; in many cases, we need Web-oriented programs, i.e. programs that can read specialized information from Web sites and present it to us in a familiar form, such as spreadsheets.
Suppose I need all the texts of books available on the Web. Trying to search by author’s name will result in a list of all links with that name, including memoirs about Dovlatova, reviews of her books, etc. It would be much more convenient to use a special tag to indicate what I am looking for. It is impossible to find interrelated resources. Let’s assume now that I did find several stories by Dovlatov that clearly constitute a single collection. It’s good if they contain links to the table of contents, but often they don’t. Therefore, you need a way to indicate that this group of pages constitutes a single resource and should be handled accordingly.
The post What is XML? appeared first on Asjava.
]]>The post Distributed Java systems: Creating and managing large-scale applications appeared first on Asjava.
]]>Distributed Java systems are interconnected components that work together to achieve a common goal. These components can be located on different machines or even in different geographical locations. Distributed Java systems allow developers to create large-scale applications that can handle high user loads and provide high availability. The main features of distributed Java systems include:
Building a distributed Java system involves several steps, including designing the system architecture, selecting the appropriate technologies, and implementing the components. Here are some best practices to follow when building distributed Java systems:
Decompose the application into smaller manageable components, often called microservices. This allows each component to be developed, deployed, and scaled independently.
Design for scalability with horizontal scaling techniques such as data partitioning and load balancing.
Ensure fault tolerance by implementing redundancy and monitoring mechanisms such as health checks and replication.
Choosing the right technologies is critical to the success of your distributed system. Some popular Java technologies for building distributed systems include:
Spring Boot: A widely used framework for building microservices and other distributed systems.
Apache Kafka: A high-performance, fault-tolerant message broker used for event-driven architectures and streaming data.
Apache Cassandra: a highly scalable distributed NoSQL database designed to process large amounts of data on many standard servers.
After designing your architecture and selecting the appropriate technologies, implement the components of your distributed system.
Managing a distributed Java system involves deploying, monitoring, and maintaining components. Some of the best practices for managing Java distributed systems are:
Distributed Java systems allow developers to create and manage large-scale applications that can handle high user loads and provide high availability. By following best practices and using the right tools, you can create a reliable and efficient distributed system. If you’re looking to hire remote Java developers for your project, consider Reintech.io’s dedicated team of Java developers with the knowledge and experience needed to build and manage distributed Java systems.
The post Distributed Java systems: Creating and managing large-scale applications appeared first on Asjava.
]]>The post Anatomy of a distributed program appeared first on Asjava.
]]>At the application level, a distributed program can be broken down into the following parts:
A typical computer operating system on a computer host can run several processes at the same time. A process is created by describing a sequence of steps in a programming language, compiling the program into an executable form, and running the executable on the operating system. During operation, a process has access to computer resources (such as CPU time and input/output devices) through the operating system. A process can be entirely dedicated to a particular program, or several programs can use a single process to perform tasks.
Each process has at least one control thread. Some operating systems support the creation of multiple control threads in a single process. Each thread in a process can run independently of the other threads, although there is usually some synchronization between them. For example, one thread may monitor input through a socket connection, while another may listen for user events (keystrokes, mouse movements, etc.) and provide feedback to the user through output devices (monitor, speakers, etc.). At some point, the input from the input stream may require feedback from the user. At this point, the two streams will need to coordinate the transfer of input to the user’s attention.
Programs written in object-oriented languages consist of interacting objects. One simple definition of an object is a group of related data with available methods for querying or modifying the data (getName() , set-Name() ) or for performing certain actions based on the data (sendName(Out-putStream o ) ). A process can consist of one or more objects, and these objects can be accessed by one or more threads in the process. And with the introduction of distributed object technology such as RMI and CORBA, an object can also be logically distributed across multiple processes on multiple computers.
For the purpose of this book, we will use the term “agent” as a generic way of referring to the important functional elements of a distributed application.
While process, flow, and object are fairly well-defined entities, an agent (at least the definition we will use for this book) is a higher-level system component defined around a particular function, or utility, or role in the overall system. For example, an e-banking program can be broken down into a customer agent, a transactional agent, and an information brokerage agent. Agents can be distributed across multiple processes and consist of multiple objects and flows in those processes. Our client agent can consist of an object in a process running on the client’s desktop that listens for data and updates the local display, and an object in a process running on the bank server that makes requests and sends data back to the client. There are two objects running in different processes on separate machines, but together we can think of them as one client agent with client-side elements and server-side elements.
Thus, a distributed program can be viewed as a coordinated group of agents working to achieve a specific goal. Each of these agents can be distributed across multiple processes on remote hosts and can consist of multiple objects or control threads. Agents can also belong to multiple programs at the same time. For example, you might be developing an ATM application that consists of an account database server with client request agents distributed across the network that send requests. The account server agent and the customer request agents are agents in the ATM program, but they can also serve agents residing at the financial institution’s headquarters as part of the administrative program.
The post Anatomy of a distributed program appeared first on Asjava.
]]>The post All about Java RMI registry and how to use it appeared first on Asjava.
]]>The Java RMI Registry is a key component of the Java RMI system and provides a centralized directory for servers to register services and for clients to search for those services.
To learn the intricacies of the Java RMI system, let’s implement a simple server object that provides a method to accept a name and return a greeting. Here is the definition of the object’s interface:
import java.rmi.Remote; import java.rmi.RemoteException; public interface Greeting extends Remote { public String greet(String name) throws RemoteException; }
The name of the interface is called Greeting . It provides a single method called greet () that takes a name and returns a suitable greeting.
To mark this interface as exportable, it must extend the interface java.rmi.Remote . In addition, the method must declare a throws clause listing java.rmi.RemoteException in addition to any application-specific exceptions. Exceptions This is to allow client code to handle (or propagate) remote method invocation errors such as host-not-found , connection failure, etc. Д.
After declaring the interface (which is used by clients), we implement the server-side object and provide the greet () method as shown. A simple format string is used to format the greeting.
public class GreetingObject implements Greeting { private String fmtString = "Hello, %s"; public String greet(String name) { return String.format(this.fmtString, name); } }
Let’s now put all these pieces together and implement the main () server method. Let’s walk through each of the relevant steps.
The first step is to create an implementation of the server object.
Greeting greeting = new GreetingObject();
Next, we get a stub for the server object from the RMI runtime environment. The stub implements the same interface as the server object. However, the method implements the necessary communication with the remote server object. This stub is used by the client to transparently call the method on the server object.
Greeting stub = (Greeting)UnicastRemoteObject.exportObject(greeting, 0);
Once a stub is obtained, we pass that stub to the RMI registry to bind to the specified named service. When a client requests an implementation of that service, it receives a stub that knows how to contact the server object. The static LocateRegistry.getRegistry () method is then used to obtain a reference to the local registry. The rebind () method is then used to bind a name to the stub.
String name = "Greeting"; Registry registry = LocateRegistry.getRegistry(port); registry.rebind(name, stub);
The complete main method.
import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; public class Main { static public void main(String[] args) throws Exception { if ( args.length == 0 ) { System.err.println("usage: java Main port#"); System.exit(1); } int index = 0; int port = Integer.parseInt(args[index++]); String name = "Greeting"; Greeting greeting = new GreetingObject(); Greeting stub = (Greeting)UnicastRemoteObject. exportObject(greeting, 0); Registry registry = LocateRegistry.getRegistry(port); registry.rebind(name, stub); System.out.println("Greeting bound to \"" + name + "\""); } }
Building the server
Let’s now look at building the server. For simplicity, we build using the command line in Linux rather than a build tool such as Maven.
The following compiles the source files into class files in the target directory.
rm -rf target mkdir target javac -d target src/server/*.java
Compile the class files into a JAR file for execution.
jar cvf target/rmi-server.jar -C target server
We also assemble the interface files needed to compile the client into a JAR library.
jar cvf target/rmi-lib.jar -C target server/Greeting.class
Client implementation
Let’s now look at the client implementation used to call the methods of the server object.
As with the server, get a reference to the registry by specifying the hostname where the registry is running and the port number.
Registry registry = LocateRegistry.getRegistry(host, port);
Next, we look for the service in the registry. The lookup () method returns a stub that can be used to call the services.
Greeting greeting = (Greeting) registry.lookup(name);
And call the method, passing the necessary arguments. Here we get the greeting by passing the name and printing it.
System.out.println(name + " reported: " + greeting.greet(myName));
The complete client code:
package client; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry.Registry; import server.Greeting; public class Client { static public void main(String[] args) throws Exception { if ( args.length != 3 ) { System.err.println("usage: java Client client host port myName"); System.exit(1); } int index = 0; String host = args[index++]; int port = Integer.parseInt(args[index++]); String myName = args[index++]; String name = "Greeting"; Registry registry = LocateRegistry.getRegistry(host, port); Greeting greeting = (Greeting) registry.lookup(name); System.out.println(name + " reported: " + greeting.greet(myName)); } }
Now let’s start the server program so it can start serving requests.
java -cp target/rmi-server.jar server.Main 1099 # throws Exception in thread "main" java.rmi.ConnectException: Connection refused to host: xxx; nested exception is: java.net.ConnectException: Connection refused
The reason you get this exception is this: note that from the server code, it is trying to connect to the local registry on port 1099. In the event of a failure, you will get this exception.
The solution is to run the RMI Registry. The RMI Registry is a program that comes with the Java Virtual Machine and is called rmiregistry . It should be located in the bin directory of the Java Virtual Machine installation. Running it is as simple as:
/usr/lib/jvm/jdk1.8.0_71/bin/rmiregistry
By default, the registry listens on port 1099. To listen on a different port, specify the port number as follows:
/usr/lib/jvm/jdk1.8.0_71/bin/rmiregistry 1100
The post All about Java RMI registry and how to use it appeared first on Asjava.
]]>The post Java – text blocks appeared first on Asjava.
]]>It is especially convenient to use the java text block when embedding XML, HTML, JSON, and SQL query fragments in the code.
String customerOld = "{\n" +
" \"firstName\": \"Gabriella",\n" +
" \"lastName\": \"Hart",\n" +
" \"age\": 35\n" +
"}";
String customerNew = """
{
"firstName": "Gabriella"
"lastName": "Hart"
"age": 35
}
""";
The result of a text block is a Java String that supports all its methods (trim, substring, replace, etc.). Using the formatted method, we can conveniently format our text:
String customerNew = """
{
"firstName": "%s",
"lastName": "%s",
"age": %d
}
""".formatted("Gabriella", "Hart", 35).
The post Java – text blocks appeared first on Asjava.
]]>The post Access modifiers in Java appeared first on Asjava.
]]>In total, there are four access modifiers in Java: public, protected, private, and default. Only two of them can be used for non-nested classes: public and default. For fields and methods, all four.
The post Access modifiers in Java appeared first on Asjava.
]]>The post Diving into the world of Java Core appeared first on Asjava.
]]>And understanding the key elements, such as variables, methods, classes, and control structures, allows programmers to create reliable and efficient programs. Let’s dive into the world of Java Core to unlock all its secrets and discover the endless possibilities of programming with this amazing language.
Java Core includes several key components that are the foundation of the Java programming language. Let’s take a look at what exactly they include and what functions they perform:
Methods are blocks of code that can be called from other parts of the program. They perform certain actions or return the results of data processing and allow us to organize code into modules to reuse it in different parts of the program.
Objects and classes. Java Core uses object-oriented programming (OOP). Objects are instances of classes, which are templates for creating objects. Classes define the state and behavior of objects. OOP allows you to organize code in a more structured and modular way.
These components are the foundation of Java Core and provide its functionality. They allow programmers to create, process, and manage data, control the flow of program execution, and organize code into modules.
Java Core is of great importance to programmers because it provides a number of advantages and opportunities. Here are some reasons why Java Core knowledge is important for a programmer:
The post Diving into the world of Java Core appeared first on Asjava.
]]>