Final java editor

download Final java editor

of 84

Transcript of Final java editor

  • 7/30/2019 Final java editor

    1/84

    1

    CHAPTER-1

    INTRODUCTION TO PROJECT

    1.1 INTRODUCTION

    JEditor is a powerful interactive development environment (IDE) for Java technologies

    that provides more power at your fingertips than all the ordinary editors. What makes

    JEditor a cut above the rest? Just look at what JEditor can do for you:

    Manage projects with ease in an interface that is much like Microsoft VisualStudio.

    Use JEditor to wrap around your existing projects and use different JDK profiles. Get down to writing code quickly with our project templates. Make viewing your project a breeze with our class browser. Debug with an easy, intuitive interface. No need for silly DOS prompts! Walk through our wizards and cut to the chase of writing your project quickly and

    easily.

    Manage and exchange your code with our Ant and CVS integration.

    Save valuable time on Classpath configuration; let JEditor do it for you. Customize our user interface the way that you like it. Set up your own run-time environments to run your application as an applet, in a

    JUnit environment, or in a DOS window.

    Experience the satisfaction of faster speed, yet lower system requirements thanwith other IDEs.

    Unlike most IDEs, JEditor has two types of tools that you can configure. The first type is

    the Java Development Kit (JDK) tools. You can use JDK tools to compile, debug, and runthe project. You can attach these tools to your project using the Project Settings dialog

    box. If no project is available, JEditor runs the default projects.

  • 7/30/2019 Final java editor

    2/84

    2

    1.3 MODULES

    Modular programming (also known as top down design and stepwise refinement) is a

    software design technique that increases the extent to which software is composed ofseparate, interchangeable components called modules by breaking down program

    functions into modules, each of which accomplishes one function and contains everything

    necessary to accomplish this.

    Conceptually, modules represent a separation of concerns, and improve maintainability

    by enforcing logical boundaries between components. Modules are typically incorporated

    into the program through interfaces.

    A module interface expresses the elements that are provided and required by the module.

    The elements defined in the interface are detectable by other modules. The

    implementation contains the working code that corresponds to the elements declared in

    the interface.

    1.3.1 Modules Used

    1.3.1.1 Writing Code

    Mail Data package is used whenever a new user enters his email and password .If the

    password is valid the old values of the database gets deleted and the new values are

    entered in the mail table of the mail database. The Mail data file is also called when a user

    presses the Receive All button and same actions occur.

    1.3.1.2 Outlook

    This is the main package of the application in controlling all major activities. It calls other

    packages as and when needed. The GUI of the application is also described here.

    1.3.1.3 Receive Mail

    This package is used when the client receives mail from the server .It contains all pop

    settings needed to communicate to server to receive mail.

  • 7/30/2019 Final java editor

    3/84

    3

    1.3.1.4 Sending

    Sending is used when we have to send mail. The Outlook package passes the text

    information as parameters which are further sent via SMTP protocol whose properties areset in the Sending package.

    1.3.1.4 SimpleMailAuthentication

    This module is used just for authentication of the user by the server by passing the

    username and password.

    1.4 SYSTEM REQUIRMENTS

    1.4.1 Hardware Requirements

    200 MHz Pentium, 160 MHz PowerPC, or 166 MHz UltraSparc At least 64 MB RAM 486 or Pentium based PC (Pentium 100MHz or better recommended). Display card supporting 8, 16, 24 or 32 bit display mode. (16-bit display moderecommended for fastest video performance).

    1.4.2 Software Requirements

    Operating SystemAny Operating System Java archive (JAR) Java Beans Activation Framework 1.1(Activation.jar), Java Mail API(Mail.jar) Front End- Java Back End- MySQL

  • 7/30/2019 Final java editor

    4/84

    4

    CHAPTER-2

    SOFTWARE ANALYSIS

    2.1 PROBLEM DEFINITION

    The main idea behind the making of outlook was to be able to operate on the emails even

    when you are not connected to the network. As usually it was impossible for a user to get

    to his email or attachments when he was offline. He was not able to compose his emails

    and save it for later use if he is offline and it was a headache for a user to remember so

    many Email addresses if needed without the use of internet.

    2.2 TERMS OF REFERENCES

    1) The main objective of the application created was to give user adaptive features if he is

    offline

    2) The Outlook application is light and can work with minimum amount of resources

    as compared to Ms Outlook.

    3) It is Adaptive to the new changing environment.

    4) Cost reduction is also an issue to be addressed.

    5) It could be easily understood by a user who has worked on Ms Outlook

    6) Compatible to any Operating System.

    2.3 FEASIBILITY REPORT

    2.3.1 Technical Feasibility

    Technically this project is feasible. There are a variety of databases we can use in order to

    develop the system, we suggest MySQL database, because its a fairly small system and

    access is ideal for such systems.

    Also as the application is developed in java it is Platform Independent. So, It can be

    installed on any Operating System and Platforms.

  • 7/30/2019 Final java editor

    5/84

    5

    2.3.2 Economic Feasibility

    The new software will mean a great advantage in terms of efficiency and speed of service,

    and accuracy and correctness will be increased.

    The new workload will be catered for and processing will be much faster.Also as the

    Application will be able to work on any Operating System it will be adaptive and will be

    cheap as compared to other mailing applications.

    Java also provides Secure Environment so the cost of maintenance will automatically

    reduce.

    2.3.3 Legal Feasibility

    It determines if there are any legal implications / requirements associated with the

    introduction of the new system. Laws that need to be addressed include:-

    - violation of the data protection act- violation of computer misuse act- violation of copyright2.3.4 Operational Feasibility

    To help the users accept the system, it is important to involve them in the designing

    process of the new system. We have achieved this by involving them right from the start

    and getting their views and developing a prototype.

  • 7/30/2019 Final java editor

    6/84

    6

    CHAPTER-3

    SYSTEM DESIGN

    3.1. 0-LEVEL DFD

    In this 0-Level DFD the brief data flow of Outlook can be depicted as-

    Client gets its validation via the email server. e.g. Gmail Serve If the account is valid the application gets access to the Server database. The values for the user in the Server database are copied to the clients database

    from where the changes are reflected in the application

    Whenever an action is performed by a user regarding sending Email, appropriatechanges are made in the Server Database.

    Fig: 3.1 0-Level DFD

  • 7/30/2019 Final java editor

    7/84

    7

    3.2 1-LEVEL DFD

    On Studying Outlook in a much deeper fashion following data flow can be observed:

    The first step is the validation process where the clients values are accepted orrejected based on their genuineness.

    This checking of users Username and Password are matched by the ServerDatabase

    Once the authenticity is proved the process Receive All Mails starts in which allthe mails of the email server are retrieved from the mail server and the values

    belonging to the user are retrieved

    These retrieved values are entered in the User Database via the Entry Process The values that are being entered in the database are being reflected back to the

    application where the user can see them and operate upon them

    As more and more changes are made by the user all these changes are only madein the user database and thus are temporary.

    Also while calling the Receive all Mails if there is an error in the connectionthen en error message prompts out regarding connection problem or false

    username and password.

  • 7/30/2019 Final java editor

    8/84

    8

    Fig: 3.2 1-LEVEL DFD

  • 7/30/2019 Final java editor

    9/84

    9

    3.3 E-R DIAGRAM

    The E-R Diagram of the application can be described as follows:-

    The client is the one who runs the application and he needs username andpassword to get connected to the server which is the attributes of the client.

    The client can get access to the application if the Username and password arecorrect

    The application on the other hand has multiple entities and these are1. Inbox2. Outbox3. Sent4. Drafts5. Deleted

    All these Entities have the same attributes and these are id1, from1, subject1,date1 and message1.

    None of these parameters are set to primary as regarding the username and password this

    overhead is left for the Email server which checks whether a user is genuine.

    Regarding other values all can be duplicate whether it be a message subject time or date.

    The id though created and can be set unique but it is just made for future references and

    no major role is played by them.

  • 7/30/2019 Final java editor

    10/84

    10

    Fig: 3.3 E-R Diagram

    CHAPTER-4

  • 7/30/2019 Final java editor

    11/84

    11

    TECHNOLOGY USED

    4.1 JAVA

    The entire component has been developed using Java technology. Java has been chosen as

    the platform because of its feature rich nature. The Java Platform provides robust end-to-

    end solutions for networked applications as well as a trusted standard for embedded

    applications. So Java was a natural choice for development process.

    4.1.1 Characteristics of Java

    1) Object OrientedJava is object oriented to the truest sense of the word. Everything in Java is represented as

    objects. Variables and methods both are encapsulated in objects. Java is the purest object-

    oriented language.

    2) RobustJava is a very robust language owing to the following features.Excellent exception handling facilities.Memory management relief for the user. User does not have to worry about allocationand deallocation of memory.

    Strict compile-time and runtime checks for data types.3) Portable and Architecture-neutral (Platform Independent):Java is portable and platform independent so much that they satisfy write once; run

    anywhere, anytime, forever. This feature is implemented in the following ways:

    Compiler generates machine independent byte-code instructions which can be runon any machine supporting Java Virtual Machine.

    Size of primitive data type is machine independent.4) Multithreaded:

  • 7/30/2019 Final java editor

    12/84

    12

    Programs can do many things simultaneously using different threads. Provides a solution for multi-process synchronization. Allows the creation of networked and interactive programs.5) Distributed: Open access to remote objects by the use of RMI (Remote Method Invocation). Brings a level of abstraction to client/server programming.6) Secure: Security is achieved by confining a java program to the java executionenvironment and not allowing access to other parts of the user computer.

    Absence of pointers provides memory related security as encroachment of memory isavoided Proper measures for prevention of viral infection and malicious intent.

    7) Dynamic and Extensible: Facilitates linking in of new classes, objects and methods. Supports native methods (methods written in other languages like C ,C++). Programs carry with them a substantial amount of runtime type information that isused to verify and resolve accesses to objects at run-time.

    8) High Performance:Just-In-Time (JIT) compilers are used to convert byte-code into native machine code

    resulting in very high performance. These JIT compilers can be used on a real time, piece

    by piece demand basis to perform on-the-fly compilation of byte-code into native-code.

    9) Compilation and InterpretationJava programs are implemented as a two-stage system.

    Compilation: Source code to byte-code and not machine instructions.

  • 7/30/2019 Final java editor

    13/84

    13

    Interpretation: Byte-code to machine code (for any system that supports using JVM)

    Thus cross-platform programs can be written.

    4.1.2 Java Swings

    "Swing" refers to the new library of GUI controls (buttons, sliders, checkboxes, etc.) that

    replaces the somewhat weak and inflexible AWT controls.

    The Swing classes eliminate Java's biggest weakness: its relatively primitive user

    interface toolkit. Java Swing helps you to take full advantage of the Swing classes,

    providing detailed descriptions of every class and interface in the key Swing packages. It

    shows you how to use all of the new components, allowing you to build state-of-the-artuser interfaces and giving you the context you need to understand what you're doing. It's

    more than documentation;Java Swinghelps you develop code quickly and effectively.

    1. Main New Features

    Lightweight: Not built on native window-system windows. Much bigger set of built-in controls: Trees, image buttons, tabbed panes, sliders,

    toolbars, color choosers, tables, text areas to display HTML or RTF, etc.

    Much more customizable: Can change border, text alignment, or add image to almostany control. Can customize how minor features are drawn. Can separate internal

    representation from visual appearance.

    "Pluggable" look and feel. Can change look and feel at runtime, or design own lookand feel.

    Many miscellaneous new features. Double-buffering built in, tool tips, dock able toolbars, keyboard accelerators, custom cursors, etc.

    2. J Component

    Components are named JXxx. E.g. JFrame, JPanel, JApplet, JDialog, JButton, etc.

    The J Component class is the root of the Visual component class hierarchy in JFC. All

    Swing components are implemented as subclass of J components class, which inherits

  • 7/30/2019 Final java editor

    14/84

    14

    from the Container class. Swing component inherit the following functionality from J

    Component

    a). Borders- Using the setBorder() method, you can specify the border that a componentdisplays around its edges. You can specify that component have extra space around its

    edges using an EmptyBorder instance.

    b). Double Buffering- It can improve the appearance of frequently changing

    components. Now you do not have to write the double buffering code because Swing

    provides it for you. By default Swing components are double buffered.

    c). Tool Tips- By specifying a string with the setToolTipNext() method, you can provide

    help to users of a components. When the cursor pauses over the components, the specified

    string is displayed in small window near the component.

    d). Look and Feel- Subject to the security restriction, you can choose the look and feel

    used by all Swing components by invoking the UIManager.setLookAndFeel() method.

    3. There is an almost-equivalent Swing component for most AWT components.

    4. Instead of adding components directly to frames or applets, we can use the

    content pane.

    Add to content pane via getContentPane().add Replace content pane via setContentPane5. Model-View-Controller architecture let us change the internal data representation

    for lists, trees, tables, etc.

    6. Default "look and feel" is a Java-specific one.

    Need special call to get native look Default called "Java look & feel"

    7. Mixing AWT and Swing is doomed

  • 7/30/2019 Final java editor

    15/84

    15

    AWT components are always on top, and z-ordering problems catch you in many

    unexpected ways. Stick with the AWT or move completely to Swing.

    4.1.3 Other Packages Used

    4.1.3.1 Java.awt

    The Abstract Window Toolkit (AWT) is Java's original platform-independent windowing,

    graphics, and user-interface widget toolkit. The AWT is now part of the Java Foundation

    Classes (JFC) the standard API for providing a graphical user interface (GUI) for a

    Java program.

    AWT is also the GUI toolkit for a number of Java ME profiles. For example, ConnectedDevice Configuration profiles require Java runtimes on mobile telephones to support

    AWT.

    4.1.3.2 Java.net

    The java.net package provides special IO routines for networks, allowing HTTP requests,

    as well as other common transactions.

    4.1.3.3 Java.awt.event

    Provide interfaces and classes for dealing with different types of events fired by AWT

    components.

    4.1.3.4 Javax.swing.event

    Provide interfaces and classes for dealing with different types of events fired by Swing

    components.

    4.1.3.5 Java.util

    Data structures that aggregate objects are the focus of the java.util package. Included in

    the package is the Collections API, an organized data structure hierarchy influenced

    heavily by the design patterns considerations.

  • 7/30/2019 Final java editor

    16/84

    16

    4.1.3.6 Java.sql

    An implementation of the JDBC API (used to access SQL databases) is grouped into the

    java.sql package.

    4.1.3.7 Javax.mail

    The JavaMail API provides a platform-independent and protocol-independent framework

    to build mail and messaging applications. The JavaMail API is available as an optional

    package for use with Java SE platform and is also included in the Java EE platform.

    4.1.3.8 Javax.mail.internet

    Contains classes specific to Internet mail systems.

    4.1.3.9 javax.mail.Authenticator

    The class Authenticator represents an object that knows how to obtain authentication for a

    network connection. Usually, it will do this by prompting the user for information.

    4.1.3.10 Javax.mail.PasswordAuthentication

    The class PasswordAuthentication is a data holder that is used by Authenticator. It issimply a repository for a user name and a password.

    4.2 JDBC INTRODUCTION

    The JDBC is a set of the database access classes. The very term JDBC stands for Java

    Database Connectivity. It was developed by Java Soft. JDBC technology is an API

    (Application Program Interface) that allows virtual access to any tabular data source from

    the Java programming language by means of some connecting software called Drivers. It

    provides cross-DBMS connectivity to a wide range of SQL databases. JDBC defines a set

    of interfaces to enable developers to access data independently of the actual database

    product used to store the data. JDBC allow Java applets, Servlets, and application to

    access data in famous database management systems.

    It also provides access to other tabular data sources, such as spread sheets or flat files.

    The JDBC API allows developers to take advantage of the Java platform's "Write Once,

  • 7/30/2019 Final java editor

    17/84

    17

    Run Anywhere" capabilities for industrial strength, cross-platform applications that

    require access to enterprise data. With a JDBC technology-enabled driver, a developer

    can easily connect all corporate data even in a heterogeneous environment. The JDBC

    API is the industry standard for database-independent connectivity between the Java

    programming language and a wide range of databases. The JDBC API makes it possible

    to do three things:

    Establish a connection with a database or access any tabular data source

    Send SQL statements

    Process the results

    4.2.1 JDBC Architecture

    Fig 4.2.1 JDBC Architecture

    JDBC itself provides a JDBC-ODBC Bridge that translates JDBC to ODBC through

    which we can access ODBC complete database

    4.2.2 Evolution of JDBC

    Earlier we had to use languages database i.e. FoxPro and Dbase etc. Microsoft

    introduced Data Access Objects (DAO) that allowed use of Ms-Access with any

    Microsoft Language. Later Microsoft Started Remote Data Object (RDO) in which we

    can use any database, but it was complex.

  • 7/30/2019 Final java editor

    18/84

    18

    Then came ODBC that allowed connectivity of any Database with Microsoft Languages

    and it removed complexity. In Microsoft, DLL is a API. In java collection of classes and

    interfaces is called an API that provides same functionality

    4.2.3 Java Database Connectivity Steps

    Before you can create a java JDBC connection to the database, you must first import the

    java.sql package.

    import java.sql.*; The star ( * ) indicates that all of the classes in the package java.sql are

    to be imported.

    4.2.3.1 Loading a Database Driver

    In this step of the JDBC connection process, we load the driver class by calling

    Class.forName(driver_class) with the Driver class name as an argument. forName is a

    static method and is used to load Drivers in Primary memory. Once loaded, the Driver

    class creates an instance of itself. A client can connect to Database Server through JDBC

    Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC

    Bridge driver is commonly used.

    The return type of the Class.forName(String ClassName) method is Class. Class is a

    class in java.lang package. E.g.

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any other driver

    4.2.3.2. Creating a JDBC ODBC Connection

    The JDBC DriverManager class defines objects which can connect Java applications to a

    JDBC driver. DriverManager is considered the backbone of JDBC architecture.

    DriverManager class manages the JDBC drivers that are installed on the system. Its

    getConnection() method is used to establish a connection to a database. It uses a

    username, password, and a JDBC URL to establish a connection to the database and

    returns a connection object. A JDBC Connection represents a session/connection with a

    specific database. Within the context of a Connection, SQL, PL/SQL statements are

  • 7/30/2019 Final java editor

    19/84

    19

    executed and results are returned. An application can have one or more connections with

    a single database, or it can have many connections with different databases. A Connection

    object provides metadata i.e. information about the database, tables, and fields. It also

    contains methods to deal with transactions.

    JDBC URL Syntax: jdbc: :

    JDBC URL Example: jdbc: : Each driver has its own

    subprotocol

    Each sub protocol has its own syntax for the source. Were using the JDBC ODBC sub

    protocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver.Eg.

    Connection con =DriverManager.getConnection(Jdbc.odbc.MyData)

    4.2.3.3 Creating a JDBC Statement Object

    Once a connection is obtained we can interact with the database. Connection interface

    defines methods for interacting with the database via the established connection. To

    execute SQL statements, you need to instantiate a Statement object from your connection

    object by using the createStatement() method.

    Statement statement = con.createStatement();

    A statement object is used to send and execute SQL statements to a database.

    Three kinds of Statements:-

    1) Statement: Execute simple sql queries without parameters.Statement createStatement();

    Creates an SQL Statement object.

    2) Prepared Statement: Execute precompiled sql queries with or without parameters.PreparedStatement prepareStatement(String sql);

    returns a new PreparedStatement object. PreparedStatement objects are precompiled

  • 7/30/2019 Final java editor

    20/84

    20

    3) SQL statements.Callable Statement: Execute a call to a database stored procedure.

    CallableStatement prepareCall(String sql)

    returns a new CallableStatement object. CallableStatement objects are SQL stored

    procedure call statements.

    4.2.3.4. Executing a SQL statement with the Statement object, and returning a JDBC

    ResultSet.

    Statement interface defines methods that are used to interact with database via the

    execution of SQL statements. The Statement class has three methods for executing

    statements:

    executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to

    use is executeQuery. For statements that create or modify tables, the method to use is

    executeUpdate.

    Note: Statements that creates a table, alter a table, or drop a table are all examples of

    DDL statements and are executed with the method executeUpdate.

    execute() executes an SQL statement that is written as String object.

    ResultSet provides access to a table of data generated by executing a Statement. The table

    rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row

    of data. The next() method is used to successively step through the rows of the tabular

    results.

    ResultSetMetaData Interface holds information on the types and properties of the

    columns in a ResultSet. It is constructed from the Connection object.

    4.2.4 JDBC Resultset and Cursor

    The rows that satisfy a particular query are called the result set. The number of rows

    returned in a result set can be zero or more. A user can access the data in a result set using

    a cursor one row at a time from top to bottom. A cursor can be thought of as a pointer to

  • 7/30/2019 Final java editor

    21/84

    21

    the rows of the result set that has the ability to keep track of which row is currently being

    accessed. The JDBC API supports a cursor to move both forward and backward and also

    allowing it to move to a specified row or to a row whose position is relative to another

    row. The JDBC Resultset example is shown in the next sections to follow.

    4.2.4.1 Types of Result Sets

    The ResultSet interface provides methods for retrieving and manipulating the results of

    executed queries, and ResultSet objects can have different functionality and

    characteristics. These characteristics are result set type, result set concurrency, and cursor

    holdability.

    The type of a ResultSet object determines the level of its functionality in two areas: the

    ways in which the cursor can be manipulated, and how concurrent changes made to the

    underlying data source are reflected by the ResultSet object.

    The sensitivity of the ResultSet object is determined by one of three different ResultSet

    types:

    TYPE_FORWARD_ONLY the result set is not scrollable i.e. the cursor moves only

    forward, from before the first row to after the last row.

    TYPE_SCROLL_INSENSITIVE the result set is scrollable; its cursor can move

    both forward and backward relative to the current position,and it can move to an absolute

    position.

    TYPE_SCROLL_SENSITIVE the result set is scrollable; its cursor can move both

    forward and backward relative to the current position, and it can move to an absolute

    position.Before you can take advantage of these features, however, you need to create a

    scrollable ResultSet object. The following line of code illustrates one way to create a

    scrollable ResultSet object:

    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,

    ResultSet.CONCUR_READ_ONLY);

  • 7/30/2019 Final java editor

    22/84

    22

    ResultSet rs = stmt.executeQuery(..);

    The first argument is one of three constants added to the ResultSet API to indicate the

    type of a ResultSet object: TYPE_FORWARD_ONLY,TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second

    argument is one of two ResultSet constants for specifying whether a result set is read-only

    or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. If you do not

    specify any constants for the type and updatability of a ResultSet object, you will

    automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

    4.2.5 Result Set Methods

    When a ResultSet object is first created, the cursor is positioned before the first row. To

    move the cursor, you can use the following methods:

    next()moves the cursor forward one row. Returns true if the cursor is now positioned

    on a row and false if the cursor is positioned after the last row.

    previous() moves the cursor backwards one row. Returns true if the cursor is now

    positioned on a row and false if the cursor is positioned before the first row.

    first() moves the cursor to the first row in the ResultSet object. Returns true if the

    cursor is now positioned on the first row and false if the ResultSet object does not

    contain any rows.

    last() moves the cursor to the last row in the ResultSet object. Returns true if the

    cursor is now positioned on the last row and false if the ResultSet object does not

    contain any rows.

    beforeFirst() positions the cursor at the start of the ResultSet object, before the first

    row. If the ResultSet object does not contain any rows, this method hasno effect.

    afterLast()positions the cursor at the end of the ResultSet object, after the last row. If

    the ResultSet object does not contain any rows, this method has no effect.

    relative(int rows)moves the cursor relative to its current position.

    absolute(int n)positions the cursor on the n-th row of the ResultSet object.

  • 7/30/2019 Final java editor

    23/84

    23

    4.2.6 JDBC Driver Types

    JDBC drivers are divided into four types or levels. The different types of JDBC drivers

    are:

    1) Type 1: JDBC-ODBC Bridge driver (Bridge)2) Type 2: Native-API/partly Java driver (Native)3) Type 3: All Java/Net-protocol driver (Middleware)4) Type 4: All Java/Native-protocol driver (Pure)

    4.2.6.1 Type 1 JDBC Driver (JDBC-ODBC Bridge driver)

    The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the

    ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended

    only for experimental use or when no other alternative is available.

    Advantage

    The JDBC-ODBC Bridge allows access to almost any database, since the databases

    ODBC drivers are already available.

    Disadvantages

    1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.

    2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC

    driver, then to the database, and this applies even in the reverse process. They are the

    slowest of all driver types.

    3. The client system requires the ODBC Installation to use the driver.

    4. Not good for the Web.

  • 7/30/2019 Final java editor

    24/84

    24

    4.2.6.2 Type 2 JDBC Driver (Native-API/partly Java driver)

    The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC

    calls into database-specific calls i.e. this driver is specific to a particular database. Somedistinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will

    have oracle native api.

    Advantage

    The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better

    performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less

    than that of TypeAlso it uses Native api which is Database specific.

    Disadvantage

    1. Native API must be installed in the Client System and hence type 2 drivers cannot be

    used for the Internet.

    2. Like Type 1 drivers, its not written in Java Language which forms a portability issue.

    3. If we change the Database we have to change the native api as it is specific to a

    database

    4. Mostly obsolete now

    5. Usually not thread safe.

    4.2.6.3Type 3 JDBC Driver (All Java/Net-protocol driver)

    Type 3 database requests are passed through the network to the middle-tier server. The

    middle-tier then translates the request to the database. If the middle-tier server can in turn

    use Type1, Type 2 or Type 4 drivers.

    Advantage

    1. This driver is server-based, so there is no need for any vendor database library to be

    present on client machines.

    2. This driver is fully written in Java and hence Portable. It is suitable for the web.

  • 7/30/2019 Final java editor

    25/84

    25

    3. There are many opportunities to optimize portability, performance, and scalability.

    4. The net protocol can be designed to make the client JDBC driver very small and fast to

    load.

    5. The type 3 driver typically provides support for features such as caching (connections,

    query results, and so on), load balancing, and advanced system administration such as

    logging and auditing.

    6. This driver is very flexible allows access to multiple databases using one driver.

    7. They are the most efficient amongst all driver types.

    Disadvantage

    It requires another server application to install and maintain. Traversing the recordset may

    take longer, since the data comes through the backend server.

    4.2.6.4 Type 4 JDBC Driver (Native-protocol/all-Java driver)

    The Type 4 uses java networking libraries to communicate directly with the database

    server.

    Advantage

    1. The major benefit of using a type 4 jdbc drivers are that they are completely written in

    Java to achieve platform independence and eliminate deployment administration issues. It

    is most suitable for the web.

    2. Number of translation layers is very less i.e. type 4 JDBC drivers dont have to

    translate database requests to ODBC or a native connectivity interface or to pass the

    request on to another server, performance is typically quite good.

    3. You dont need to install special software on the client or server. Further, these drivers

    can be downloaded dynamically.

  • 7/30/2019 Final java editor

    26/84

    26

    Disadvantage

    With type 4 drivers, the user needs a different driver for each database.

    4.3 JAVA MAIL API

    4.3.1 Introduction to Java Mail API

    The Java Mail API is a standard extension to java that provides a class library for email

    clients (mail sender and receiver). Programs use the Java Mail API to communicate with

    the SMTP and POP servers to send and receive emails.

    The Java Mail API is a high level representation of the basic components of any Email

    System. The components are represented by abstract classes in javax.mail package. For

    instance the Message(Abstract class) represents an email message. It declares Abstract

    Methods that which are implemented by its subclass MimeMessage. The abstract class

    folder represents a message container. It declares abstract method to get message from a

    Folder.

    Subclasses of these classes implement the abstract methods. We use MimeMessage

    instead of Message and Internet Address instead of Address.

    4.3.2 Simple Mail Transfer Protocol

    Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (e-mail)

    transmission across Internet Protocol (IP) networks. While electronic mail servers and

    other mail transfer agents use SMTP to send and receive mail messages, user-level client

    mail applications typically only use SMTP for sending messages to a mail server for

    relaying.

    4.3.3 Post Office Protocol (pop3)

    In computing, the Post Office Protocol (POP) is an application-layer Internet standard

    protocol used by local e-mail clients to retrieve e-mail from a remote server over a

    TCP/IP connection.[1] POP and IMAP (Internet Message Access Protocol) are the two

    most prevalent Internet standard protocols for e-mail retrieval.[2] Virtually all modern e-

    mail clients and servers support both. The POP protocol has been developed through

  • 7/30/2019 Final java editor

    27/84

    27

    several versions, with version 3 (POP3) being the current standard. Most webmail service

    providers such as Hotmail, Gmail and Yahoo! Mail also provide IMAP and POP3 service

    Fig 4.3.3 SMTP and POP

    4.3.4 Sending Email

    The Java Mail API provides everything that our program needs to send email. To send

    Email our program needs to follow these 8 basic steps.

    NOTE: SMTP and POP3 are run on port no 25 and 110 by default.Gmail does not use

    default port no. it uses 465 for SMTP and 995 for POP3.

    1)Set the mail.host property to point to the local mail server. e.g.

    Properties p=new Properties();

    p.put("mail.smtp.host","smtp.gmail.com");

    p.put("mail.smtp.port","465");

    p.put("mail.smtp.auth","true");

  • 7/30/2019 Final java editor

    28/84

    28

    p.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");

    2) Start the mail Session with Session getInstance() method

    The Session object represents an on-going communication between a program and mail

    server. E.g.

    Session session=Session.getInstance(p, new SimpleMailAuthentication(from,pwd));

    property(p) will tell the server the properties and Authenticator object is used to

    authenticate users

    3) Create a new Message object by instantiating one of its subclasses. The session

    object is used to create a message object. e.g.

    Message msg= new MimeMessage(session);

    Message is an abstract class and MimeMessage is inherited class of Message class.

    Message represents Email. We can also specify to, cc and bcc in Email.

    Set the Message from address (InternetAddress object). The setFrom() allows us to

    specify who is sending the message. E.g. msg.setFrom(new InternetAddress(String email,

    String signature);

    Set the Message to Address, the setRecipient () specify the recipient. E.g.

    msg.setRecipient(MessageRecipientType, new InternetAddress(String email);

    MessageRecipientType can have any of the 3 values-

    MessageRecipientType.TO

    MessageRecipient.CC

    MessageRecipient.BCC

    4) Set the Message Subject. E.g. msg.setSubject(String); setSubject() method is used

    to add Subject to the Email.

    5) Set the content of the Message. E.g. msg.setContent(String);

  • 7/30/2019 Final java editor

    29/84

    29

    6) Send the Message to the recipient using send() method of Transport Class. E.g.

    Transport.send(msg);

    4.3.5 Receiving Email

    Following steps are used to receive email.

    1) Set up the Properties, that is used for Connection.2) Get a Session object in session.getDefaultInstance() method.3) Use the Session getStore() method to return a store.4)

    Connect to the Store, this connects the POP server.

    5) Get the Inbox Folder from the Store with the getFolder() method. E.g. Inbox,Personal etc.

    6) Open the Folder (e.g. Inbox), we need to specify mode i.e., Read only orRead/Write.

    7) Get the Message from the Folder as an Array of Message objects.8) Iterate through the array of messages, processing each element using the methodsof Message class.

  • 7/30/2019 Final java editor

    30/84

    30

    CHAPTER-5

    IMPLEMENTATION

    5.1 DATABASE MANAGEMENT

    A database management system (DBMS) is a software package with computer programs

    that controls the creation, maintenance, and use of a database. It allows organizations to

    conveniently develop databases for various applications. A database is an integrated

    collection of data records, files, and other objects. A DBMS allows different user

    application programs to concurrently access the same database. DBMSs may use a variety

    of database models, such as the relational model or object model, to conveniently

    describe and support applications. It typically supports query languages, which are in fact

    high-level programming languages, dedicated database languages that considerably

    simplify writing database application programs. Database languages also simplify the

    database organization as well as retrieving and presenting information from it. A DBMS

    provides facilities for controlling data access, enforcing data integrity, managing

    concurrency control, and recovering the database after failures and restoring it from

    backup files, as well as maintaining database security.

    5.2 SQL

    SQL (sometimes referred to as Structured Query Language) is a special-purpose

    programming language designed for managing data in relational database management

    systems (RDBMS).

    Originally based upon relational algebra and tuple relational calculus,[4] its scope

    includes data insert, query, update and delete, schema creation and modification, and data

    access control.

    SQL was one of the first commercial languages for Edgar F. Codd's relational model, as

    described in his influential 1970 paper, "A Relational Model of Data for Large Shared

    Data Banks". Despite not adhering to the relational model as described by Codd, it

    became the most widely used database language. Although SQL is often described as, and

    to a great extent is, a declarative language, it also includes procedural elements. SQL

  • 7/30/2019 Final java editor

    31/84

    31

    became a standard of the American National Standards Institute (ANSI) in 1986 and of

    the International Organization for Standards (ISO) in 1987. Since then, the standard has

    been enhanced several times with added features. However, issues of SQL code

    portability between major RDBMS products still exist due to lack of full compliance

    with, or different interpretations of, the standard. Among the reasons mentioned are the

    large size and incomplete specification of the standard, as well as vendor lock-in. The

    most common operation in SQL is the query, which is performed with the declarative

    SELECT statement. SELECT retrieves data from one or more tables, or expressions.

    Standard SELECT statements have no persistent effects on the database. Some non-

    standard implementations of SELECT can have persistent effects, such as the SELECT

    INTO syntax that exists in some databases.

    Queries allow the user to describe desired data, leaving the database management system

    (DBMS) responsible for planning, optimizing, and performing the physical operations

    necessary to produce that result as it chooses.

    A query includes a list of columns to be included in the final result immediately following

    the SELECT keyword. An asterisk ("*") can also be used to specify that the query should

    return all columns of the queried tables. SELECT is the most complex statement in SQL,with optional keywords and clauses that include:

    The FROM clause which indicates the table(s) from which data is to be retrieved.The FROM clause can include optional JOIN subclauses to specify the rules for joining

    tables.

    The WHERE clause includes a comparison predicate, which restricts the rowsreturned by the query. The WHERE clause eliminates all rows from the result set for

    which the comparison predicate does not evaluate to True.

    The GROUP BY clause is used to project rows having common values into asmaller set of rows. GROUP BY is often used in conjunction with SQL aggregation

    functions or to eliminate duplicate rows from a result set. The WHERE clause is applied

    before the GROUP BY clause.

  • 7/30/2019 Final java editor

    32/84

    32

    The HAVING clause includes a predicate used to filter rows resulting from theGROUP BY clause. Because it acts on the results of the GROUP BY clause, aggregation

    functions can be used in the HAVING clause predicate.

    The ORDER BY clause identifies which columns are used to sort the resultingdata, and in which direction they should be sorted (options are ascending or descending).

    Without an ORDER BY clause, the order of rows returned by an SQL query is undefined.

    5.3 ARCHITECTURE OF DATABASE USED

    There are total 5 tables in mail database which are used for saving data

    Data Definitions of all 5 tables are -

    1) Mail-this table is used for login page of this software.Table 5.3.1-Mail Relation

    Field Type

    username Varchar(50)

    offpassword Varchar(50)

    emailid Varchar(100)

    onpassword Varchar(100)

  • 7/30/2019 Final java editor

    33/84

    33

    2) Inbox- Used to save mails if application cant connect to the internet

    Table 5.3.2-Outbox Relation

    Field Type

    Sent_Date Varchar(500)

    Sender Varchar(1000)

    Subject Varchar(2000)

    Body Varchar(4000)

    No. Integer

    5.4 TESTING

    5.4.1 INTRODUCTION

    The purpose of system testing is to identify and correct errors in the system and also to

    judge if the system meets the requirements of the user or not. There are three levels of

    system testing. They are as follows:

    5.4.2 UNIT TESTING:

    This type of testing focuses on the verification of the smallest unit of software design

    namely the module. Using the procedural description as a guide, important control paths

    are tested to uncover the errors within the boundary of a module. Unit testing is normally

    white-box oriented, and the steps can be conducted in parallel for multiple modules. In

    this project the sub-modules have been individually tested.

    Following checks were made:

    Given set of data was taken as input to the module and the output was observed

    Logic and boundary conditions for input and output were also checked

    Interfaces between two modules were also checked

  • 7/30/2019 Final java editor

    34/84

    34

    Runtime Exceptions were thrown which were detected and rectified by taking the

    Stack Trace

    Also all the possible situation were anticipated with the help of the user to conductthorough tests of the system.

    5.4.3 INTEGRATION TESTING:

    In this type of testing the main aim is to take the unit tested modules and build a program

    structure which can be directed and dictated by the design.

    This includes:

    Top-down Testing

    Bottom-up testing

    Regression Testing

    The last of the above was particularly important in this project which helped in ensuring

    changes without introducing unintended behaviour in addition.

    5.4.4 SYSTEM TESTING:

    This type of testing consists of a series of tests whose primary purpose is to fully exercise

    the computer based systemall work to verify that system elements have been properly

    integrated and that they perform specified functions.

    When the individual program modules are working, we combined the modules into single

    working system. This integration was planned and conducted in such a way that whenever

    an error occurs we get an idea about the source of it.

    The entire system was viewed as a hierarchy of modules. We began with the module at

    the highest level of design and worked down. Then the next modules to be tested were

    those that called previously tested modules.

  • 7/30/2019 Final java editor

    35/84

    35

    5.4.5 FUNCTIONAL TESTING:

    Once it was certain that information passed between modules according to the design

    description, the system was tested to assure whether the functions describing therequirement specification were performed by the system.

    5.4.6 ACCEPTANCE TESTING:

    When the functional test completes The user gets involved to make sure that the system

    works according to the users expectation. System validation checks the quality of the

    software in both simulated and live environments. It has two phases.

    1) Alpha Testing:In this the software goes through a phase in which errors and failures based on simulated

    user requirements are verified and studied. The modified software is then subjected to

    Beta Testing.

    2) Beta Testing:This is testing the software in the actual users site or a live environment .The system is

    used regularly with live transaction .After a scheduled time, failures and errors are

    documented and final correction and enhancements are made before the package is

    released for use.

  • 7/30/2019 Final java editor

    36/84

    36

    5.5 SNAPSHOTS

    Fig 5.1- Login Panel

    Fig 5.2- Online Or Offline Selection

  • 7/30/2019 Final java editor

    37/84

    37

    Fig 5.3-Compose Email

    Fig 5.4- Inbox

  • 7/30/2019 Final java editor

    38/84

    38

    Fig 5.5Relation LOGIN

    Fig 5.6Relation INBOX

  • 7/30/2019 Final java editor

    39/84

    39

    CHAPTER -6

    CONCLUSION

    Outlook Application is created on Java which is both robust and secure and can be

    installed and executed on different machine and various platforms.

    The Application consumes very less memory space. This application provides basic

    functionalities of Microsoft Outlook Express. The interactive and easy to understand user-

    interface provides an efficient way to the end/novice user to work easily and efficiently.

    The Outlook Application can be further enhanced to support different languages like

    Hindi, French etc. and basic utilities like Calculator, Calendar, Alarm and Scheduler can

    be implemented within the Application interface to provide solution to basic necessity

    required by the User.

    There are few limitations in this project which can be overcome in time-

    Till date the application supports only single user at a time and the DatabaseRelations gets erased whenever a new username is provided.

    The application works only with Googles Gmail which provide free SMTP andPOP servers. While other Mail Server like Yahoo Mail charge for providing connections

    to their SMTP and POP servers.

    Overall, the basic advantage of using the Front End as Java and Back End as MySQL is

    that both are available as open-source and more and more updations are possible.

  • 7/30/2019 Final java editor

    40/84

    40

    REFERENCES

    [1].Herbert Schildts, Complete Reference Java 6, Seventh Edition[2].OReilly, JDBC 2, Second Edition[3].Wikipedia.org

    // import statements

    import javax.swing.*;

    import javax.swing.event.*;

    import java.awt.*;

    import java.awt.event.*;

    import java.io.*;

    import javax.swing.text.*;

    /**

    A class for creating a stack with Object items. it's used for undo/redo operations

    */

    class StackArray{

    Object[] items;

    private int maxSize;

    private int stackTop;

    public StackArray(int s) {

  • 7/30/2019 Final java editor

    41/84

    41

    maxSize = s;

    items = new Object[maxSize];

    stackTop = -1;

    }

    public boolean isEmpty() {

    return (stackTop == -1);

    }

    public boolean isFull() {

    return (stackTop == maxSize - 1);

    }

    public void push(Object d) throws StackOutOfBoundsException{

    if(isFull()){

    for(int i=0;i

  • 7/30/2019 Final java editor

    42/84

    42

    else

    stackTop--;

    }

    public Object peek() throws StackOutOfBoundsException{

    if(isEmpty())

    throw new StackOutOfBoundsException("Stack Empty");

    else

    return items[stackTop];

    }

    }

    /**

    A class for handling stack errors.

    */

    class StackOutOfBoundsException extends IndexOutOfBoundsException {

    public StackOutOfBoundsException() {} // default constructor

    public StackOutOfBoundsException(String problem) {

    super(problem); // let superclass constructor handle the argument

    }

    }

    /**

    A class for compiling and executing the java source code in a separate thread

    @see Thread.

  • 7/30/2019 Final java editor

    43/84

    43

    */

    class JavaCommands extends Thread{

    static String path = ""; // this is the path to the java bin directory

    // the main program sets this each time the program is loaded.

    String JAVA_HOME = System.getProperty("java.home");

    String java_dir

    =JAVA_HOME.substring(0,JAVA_HOME.lastIndexOf(File.separator));

    String compileCommand=java_dir+File.separator+"bin"+File.separator+"javac.exe ";

    String runClassCommand

    =java_dir+File.separator+"bin"+File.separator+"java.exe ";

    /**

    needed to get streams from JDK.

    */

    Process compile;

    /**

    used to retrieve errors when compiling a file.

    */

    String errors;

    /**

    used for getting output from the jdk

    */

    BufferedReader br;

  • 7/30/2019 Final java editor

    44/84

    44

    /**

    command for thread to run

    */

    String command;

    String classname,classpath;

    /**

    This method compiles a .java file.

    @param filename the complete path of the source code file (.java).

    @see Exception

    */

    public void compile(String filename){

    String line = "";

    JEditor.errOutput.setText("");

    try{

    compile = Runtime.getRuntime().exec(compileCommand

    +"\""+filename+"\"");

    br = new BufferedReader(new

    InputStreamReader(compile.getErrorStream()));

    }

    catch(Exception e){

    JEditor.errOutput.append("Error: "+e);

    return;

    }

  • 7/30/2019 Final java editor

    45/84

    45

    // now we check for errors in the user code

    try{

    while (true) {

    line = br.readLine();

    if(line != null){

    System.err.println(line + '\n');

    JEditor.errOutput.append(line+'\n');

    }

    else

    {

    br.close();

    break;

    }

    }

    }

    catch(Exception e)

    {

    JEditor.errOutput.append("\nAttempt to check for errors failed");

    compile.destroy();

    return;

    }

    JEditor.errOutput.append('\n'+"Process completed");

  • 7/30/2019 Final java editor

    46/84

    46

    JEditor.errOutput.setCaretPosition(0);

    }

    /**

    This method invokes the run() method to execute a .class file.

    @param file the compelete path of the source code file

    */

    public void runClass(String file)

    {

    Thread thead = new Thread(this);

    command = runClassCommand;

    classname=file.substring(file.lastIndexOf(File.separator)+1,file.length()-

    5);

    classpath=file.substring(0,file.lastIndexOf(File.separator));

    start();

    }

    /**

    This method executes a .class file in a separate thread

    @see Thread

    */

    public void run()

    {

    try

  • 7/30/2019 Final java editor

    47/84

    47

    {

    compile = Runtime.getRuntime().exec(command +"-classpath "+"\""+classpath+"\"

    "+classname);

    }

    catch(Exception e)

    {

    JEditor.errOutput.append("\nFailed to execute java.exe " + "check the

    directory and try again");

    return;

    }

    try

    {

    BufferedReader br = new BufferedReader(new

    InputStreamReader(compile.getInputStream()));

    while(true)

    {

    String line = br.readLine();

    if (line == null)

    {

    br.close();

    break;

    }

  • 7/30/2019 Final java editor

    48/84

    48

    else if(line.length() > 0)

    JEditor.errOutput.append("\nSystem: " + line + '\n');

    }

    compile.destroy();

    }

    catch(Exception e)

    {

    JEditor.errOutput.append("\nRedirecting System.out failed");

    compile.destroy();

    }

    JEditor.errOutput.append('\n' + "Exception in thread [main]

    java.lang.NoClassDefFoundError: "+classname);

    }

    }

    /**

    the main class for creating the frame and mainpulating the commands.

    */

    public class JEditor extends JFrame implements ActionListener,CaretListener{

    JPanel northPanel = new JPanel();

    JToolBar toolBar = new JToolBar();

  • 7/30/2019 Final java editor

    49/84

    49

    JDesktopPane desktop;

    JTabbedPane desktopTabbedPane = new

    JTabbedPane(SwingConstants.BOTTOM);

    JPanel statusPanel=new JPanel(new BorderLayout());

    JSplitPane splitPaneV;

    JScrollPane textareaScrollPane;

    JLabel col_row=new JLabel("Col: " + 0 + " Row: " + 0);

    int document = 1,tabIndex=0;

    String filePath;

    JButton

    newButton,openButton,saveButton,saveAsButton,cutButton,copyButton,pasteButton,und

    oButton,redoButton,indentButton,undentButton,compileButton,runButton;

    JButton[] toolbarButton=new JButton[13];

    String [] toolbarImages=

    {"new","open","save","saveas","cut","copy","paste","undo","redo","indent","undent","co

    mpile","run"};

    JInternalFrame jif[]=new JInternalFrame[50];

    JTextArea[] jta=new JTextArea[50];

    boolean[] isChanged=new boolean[50];

    String[] savedFileName=new String[50];

    Font myFont=new Font("Courier",Font.PLAIN,12);

    static JTextArea errOutput=new JTextArea();

    JMenuBar jmb = new JMenuBar();

    JMenu jmFile = new JMenu(" File ");

  • 7/30/2019 Final java editor

    50/84

    50

    JMenu jmEdit = new JMenu(" Edit ");

    JMenu jmBuild = new JMenu(" Build ");

    JMenu jmHelp = new JMenu(" Help ");

    JMenuItem jmiNew,jmiOpen,jmiClose,jmiSave,jmiSaveAs,jmiExit;

    JMenuItem jmiCut,jmiCopy,jmiPaste,jmiSelectAll,jmiGoTo,jmiUndo;

    JMenuItem jmiCompile,jmiExecute;

    JMenuItem jmiHelp,jmiAbout;

    // Go to frame components

    JTextArea textarea;

    JTextField linenumber=new JTextField(15);

    JFrame jfGoto=new JFrame("Go to line number");

    JLabel jlFromTo=new JLabel();

    JButton jbGoto=new JButton("Go");

    //creates two stacks of size 100

    StackArray string_stack = new StackArray(100);

    StackArray location_stack = new StackArray(100);

    public JEditor(){

    Container cp=getContentPane();

    //creates menus

    setJMenuBar(menuBar());

    northPanel.setLayout(new BorderLayout());

    //adding buttons to the toolbar

  • 7/30/2019 Final java editor

    51/84

    51

    addButtons(toolBar);

    //adding the toolbar to the panel

    northPanel.add("North", toolBar);

    //adding the panel to the contentpane

    cp.add("North",northPanel);

    splitPaneV = new JSplitPane(JSplitPane.VERTICAL_SPLIT );

    Dimension minimumSize = new Dimension(0, 500);

    desktopTabbedPane.setMinimumSize(minimumSize);

    splitPaneV.setLeftComponent(desktopTabbedPane);

    splitPaneV.setRightComponent(new JScrollPane(errOutput));

    splitPaneV.setOneTouchExpandable(true);

    cp.add("Center",splitPaneV);

    statusPanel.add(col_row,BorderLayout.EAST);

    cp.add("South",statusPanel);

    int width=Toolkit.getDefaultToolkit().getScreenSize().width;

    int height=Toolkit.getDefaultToolkit().getScreenSize().height;

    setBounds( 0, 0, width, height - 50 );

    setTitle("JEditor v1.5");

    show();

    addWindowListener(new WindowAdapter(){

    public void windowClosing(WindowEvent e){

    closeAllFrames();

  • 7/30/2019 Final java editor

    52/84

    52

    System.out.print("Thanks for using JEditor 1.0 :)\n");

    System.exit(0);

    }

    });

    }

    private JMenuBar menuBar(){

    //File Menu

    jmiNew = new JMenuItem(" New ");

    jmiNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,

    ActionEvent.CTRL_MASK));

    jmiNew.setIcon(new ImageIcon("images/new.gif"));

    jmiNew.addActionListener(this);

    jmFile.add(jmiNew);

    jmiOpen = new JMenuItem(" Open... ");

    jmiOpen.addActionListener(this);

    jmiOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,

    ActionEvent.CTRL_MASK));

    jmiOpen.setIcon(new ImageIcon("images/open.gif"));

    jmFile.add(jmiOpen);

    jmiClose = new JMenuItem(" Close ");

    jmiClose.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {

    closeFrame();

  • 7/30/2019 Final java editor

    53/84

    53

    }

    });

    jmFile.add(jmiClose);

    jmFile.addSeparator();

    jmiSave = new JMenuItem(" Save ");

    jmiSave.addActionListener(this);

    jmiSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,

    ActionEvent.CTRL_MASK));

    jmiSave.setIcon(new ImageIcon("images/save.gif"));

    jmFile.add(jmiSave);

    jmiSaveAs = new JMenuItem(" Save As... ");

    jmiSaveAs.addActionListener(this);

    jmiSaveAs.setIcon(new ImageIcon("images/saveas.gif"));

    jmFile.add(jmiSaveAs);

    jmFile.addSeparator();

    jmiExit = new JMenuItem(" Exit ");

    jmiExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,

    ActionEvent.ALT_MASK));

    jmiExit.addActionListener(this);

    jmFile.add(jmiExit);

    //Edit Menu

    jmiCut = new JMenuItem(" Cut ");

    jmiCut.setAccelerator(KeyStroke.getKeyStroke(

  • 7/30/2019 Final java editor

    54/84

    54

    KeyEvent.VK_X, ActionEvent.CTRL_MASK));

    jmiCut.addActionListener(this);

    jmEdit.add(jmiCut);

    jmiCopy = new JMenuItem(" Copy ");

    jmiCopy.addActionListener(this);

    jmiCopy.setAccelerator(KeyStroke.getKeyStroke(

    KeyEvent.VK_C, ActionEvent.CTRL_MASK));

    jmEdit.add(jmiCopy);

    jmiPaste = new JMenuItem(" Paste ");

    jmiPaste.addActionListener(this);

    jmiPaste.setAccelerator(KeyStroke.getKeyStroke(

    KeyEvent.VK_V, ActionEvent.CTRL_MASK));

    jmEdit.add(jmiPaste);

    jmEdit.addSeparator();

    jmiSelectAll = new JMenuItem(" Select All ");

    jmiSelectAll.setAccelerator(KeyStroke.getKeyStroke(

    KeyEvent.VK_A, ActionEvent.CTRL_MASK));

    jmiSelectAll.addActionListener(this);

    jmEdit.add(jmiSelectAll);

    jmiGoTo = new JMenuItem(" Go To... ");

    jmiGoTo.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {

  • 7/30/2019 Final java editor

    55/84

    55

    goTo();

    }

    });

    jmiGoTo.setAccelerator(KeyStroke.getKeyStroke(

    KeyEvent.VK_G, ActionEvent.CTRL_MASK));

    jmEdit.add(jmiGoTo);

    jmEdit.addSeparator();

    jmiUndo = new JMenuItem(" Undo ");

    jmiUndo.addActionListener(this);

    jmiUndo.setAccelerator(KeyStroke.getKeyStroke(

    KeyEvent.VK_Z, ActionEvent.CTRL_MASK));

    jmEdit.add(jmiUndo);

    //Build Menu

    jmiCompile = new JMenuItem(" Compile File ");

    jmiCompile.addActionListener(this);

    jmBuild.add(jmiCompile);

    jmiExecute = new JMenuItem(" Execute File ");

    jmiExecute.addActionListener(this);

    jmBuild.add(jmiExecute);

    //Help Menu

    jmiHelp = new JMenuItem(" Help Contents... ");

  • 7/30/2019 Final java editor

    56/84

    56

    jmHelp.add(jmiHelp);

    jmHelp.addSeparator();

    jmiAbout = new JMenuItem(" About ");

    jmHelp.add(jmiAbout);

    jmb.add(jmFile);

    jmb.add(jmEdit);

    jmb.add(jmBuild);

    jmb.add(jmHelp);

    return jmb;

    }

    /**

    this method is called when the caret position is updated.

    @param e the caret event.

    */

    public void caretUpdate(CaretEvent e)

    {

    try

    {

    int col = e.getDot() -

    jta[desktopTabbedPane.getSelectedIndex()].getLineStartOffset(jta[desktopTabbedPane.g

    etSelectedIndex()].getLineOfOffset(e.getDot())) + 1;

  • 7/30/2019 Final java editor

    57/84

    57

    int row=

    jta[desktopTabbedPane.getSelectedIndex()].getLineOfOffset(e.getDot()) + 1;

    col_row.setText("Col: " + col + " Row: " + row);

    }

    catch(Exception ex)

    {System.err.println(ex);}

    }

    /**

    this method is invoked when an action occurs.

    @param e the action event.

    */

    public void actionPerformed(ActionEvent e){

    if ((e.getSource()==jmiNew)||(e.getSource()==toolbarButton[0]))

    newFile(false,null);

    else if ((e.getSource()==jmiOpen)||(e.getSource()==toolbarButton[1]))

    openFile();

    else if ((e.getSource()==jmiSave)||(e.getSource()==toolbarButton[2]))

    save();

    else if ((e.getSource()==jmiSaveAs)||(e.getSource()==toolbarButton[3]))

    saveAs();

    else if(e.getSource()==jmiCut || e.getSource()==toolbarButton[4])

    cut();

  • 7/30/2019 Final java editor

    58/84

    58

    else if(e.getSource()==jmiCopy || e.getSource()==toolbarButton[5])

    jta[desktopTabbedPane.getSelectedIndex()].copy();

    else if(e.getSource()==jmiPaste || e.getSource()==toolbarButton[6])

    paste();

    else if(e.getSource()==jmiUndo || e.getSource()==toolbarButton[7])

    undo();

    else if(e.getSource()==toolbarButton[9])

    increaseIndent();

    else if(e.getSource()==toolbarButton[10])

    decreaseIndent();

    else if(e.getSource()==jmiCompile || e.getSource()==toolbarButton[11])

    compile();

    else if(e.getSource()==jmiExecute || e.getSource()==toolbarButton[12])

    execute();

    else if(e.getSource()==jmiSelectAll){

    jta[desktopTabbedPane.getSelectedIndex()].selectAll();

    jta[desktopTabbedPane.getSelectedIndex()].requestFocus();

    }

    else if(e.getSource()==jmiExit){

    closeAllFrames();

    System.exit(0);

  • 7/30/2019 Final java editor

    59/84

    59

    }

    }

    /**

    This method adds buttons to the toolbar.

    @param toolBar the toolbar to which the buttons are added.

    */

    void addButtons(JToolBar toolBar) {

    for (int i=0;i

  • 7/30/2019 Final java editor

    60/84

    60

    /**

    Transfers the selected range in the associated text model to the system clipboard,

    removing the contents from the model. Does nothing for null selections.

    */

    private void cut(){

    JTextArea t=jta[desktopTabbedPane.getSelectedIndex()];

    string_stack.push(t.getSelectedText());

    location_stack.push(""+t.getSelectionStart());

    toolbarButton[7].setEnabled(true); // enable undo button

    t.cut();

    t.requestFocus();

    }

    /**

    Transfers the contents of the system clipboard into the associated text model.

    */

    private void paste(){

    JTextArea t=jta[desktopTabbedPane.getSelectedIndex()];

    int start=t.getCaretPosition();

    t.paste();

    int end =t.getCaretPosition();

  • 7/30/2019 Final java editor

    61/84

    61

    t.setSelectionStart(start);

    t.setSelectionEnd(end);

    string_stack.push(t.getSelectedText());

    location_stack.push(""+start+","+end);

    toolbarButton[7].setEnabled(true); // enable undo button

    t.setSelectionStart(end);

    t.requestFocus();

    }

    /**

    Undo the last edit in the text component

    */

    private void undo(){

    JTextArea t=jta[desktopTabbedPane.getSelectedIndex()];

    try{

    String s=(String)location_stack.peek();

    if ((String)string_stack.peek()!=null)

    if(s.indexOf(",")>0){ //undoing paste command

    t.setSelectionStart(Integer.parseInt(s.substring(0,s.indexOf(","))));

    t.setSelectionEnd(Integer.parseInt(s.substring(s.indexOf(",")+1)));

    t.replaceSelection("");

  • 7/30/2019 Final java editor

    62/84

    62

    t.requestFocus();

    }

    else // undoing Backspace

    t.insert((String)string_stack.peek(),Integer.parseInt(s));

    else{ //undoing every typed character

    t.setSelectionStart(Integer.parseInt(s));

    t.setSelectionEnd(Integer.parseInt(s)+1);

    t.replaceSelection("");

    t.requestFocus();

    }

    string_stack.pop();

    location_stack.pop();

    if (location_stack.isEmpty()) toolbarButton[7].setEnabled(false);

    }

    catch(StackOutOfBoundsException e) {

    System.err.println("\n"+e);

    t.requestFocus();

    }

    }

    /**

  • 7/30/2019 Final java editor

    63/84

    63

    Creats a new empty text area inside an internal frame.

    */

    private void newFile(boolean isSaved,String filename){

    String title;

    if(!isSaved){ //if the file is not saved

    title = "Document" + document; document++;

    savedFileName[tabIndex]=null;

    }

    else

    title = filename;

    //create new desktop

    desktop=new JDesktopPane();

    //creates a new internal frmae

    jif[tabIndex] = new JInternalFrame(title,true,true,true,true);

    jta[tabIndex] = new JTextArea();

    jta[tabIndex].setFont(myFont);

    jta[tabIndex].setTabSize(4);

    jta[tabIndex].setCaretColor(Color.red);

    jta[tabIndex].setMargin(new Insets(0, 5, 0, 5));

    //adding the textarea to the scrollpane

    textareaScrollPane=new JScrollPane(jta[tabIndex]);

    //adding the scrollpane to the internal frame

  • 7/30/2019 Final java editor

    64/84

    64

    jif[tabIndex].getContentPane().add(textareaScrollPane);

    //creating a new icon

    ImageIcon icon = new ImageIcon("images/icon.gif");

    jif[tabIndex].setResizable(true);

    //sets the size of the internal frame

    jif[tabIndex].setSize(600, 395);

    //adding the internal frame to the desktop

    desktop.add(jif[tabIndex]);

    //adding the desktop to a new tab

    desktopTabbedPane.addTab(title,icon,desktop,title);

    //selects the current tab

    desktopTabbedPane.setSelectedIndex(tabIndex);

    //sets the frame to be visible

    jif[tabIndex].setVisible(true);

    isChanged[tabIndex]=false;

    //adding a caretlistener to the current textarea

    jta[tabIndex].addCaretListener(this);

    //adding a keylistener to the current textarea

    jta[tabIndex].addKeyListener(new KeyAdapter() {

    public void keyPressed(KeyEvent evt) {

    int key = evt.getKeyCode();

    JTextArea t=jta[desktopTabbedPane.getSelectedIndex()];

  • 7/30/2019 Final java editor

    65/84

    65

    // if the pressed key is Backspace

    if(key!=KeyEvent.VK_BACK_SPACE){

    string_stack.push(null);

    location_stack.push(""+t.getCaretPosition());

    toolbarButton[7].setEnabled(true);

    }

    else{

    char last_char=t.getText().charAt(t.getCaretPosition()-1);

    string_stack.push(""+last_char);

    location_stack.push(""+(t.getCaretPosition()-1));

    toolbarButton[7].setEnabled(true);

    }

    desktopTabbedPane.setTitleAt(desktopTabbedPane.getSelectedIndex(),jif[desktopTabbed

    Pane.getSelectedIndex()].getTitle()+" * ");

    isChanged[desktopTabbedPane.getSelectedIndex()]=true;

    }

    });

    //adding a listener to the internal frame

    jif[tabIndex].addInternalFrameListener(new InternalFrameAdapter(){

    public void internalFrameClosing(InternalFrameEvent e){

    closeFrame();

  • 7/30/2019 Final java editor

    66/84

    66

    }

    });

    tabIndex++;

    errOutput.setText("");

    for (int i=2;i

  • 7/30/2019 Final java editor

    67/84

    67

    } else if (dot < mark) {

    startOffset = dot;

    endOffset = mark;

    } else {

    startOffset = mark;

    endOffset = dot;

    cursorFront = false;

    }

    // Used within while loop below

    int start = startOffset;

    int line = 0;

    try {

    line = textArea.getLineOfOffset( startOffset );

    start = textArea.getLineStartOffset( line );

    }

    catch ( BadLocationException ble ) {

    ble.printStackTrace();

    }

    // Check first loop as undentAction latter on. Watch out for soft&hard tab

    while ( true ) {

    try {

    textArea.setCaretPosition(start);

  • 7/30/2019 Final java editor

    68/84

    68

    textArea.replaceSelection("\t");

    endOffset++;

    line = textArea.getLineOfOffset( start );

    start = textArea.getLineEndOffset(line);

    if ( endOffset < start )

    break;

    }

    catch ( BadLocationException ble ) { ble.printStackTrace(); }

    } // End while

    startOffset++;

    if ( cursorFront ) {

    textArea.setCaretPosition( endOffset );

    textArea.moveCaretPosition( startOffset );

    }

    else {

    textArea.setCaretPosition( startOffset );

    textArea.moveCaretPosition( endOffset );

    }

    textArea.requestFocus();

    }

    /**

    Decreases the indent of the selected line(s).

  • 7/30/2019 Final java editor

    69/84

    69

    @throws BadLocationException

    */

    private void decreaseIndent(){

    JTextArea textArea = jta[desktopTabbedPane.getSelectedIndex()];

    Caret caret = textArea.getCaret();

    int dot = caret.getDot();

    int mark = caret.getMark();

    boolean cursorFront = true;

    // Used for setting cursor

    int startOffset = 0,

    endOffset = 0;

    if (dot == mark) { // no selection

    startOffset = dot;

    endOffset = dot;

    } else if (dot < mark) {

    startOffset = dot;

    endOffset = mark;

    }

    else {

    startOffset = mark;

    endOffset = dot;

    cursorFront = false;

  • 7/30/2019 Final java editor

    70/84

    70

    }

    int line = 0;

    // Used for working within while loop

    int start = 0;

    int end = 0;

    try {

    line = textArea.getLineOfOffset( startOffset );

    start = textArea.getLineStartOffset(line);

    }

    catch ( BadLocationException ble ) {

    ble.printStackTrace();

    }

    boolean decrementStart = true;

    if ( startOffset == start )

    decrementStart = false;

    int tabSize = textArea.getTabSize();

    boolean firstLoop = true;

    // First loop checking takes care of soft/hard tab

    while ( true ) {

    textArea.setCaretPosition(start);

    try {

    end = textArea.getLineEndOffset(line);

  • 7/30/2019 Final java editor

    71/84

    71

    String s = textArea.getText(start, end-start-1 ); // -1 is for

    '/n'

    int c = undent( textArea, s, start, tabSize );

    if ( firstLoop ) { // If first iteration

    firstLoop = false;

    if ( decrementStart ) {

    startOffset = startOffset - c;

    }

    else

    break; // If cursor at start of line with no

    selection

    }

    start = end-c;

    endOffset = endOffset - c;

    if ( endOffset < start )

    break;

    line = textArea.getLineOfOffset( start );

    }

    catch ( BadLocationException ble ) {

    ble.printStackTrace();

    return;

  • 7/30/2019 Final java editor

    72/84

    72

    }

    } // End while

    if ( cursorFront ) {

    textArea.setCaretPosition( endOffset );

    textArea.moveCaretPosition( startOffset );

    }

    else {

    textArea.setCaretPosition( startOffset );

    textArea.moveCaretPosition( endOffset );

    }

    textArea.requestFocus();

    }

    /**

    Used by decreaseIndent(). .

    */

    public int undent( JTextArea textArea, String s, int start, int tabSize ) {

    Character tabChar = new Character('\t');

    int counter = 0;

    boolean tab = false;

    try {

    // s is never null

    for ( int j = 0; j < s.length(); j++ ) {

  • 7/30/2019 Final java editor

    73/84

    73

    char c = s.charAt(j);

    if ( tabChar.equals( new Character(c) ) ) {

    tab = true;

    break;

    }

    else if ( Character.isWhitespace( c ) ) {

    counter++;

    }

    else {

    break;

    }

    if ( counter == tabSize )

    break;

    }// End for

    if ( tab ) {

    textArea.replaceRange( "", start+counter, start+counter+1 );

    counter = 1;

    }

    else {

    if ( counter != 0 ) {

    textArea.replaceRange( "", start, start+counter );

  • 7/30/2019 Final java editor

    74/84

    74

    }

    }

    }

    catch ( Exception ble ) {

    ble.printStackTrace();

    }

    return counter;

    } // End undent

    /**

    Closes the selected frame. .

    */

    private void closeFrame(){

    int selectedIndex=desktopTabbedPane.getSelectedIndex();

    if (isChanged[selectedIndex]){

    int n = JOptionPane.showConfirmDialog(null,"Do you want to save

    changes to "+

    jif[selectedIndex].getTitle()+"?"

    ,"JEditor

    1.0",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);

    if(n == JOptionPane.YES_OPTION){

    if(savedFileName[selectedIndex]== null)

    saveAs() ;

  • 7/30/2019 Final java editor

    75/84

    75

    else

    save();

    }

    }

    desktopTabbedPane.removeTabAt(selectedIndex); tabIndex--;

    if (desktopTabbedPane.getTabCount()==0){

    for (int i=0; i=0){

    if (isChanged[last_tab_index]){

    int n = JOptionPane.showConfirmDialog(null,"Do you want to

    save changes to "+

    jif[last_tab_index].getTitle()+"?"

  • 7/30/2019 Final java editor

    76/84

    76

    ,"JEditor

    1.0",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);

    if(n == JOptionPane.YES_OPTION){

    if(savedFileName[last_tab_index]== null)

    saveAs() ;

    else

    save();

    }

    }

    desktopTabbedPane.removeTabAt(last_tab_index); last_tab_index-

    -;

    }

    }

    /**

    Loads the contents of a file into the text component.

    @throws IOException

    */

    private void openFile() {

    // Use a filedialog to get the input file

    FileDialog fd = new FileDialog(this, "Load File", FileDialog.LOAD );

    fd.show();

    String file = fd.getFile();

    if ( file == null ) // Cancel

  • 7/30/2019 Final java editor

    77/84

    77

    return;

    // Use a file input stream to read in the data

    try {

    String fullPath=fd.getDirectory()+fd.getFile();

    FileInputStream fis = new FileInputStream (fullPath);

    // Data read in bytes

    byte [] data = new byte [ fis.available() ];

    fis.read(data);

    savedFileName[tabIndex]=fullPath;

    newFile(true,file);

    int index=desktopTabbedPane.getSelectedIndex();

    jta[index].setText(new String(data));

    jta[index].setCaretPosition(0);

    jta[index].requestFocus();

    }

    catch (IOException e ) {

    System.err.println("Could not load file..." );

    }

    }

    /**

    Saves the changes to the file.

    */

  • 7/30/2019 Final java editor

    78/84

    78

    private void save(){

    int selectedIndex=desktopTabbedPane.getSelectedIndex();

    try{

    if(savedFileName[selectedIndex]==null)

    saveAs();

    else{

    FileOutputStream fos=new

    FileOutputStream(savedFileName[selectedIndex]);

    fos.write(jta[selectedIndex].getText().getBytes());

    fos.close();

    desktopTabbedPane.setTitleAt(selectedIndex,jif[selectedIndex].getTitle());

    }

    }

    catch(Exception e)

    {

    System.err.println("Save Failed");

    }

    }

    /**

    Saves the contents of the text component to a file.

    @throws IOException

    */

  • 7/30/2019 Final java editor

    79/84

    79

    private void saveAs(){

    int index=desktopTabbedPane.getSelectedIndex();

    FileDialog fd = new FileDialog(this,"Save As",FileDialog.SAVE);

    fd.setFile(jif[desktopTabbedPane.getSelectedIndex()].getTitle());

    fd.show();

    if(fd.getFile() == null) //when choose cancel

    return;

    try{

    String fullPath=fd.getDirectory()+fd.getFile();

    FileOutputStream fos=new FileOutputStream(fullPath);

    fos.write(jta[index].getText().getBytes());

    fos.close();

    // change title to new file name.

    desktopTabbedPane.setTitleAt(index,fd.getFile());

    jif[desktopTabbedPane.getSelectedIndex()].setTitle(fd.getFile());

    savedFileName[tabIndex-1]=fullPath;

    }

    catch(Exception e)

    {

    System.err.println("Save Failed");

    }

    }

  • 7/30/2019 Final java editor

    80/84

    80

    /**

    Displays a window to enter the number of the line to which you want to go.

    */

    private void goTo(){

    if(desktopTabbedPane.getSelectedIndex()

  • 7/30/2019 Final java editor

    81/84

    81

    int go = Integer.parseInt(line);

    textarea.select(textarea.getLineStartOffset(go - 1),textarea.getLineEndOffset(go -1) - 1);

    textarea.requestFocus();

    }

    catch(Exception e){

    errOutput.setText(line + " is not a valid line

    number");

    }

    }

    jfGoto.dispose();

    }

    });

    }

    /**

    to check if the file in the selected frame is saved or not. if it's saved it invokes

    compile() method of JavaCommands class. if the file is not saved it displays the Save As

    dialaog.

    @see JavaCommands

    */

    private void compile(){

  • 7/30/2019 Final java editor

    82/84

    82

    if(savedFileName[desktopTabbedPane.getSelectedIndex()] == null)

    {

    int n = JOptionPane.showConfirmDialog(null,

    "you should save this file before compiling ? ",

    "JEditor 1.0",

    JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);

    if(n == JOptionPane.YES_OPTION)

    saveAs();

    else

    return;

    }

    else

    {

    try

    {

    save();

    JavaCommands c = new JavaCommands();

    c.compile(savedFileName[desktopTabbedPane.getSelectedIndex()]);

    }

    catch(Exception e)

    {System.err.println(e);}

  • 7/30/2019 Final java editor

    83/84

    83

    }

    }

    /**

    to check if the file in the selected frame is saved or not. if it's saved it invokes

    runClass() method of JavaCommands class. if the file is not saved it displays the Save As

    dialaog.

    @see JavaCommands

    */

    private void execute(){

    int index=desktopTabbedPane.getSelectedIndex();

    if(savedFileName[index] == null)

    {

    int n = JOptionPane.showConfirmDialog(null,

    "you should save this file before compiling ? ",

    "JEditor 1.0",

    JOptionPane.YES_NO_OPTION,JOptionPane.INFORMATION_MESSAGE);

    if(n == JOptionPane.YES_OPTION)

    saveAs();

    else

    return;

    }

    else

  • 7/30/2019 Final java editor

    84/84

    {

    try

    {

    JavaCommands c = new JavaCommands();

    c.runClass(savedFileName[index]);

    }

    catch(Exception e)

    {System.err.println(e);}

    }

    }

    /**

    The main method creates JEditor object.

    @param String[] args: Command line arguments as an array of Strings.

    */

    public static void main(String[]args){

    JEditor mainFrame= new JEditor();

    }

    }