Spring DI – Overview

Spring DI – Overview ”; Previous Next Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code. Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. Spring provides Ioc Containers which tend to be lightweight, especially when compared to EJB containers, for example. This is beneficial for developing and deploying applications on computers with limited memory and CPU resources. Dependency Injection (DI) The technology that Spring is most identified with is the Dependency Injection (DI) flavor of Inversion of Control. The Inversion of Control (IoC) is a general concept, and it can be expressed in many different ways. Dependency Injection is merely one concrete example of Inversion of Control. When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing. Dependency Injection helps in gluing these classes together and at the same time keeping them independent. What is dependency injection exactly? Let”s look at these two words separately. Here the dependency part translates into an association between two classes. For example, class A is dependent of class B. Now, let”s look at the second part, injection. All this means is, class B will get injected into class A by the IoC. Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods. As Dependency Injection is the heart of Spring Framework, we will explain this concept in a separate chapter with relevant example. Print Page Previous Next Advertisements ”;

Spring DI – IOC Containers

Spring DI – IoC Containers ”; Previous Next The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI to manage the components that make up an application. These objects are called Spring Beans, which we will discuss in the next chapter. The container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The following diagram represents a high-level view of how Spring works. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application. Spring provides the following two distinct types of containers. Sr.No. Container & Description 1 Spring BeanFactory Container This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring. 2 Spring ApplicationContext Container This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface. The ApplicationContext container includes all functionality of the BeanFactorycontainer, so it is generally recommended over BeanFactory. BeanFactory can still be used for lightweight applications like mobile devices or applet-based applications where data volume and speed is significant. Print Page Previous Next Advertisements ”;

RxJava – Filtering Operators

RxJava – Filtering Operators ”; Previous Next Following are the operators which are used to selectively emit item(s) from an Observable. Sr.No. Operator & Description 1 Debounce Emits items only when timeout occurs without emiting another item. 2 Distinct Emits only unique items. 3 ElementAt emit only item at n index emitted by an Observable. 4 Filter Emits only those items which pass the given predicate function. 5 First Emits the first item or first item which passed the given criteria. 6 IgnoreElements Do not emits any items from Observable but marks completion. 7 Last Emits the last element from Observable. 8 Sample Emits the most recent item with given time interval. 9 Skip Skips the first n items from an Observable. 10 SkipLast Skips the last n items from an Observable. 11 Take takes the first n items from an Observable. 12 TakeLast takes the last n items from an Observable. Filtering Operator Example Create the following Java program using any editor of your choice in, say, C:> RxJava. ObservableTester.java import io.reactivex.Observable; //Using take operator to filter an Observable public class ObservableTester { public static void main(String[] args) { String[] letters = {“a”, “b”, “c”, “d”, “e”, “f”, “g”}; final StringBuilder result = new StringBuilder(); Observable<String> observable = Observable.fromArray(letters); observable .take(2) .subscribe( letter -> result.append(letter)); System.out.println(result); } } Verify the Result Compile the class using javac compiler as follows − C:RxJava>javac ObservableTester.java Now run the ObservableTester as follows − C:RxJava>java ObservableTester It should produce the following output − ab Print Page Previous Next Advertisements ”;

XStream – Environment Setup

Xstream – Environment ”; Previous Next In this chapter, we will discuss on the different aspects of setting up a congenial environment for Java. Local Environment Setup If you want to set up your environment for Java programming language, then this section explains how to download and set up Java on your machine. Please follow the steps given below to set up you Java environment. Java SE can be downloaded for free from the link − Download Java. Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set the environment variables to point to correct installation directories − Setting Up the Path for Windows 2000/XP Assuming you have installed Java in c:Program Filesjavajdk directory − Right-click on ”My Computer” and select ”Properties”. Click the ”Environment variables” button under the ”Advanced” tab. Alter the ”Path” variable so that it also contains the path to the Java executable. For example, if the path is currently set to ”C:WINDOWSSYSTEM32”, then change your path to read ”C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin”. Setting Up the Path for Windows 95/98/ME Assuming you have installed Java in c:Program Filesjavajdk directory − Edit the ”C:autoexec.bat” file and add the following line at the end − ”SET PATH = %PATH%;C:Program Filesjavajdkbin” Setting Up the Path for Linux, UNIX, Solaris, FreeBSD Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this. For example, if you use bash as your shell, then you would add the following line at the end of your ”.bashrc: export PATH=/path/to/java:$PATH” Popular Java Editors To write Java programs, you will need a text editor. There are even more sophisticated IDEs available in the market. But for now, you can consider one of the following − Notepad − On Windows, you can use any simple text editor like Notepad (Recommended for this tutorial) or TextPad. Netbeans − It is a Java IDE that is free and can be downloaded from https://www.netbeans.org/index.html. Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from https://www.eclipse.org/. Download XStream Archive Download the latest version of XStream jar file from XStream download page. At the time of writing this tutorial, we have downloaded xstream-1.4.18.jar and copied it into C:>XStream folder. OS Archive name Windows xstream-1.4.18.jar Linux xstream-1.4.18.jar Mac xstream-1.4.18.jar Set XStream Environment Set the XStream_HOME environment variable to point to the base directory location where xstream jar is stored on your machine. The following table shows how to set the XStream environment on Windows, Linux, and Mac, assuming we”ve extracted xstream-1.4.18.jar in the XStream folder. Sr.No. OS & Description 1 Windows Set the environment variable XStream_HOME to C:XStream 2 Linux export XStream_HOME=/usr/local/XStream 3 Mac export XStream_HOME=/Library/XStream Set CLASSPATH Variable Set the CLASSPATH environment variable to point to the XStream jar location. The following table shows how to set the CLASSPATH variable on Windows, Linux, and Mac system, assuming we”ve stored xstream-1.4.18.jar in the XStream folder. Sr.No. OS & Description 1 Windows Set the environment variable CLASSPATH to %CLASSPATH%;%XStream_HOME%xstream-1.4.18.jar; 2 Linux export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar; 3 Mac export CLASSPATH=$CLASSPATH:$XStream_HOME/xstream-1.4.18.jar; Print Page Previous Next Advertisements ”;

Spring AOP – Application

Spring AOP – XML Based Application ”; Previous Next In this chapter, we will write actual AOP applications using Spring AOP Framework. Before you start writing your first example using Spring-WS framework, you have to make sure that you have set up your Spring AOP environment properly as explained in Spring Web Services – Environment Setup chapter. Now, proceed to write a simple console-ased Spring AOP Application, which will demonstrate AOP concepts. Create a Project Step 1 − Open a command console, go the C:MVN directory and execute the following mvn command. C:MVN>mvn archetype:generate -DgroupId=com.tutorialspoint -DartifactId=Student -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false Maven will start processing and will create the complete Java application project structure. [INFO] Scanning for projects… [INFO] [INFO] ——————< org.apache.maven:standalone-pom >——————- [INFO] Building Maven Stub Project (No POM) 1 [INFO] ——————————–[ pom ]——————————— [INFO] [INFO] >>> maven-archetype-plugin:3.2.0:generate (default-cli) > generate-sources @ standalone-pom >>> [INFO] [INFO] <<< maven-archetype-plugin:3.2.0:generate (default-cli) < generate-sources @ standalone-pom <<< [INFO] [INFO] [INFO] — maven-archetype-plugin:3.2.0:generate (default-cli) @ standalone-pom — [INFO] Generating project in Batch mode [INFO] —————————————————————————- [INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0 [INFO] —————————————————————————- [INFO] Parameter: basedir, Value: C:MVN [INFO] Parameter: package, Value: com.tutorialspoint [INFO] Parameter: groupId, Value: com.tutorialspoint [INFO] Parameter: artifactId, Value: Student [INFO] Parameter: packageName, Value: com.tutorialspoint [INFO] Parameter: version, Value: 1.0-SNAPSHOT [INFO] project created from Old (1.x) Archetype in dir: C:MVNStudent [INFO] ———————————————————————— [INFO] BUILD SUCCESS [INFO] ———————————————————————— [INFO] Total time: 13.388 s [INFO] Finished at: 2021-12-27T20:18:26+05:30 [INFO] ———————————————————————— Step 2 − Go to C:/MVN directory. You”ll see a Java application project created, named student (as specified in artifactId). Update the POM.xml to include Spring-AOP dependencies. Add MainApp.java, Student.java, and Logging.java files. POM.xml <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>Student</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>Student</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.14</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> </dependency> </dependencies> </project> Following is the content of the Logging.java file. package com.tutorialspoint; public class Logging { /** * This is the method which I would like to execute * before a selected method execution. */ public void beforeAdvice() { System.out.println(“Going to setup student profile.”); } /** * This is the method which I would like to execute * after a selected method execution. */ public void afterAdvice() { System.out.println(“Student profile has been setup.”); } /** * This is the method which I would like to execute * when any method returns. */ public void afterReturningAdvice(Object retVal){ System.out.println(“Returning:” + retVal.toString() ); } /** * This is the method which I would like to execute * if there is an exception raised. */ public void AfterThrowingAdvice(IllegalArgumentException ex) { System.out.println(“There has been an exception: ” + ex.toString()); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); student.printThrowException(); } } Step 3 − Add the configuration file Beans.xml under src > main > resources folder. <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:config> <aop:aspect id = “log” ref = “logging”> <aop:pointcut id = “selectAll” expression = “execution(* com.tutorialspoint.*.*(..))”/> <aop:before pointcut-ref = “selectAll” method = “beforeAdvice”/> <aop:after pointcut-ref = “selectAll” method = “afterAdvice”/> <aop:after-returning pointcut-ref = “selectAll” returning = “retVal” method = “afterReturningAdvice”/> <aop:after-throwing pointcut-ref = “selectAll” throwing = “ex” method = “AfterThrowingAdvice”/> </aop:aspect> </aop:config> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Step 4 − Open the command console, go the C:MVN directory and execute the following mvn command. C:MVN>Student> mvn package Maven will start processing and downloading the required libraries. C:MVNStudent>mvn package [INFO] Scanning for projects… [INFO] [INFO] ———————< com.tutorialspoint:Student >——————— [INFO] Building Student 1.0-SNAPSHOT [INFO] ——————————–[ jar ]——————————— [INFO] [INFO] — maven-resources-plugin:2.6:resources (default-resources) @ Student — [INFO] Using ”UTF-8” encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] [INFO] — maven-compiler-plugin:3.1:compile (default-compile) @ Student — [INFO] Nothing to compile – all classes are up to date [INFO] [INFO] — maven-resources-plugin:2.6:testResources (default-testResources) @ Student — [INFO] Using ”UTF-8” encoding to copy filtered resources. [INFO] skip non existing resourceDirectory C:MVNStudentsrctestresources [INFO] [INFO] — maven-compiler-plugin:3.1:testCompile (default-testCompile) @ Student — [INFO] Nothing to compile – all classes are up to date [INFO] [INFO] — maven-surefire-plugin:2.12.4:test (default-test) @ Student — [INFO] Surefire report directory: C:MVNStudenttargetsurefire-reports ——————————————————- T E S T S ——————————————————- Running com.tutorialspoint.AppTest Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.093 sec Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] — maven-jar-plugin:2.4:jar (default-jar) @ Student — [INFO] ———————————————————————— [INFO] BUILD SUCCESS [INFO] ———————————————————————— [INFO] Total time: 4.213 s [INFO] Finished at: 2021-12-27T20:42:00+05:30 [INFO] ———————————————————————— C:MVNStudent> Import Project in Eclipse Step 1 − Open Eclipse. Step 2 − Select File → Import → option. Step 3 − Select Maven Projects

Spring AOP – Application

Spring AOP – Annotation Based Application ”; Previous Next Let us write an example which will implement advice using Annotation based configuration. For this, let us have a working Eclipse IDE in place and use the following steps to create a Spring application. Step Description 1 Update the project Student created under chapter Spring AOP – Application. 2 Update the bean configuration and run the application as explained below. Following is the content of Logging.java file. This is actually a sample of aspect module, which defines the methods to be called at various points. package com.tutorialspoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; @Aspect public class Logging { /** Following is the definition for a Pointcut to select * all the methods available. So advice will be called * for all the methods. */ @Pointcut(“execution(* com.tutorialspoint.*.*(..))”) private void selectAll(){} /** * This is the method which I would like to execute * before a selected method execution. */ @Before(“selectAll()”) public void beforeAdvice(){ System.out.println(“Going to setup student profile.”); } } Following is the content of the Student.java file. package com.tutorialspoint; public class Student { private Integer age; private String name; public void setAge(Integer age) { this.age = age; } public Integer getAge() { System.out.println(“Age : ” + age ); return age; } public void setName(String name) { this.name = name; } public String getName() { System.out.println(“Name : ” + name ); return name; } public void printThrowException(){ System.out.println(“Exception raised”); throw new IllegalArgumentException(); } } Following is the content of the MainApp.java file. package com.tutorialspoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext(“Beans.xml”); Student student = (Student) context.getBean(“student”); student.getName(); student.getAge(); } } Following is the configuration file Beans.xml. <?xml version = “1.0” encoding = “UTF-8”?> <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xmlns:aop = “http://www.springframework.org/schema/aop” xsi:schemaLocation = “http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd “> <aop:aspectj-autoproxy/> <!– Definition for student bean –> <bean id = “student” class = “com.tutorialspoint.Student”> <property name = “name” value = “Zara” /> <property name = “age” value = “11”/> </bean> <!– Definition for logging aspect –> <bean id = “logging” class = “com.tutorialspoint.Logging”/> </beans> Run Project Once you are done creating the source and configuration files, run your application. Rightclick on MainApp.java in your application and use run as Java Application command. If everything is fine with your application, it will print the following message. Going to setup student profile. Name : Zara Going to setup student profile. Age : 11 Print Page Previous Next Advertisements ”;

TIKA – Content Extraction

TIKA – Content Extraction ”; Previous Next Tika uses various parser libraries to extract content from given parsers. It chooses the right parser for extracting the given document type. For parsing documents, the parseToString() method of Tika facade class is generally used. Shown below are the steps involved in the parsing process and these are abstracted by the Tika ParsertoString() method. Abstracting the parsing process − Initially when we pass a document to Tika, it uses a suitable type detection mechanism available with it and detects the document type. Once the document type is known, it chooses a suitable parser from its parser repository. The parser repository contains classes that make use of external libraries. Then the document is passed to choose the parser which will parse the content, extract the text, and also throw exceptions for unreadable formats. Content Extraction using Tika Given below is the program for extracting text from a file using Tika facade class − import java.io.File; import java.io.IOException; import org.apache.tika.Tika; import org.apache.tika.exception.TikaException; import org.xml.sax.SAXException; public class TikaExtraction { public static void main(final String[] args) throws IOException, TikaException { //Assume sample.txt is in your current directory File file = new File(“sample.txt”); //Instantiating Tika facade class Tika tika = new Tika(); String filecontent = tika.parseToString(file); System.out.println(“Extracted Content: ” + filecontent); } } Save the above code as TikaExtraction.java and run it from the command prompt − javac TikaExtraction.java java TikaExtraction Given below is the content of sample.txt. Hi students welcome to tutorialspoint It gives you the following output − Extracted Content: Hi students welcome to tutorialspoint Content Extraction using Parser Interface The parser package of Tika provides several interfaces and classes using which we can parse a text document. Given below is the block diagram of the org.apache.tika.parser package. There are several parser classes available, e.g., pdf parser, Mp3Passer, OfficeParser, etc., to parse respective documents individually. All these classes implement the parser interface. CompositeParser The given diagram shows Tika’s general-purpose parser classes: CompositeParser and AutoDetectParser. Since the CompositeParser class follows composite design pattern, you can use a group of parser instances as a single parser. The CompositeParser class also allows access to all the classes that implement the parser interface. AutoDetectParser This is a subclass of CompositeParser and it provides automatic type detection. Using this functionality, the AutoDetectParser automatically sends the incoming documents to the appropriate parser classes using the composite methodology. parse() method Along with parseToString(), you can also use the parse() method of the parser Interface. The prototype of this method is shown below. parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) The following table lists the four objects it accepts as parameters. Sr.No. Object & Description 1 InputStream stream Any Inputstream object that contains the content of the file 2 ContentHandler handler Tika passes the document as XHTML content to this handler, thereafter the document is processed using SAX API. It provides efficient postprocessing of the contents in a document. 3 Metadata metadata The metadata object is used both as a source and a target of document metadata. 4 ParseContext context This object is used in cases where the client application wants to customize the parsing process. Example Given below is an example that shows how the parse() method is used. Step 1 − To use the parse() method of the parser interface, instantiate any of the classes providing the implementation for this interface. There are individual parser classes such as PDFParser, OfficeParser, XMLParser, etc. You can use any of these individual document parsers. Alternatively, you can use either CompositeParser or AutoDetectParser that uses all the parser classes internally and extracts the contents of a document using a suitable parser. Parser parser = new AutoDetectParser(); (or) Parser parser = new CompositeParser(); (or) object of any individual parsers given in Tika Library Step 2 − Create a handler class object. Given below are the three content handlers − Sr.No. Class & Description 1 BodyContentHandler This class picks the body part of the XHTML output and writes that content to the output writer or output stream. Then it redirects the XHTML content to another content handler instance. 2 LinkContentHandler This class detects and picks all the H-Ref tags of the XHTML document and forwards those for the use of tools like web crawlers. 3 TeeContentHandler This class helps in using multiple tools simultaneously. Since our target is to extract the text contents from a document, instantiate BodyContentHandler as shown below − BodyContentHandler handler = new BodyContentHandler( ); Step 3 − Create the Metadata object as shown below − Metadata metadata = new Metadata(); Step 4 − Create any of the input stream objects, and pass your file that should be extracted to it. FileInputstream Instantiate a file object by passing the file path as parameter and pass this object to the FileInputStream class constructor. Note − The path passed to the file object should not contain spaces. The problem with these input stream classes is that they don’t support random access reads, which is required to process some file formats efficiently. To resolve this problem, Tika provides TikaInputStream. File file = new File(filepath) FileInputStream inputstream = new FileInputStream(file); (or) InputStream stream = TikaInputStream.get(new File(filename)); Step 5 − Create a parse context object as shown below − ParseContext context =new ParseContext(); Step 6 − Instantiate the parser object, invoke the parse method, and pass all the objects required, as shown in the prototype below − parser.parse(inputstream, handler, metadata, context); Given below is the program for content extraction using the parser interface − import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.AutoDetectParser; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.Parser; import org.apache.tika.sax.BodyContentHandler; import org.xml.sax.SAXException; public class ParserExtraction { public static void main(final String[] args) throws IOException,SAXException, TikaException { //Assume sample.txt is in your current directory File file = new File(“sample.txt”); //parse method parameters Parser parser = new AutoDetectParser(); BodyContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); FileInputStream inputstream = new FileInputStream(file); ParseContext context = new ParseContext(); //parsing the file parser.parse(inputstream, handler, metadata, context);

RxJava – Using CompositeDisposable

RxJava – Using CompositeDisposable ”; Previous Next The CompositeDisposable class represents a container which can hold multiple disposable and offers O(1) complexity of adding and removing disposables. Class Declaration Following is the declaration for io.reactivex.disposables.CompositeDisposable class − public final class CompositeDisposable extends Object implements Disposable, io.reactivex.internal.disposables.DisposableContainer CompositeDisposable Example Create the following Java program using any editor of your choice in, say, C:> RxJava. ObservableTester.java import io.reactivex.Maybe; import io.reactivex.Single; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.observers.DisposableMaybeObserver; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; import java.util.concurrent.TimeUnit; public class ObservableTester { public static void main(String[] args) throws InterruptedException { CompositeDisposable compositeDisposable = new CompositeDisposable(); //Create an Single observer Disposable disposableSingle = Single.just(“Hello World”) .delay(2, TimeUnit.SECONDS, Schedulers.io()) .subscribeWith( new DisposableSingleObserver<String>() { @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onSuccess(String value) { System.out.println(value); } }); //Create an observer Disposable disposableMayBe = Maybe.just(“Hi”) .delay(2, TimeUnit.SECONDS, Schedulers.io()) .subscribeWith(new DisposableMaybeObserver<String>() { @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onSuccess(String value) { System.out.println(value); } @Override public void onComplete() { System.out.println(“Done!”); } }); Thread.sleep(3000); compositeDisposable.add(disposableSingle); compositeDisposable.add(disposableMayBe); //start observing compositeDisposable.dispose(); } } Verify the Result Compile the class using javac compiler as follows − C:RxJava>javac ObservableTester.java Now run the ObservableTester as follows − C:RxJava>java ObservableTester It should produce the following output − Hello World Hi Print Page Previous Next Advertisements ”;

TIKA – Environment

TIKA – Environment ”; Previous Next This chapter takes you through the process of setting up Apache Tika on Windows and Linux. User administration is needed while installing the Apache Tika. System Requirements JDK Java SE 2 JDK 1.6 or above Memory 1 GB RAM (recommeneded) Disk Space No minimum requirement Operating System Version Windows XP or above, Linux Step 1: Verifying Java Installation To verify Java installation, open the console and execute the following java command. OS Task Command Windows Open command console >java –version Linux Open command terminal $java –version If Java has been installed properly on your system, then you should get one of the following outputs, depending on the platform you are working on. OS Output Windows Java version “1.7.0_60” Java (TM) SE Run Time Environment (build 1.7.0_60-b19) Java Hotspot (TM) 64-bit Server VM (build 24.60-b09, mixed mode) Lunix java version “1.7.0_25” Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode) We assume the readers of this tutorial have Java 1.7.0_60 installed on their system before proceeding for this tutorial. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed. Step 2: Setting Java Environment Set the JAVA_HOME environment variable to point to the base directory location where Java is installed on your machine. For example, OS Output Windows Set Environmental variable JAVA_HOME to C:ProgramFilesjavajdk1.7.0_60 Linux export JAVA_HOME = /usr/local/java-current Append the full path of the Java compiler location to the System Path. OS Output Windows Append the String; C:Program FilesJavajdk1.7.0_60bin to the end of the system variable PATH. Linux export PATH = $PATH:$JAVA_HOME/bin/ Verify the command java-version from command prompt as explained above. Step 3: Setting up Apache Tika Environment Programmers can integrate Apache Tika in their environment by using Command line, Tika API, Command line interface (CLI) of Tika, Graphical User interface (GUI) of Tika, or the source code. For any of these approaches, first of all, you have to download the source code of Tika. You will find the source code of Tika at https://Tika.apache.org/download.html, where you will find two links − apache-tika-1.6-src.zip − It contains the source code of Tika, and Tika -app-1.6.jar − It is a jar file that contains the Tika application. Download these two files. A snapshot of the official website of Tika is shown below. After downloading the files, set the classpath for the jar file tika-app-1.6.jar. Add the complete path of the jar file as shown in the table below. OS Output Windows Append the String “C:jarsTika-app-1.6.jar” to the user environment variable CLASSPATH Linux Export CLASSPATH = $CLASSPATH − /usr/share/jars/Tika-app-1.6.tar − Apache provides Tika application, a Graphical User Interface (GUI) application using Eclipse. Tika-Maven Build using Eclipse Open eclipse and create a new project. If you do not having Maven in your Eclipse, set it up by following the given steps. Open the link https://wiki.eclipse.org/M2E_updatesite_and_gittags. There you will find the m2e plugin releases in a tabular format Pick the latest version and save the path of the url in p2 url column. Now revisit eclipse, in the menu bar, click Help, and choose Install New Software from the dropdown menu Click the Add button, type any desired name, as it is optional. Now paste the saved url in the Location field. A new plugin will be added with the name you have chosen in the previous step, check the checkbox in front of it, and click Next. Proceed with the installation. Once completed, restart the Eclipse. Now right click on the project, and in the configure option, select convert to maven project. A new wizard for creating a new pom appears. Enter the Group Id as org.apache.tika, enter the latest version of Tika, select the packaging as jar, and click Finish. The Maven project is successfully installed, and your project is converted into Maven. Now you have to configure the pom.xml file. Configure the XML File Get the Tika maven dependency from https://mvnrepository.com/artifact/org.apache.tika Shown below is the complete Maven dependency of Apache Tika. <dependency> <groupId>org.apache.Tika</groupId> <artifactId>Tika-core</artifactId> <version>1.6</version> <groupId>org.apache.Tika</groupId> <artifactId> Tika-parsers</artifactId> <version> 1.6</version> <groupId> org.apache.Tika</groupId> <artifactId>Tika</artifactId> <version>1.6</version> <groupId>org.apache.Tika</groupId> < artifactId>Tika-serialization</artifactId> < version>1.6< /version> < groupId>org.apache.Tika< /groupId> < artifactId>Tika-app< /artifactId> < version>1.6< /version> <groupId>org.apache.Tika</groupId> <artifactId>Tika-bundle</artifactId> <version>1.6</version> </dependency> Print Page Previous Next Advertisements ”;

RxJava – Completable Observable

RxJava – Completable Observable ”; Previous Next The Completable class represents deferred response. Completable observable can either indicate a successful completion or error. Class Declaration Following is the declaration for io.reactivex.Completable class − public abstract class Completable extends Object implements CompletableSource Protocol Following is the sequential protocol that Completable Observable operates − onSubscribe (onError | onComplete)? Completable Example Create the following Java program using any editor of your choice in, say, C:> RxJava. ObservableTester.java import java.util.concurrent.TimeUnit; import io.reactivex.Completable; import io.reactivex.disposables.Disposable; import io.reactivex.observers.DisposableCompletableObserver; import io.reactivex.schedulers.Schedulers; public class ObservableTester { public static void main(String[] args) throws InterruptedException { //Create an observer Disposable disposable = Completable.complete() .delay(2, TimeUnit.SECONDS, Schedulers.io()) .subscribeWith(new DisposableCompletableObserver() { @Override public void onError(Throwable e) { e.printStackTrace(); } @Override public void onStart() { System.out.println(“Started!”); } @Override public void onComplete() { System.out.println(“Done!”); } }); Thread.sleep(3000); //start observing disposable.dispose(); } } Verify the Result Compile the class using javac compiler as follows − C:RxJava>javac ObservableTester.java Now run the ObservableTester as follows − C:RxJava>java ObservableTester It should produce the following output − Started! Done! Print Page Previous Next Advertisements ”;