Sunday, June 17, 2012

Maven Important Command

Command 1. The install:install goal
In most cases, install:install goal doesn't need any configuration, it needs the project's POM and the artifact file to be installed during the install phase of the default build lifecycle. mvn install ::
install:install-file goal
The install:install-file goal is used primarily for installing artifacts to the local repository which were not built by Maven. The project's development team may or may not provide a POM for the artifact. Here's a list of some of the available parameters for the install-file goal:

$mvn install:install-file -Dfile=your-artifact-1.0.jar [-DpomFile=your-pom.xml] [-Dsources=src.jar] [-Djavadoc=apidocs.jar] [-DgroupId=org.some.group] [-DartifactId=your-artifact] [-Dversion=1.0] [-Dpackaging=jar] [-Dclassifier=sources] [-DgeneratePom=true] [-DcreateChecksum=true]

  • The groupId, artifactId, version and packaging of the file to install. These can be taken from the specified pomFile, and overridden or specified using the command line. When the pomFile contains a parent section, the parent's groupId can be considered if the groupId is not specified further for the current project or on the command line.
  • The optional classifier parameter can be used to install secondary artifacts for a project, like a javadoc or sources JAR. If a classifier is not given, Maven assumes the file is the main artifact for the project.

Command 2: The deploy:deploy Mojo
In most cases, this mojo is invoked when you call the deploy phase of the default build lifecycle.
To enable this mojo to function, you must include a valid section POM, which at the minimum provides a defining the remote repository location for your artifact. To separate snapshot artifacts from release artifacts, you can also specify a location. Finally, to deploy a project website, you must specify a section here as well. It's also important to note that this section can be inherited, allowing you to specify the deployment location one time for a set of related projects.
If your repository is secured, you may also want to configure your settings.xml file to define corresponding entries which provides authentication information. Server entries are matched to the different parts of the distributionManagement using their elements. For example, your project may have a distributionManagement section similar to the following:
[...]
 
   
      internal.repo
      MyCo Internal Repository
      Host to Company Repository
   

 

[...]
In this case, you can specify a server definition in your settings.xml to provide authentication information for both of these repositories at once. Your server section might look like this:
[...]
   
      internal.repo
      maven
      foobar
   

[...]
Please see the article about Password Encryption for instructions on how to avoid clear text passwords in the settings.xml.
Once you've configured your repository deployment information correctly deploying your project's artifact will only require invocation of the deploy phase of the build:
mvn deploy
The deploy:deploy-file Mojo
The deploy:deploy-file mojo is used primarily for deploying artifacts to which were not built by Maven. The project's development team may or may not provide a POM for the artifact, and in some cases you may want to deploy the artifact to an internal remote repository. The deploy-file mojo provides functionality covering all of these use cases, and offers a wide range of configurability for generating a POM on-the-fly. Additionally, you can specify what layout your repository uses. The full usage statement of the deploy-file mojo can be described as:
mvn deploy:deploy-file -Durl=file://C:\m2-repo -DrepositoryId=some.id -Dfile=your-artifact-1.0.jar [-DpomFile=your-pom.xml] [-DgroupId=org.some.group] [-DartifactId=your-artifact] [-Dversion=1.0] [-Dpackaging=jar] [-Dclassifier=test] [-DgeneratePom=true] [-DgeneratePom.description="My Project Description"] [-DrepositoryLayout=legacy] [-DuniqueVersion=false]
If the following required information is not specified in some way, the goal will fail:
•The artifact file to deploy
•The group, artifact, version and packaging of the file to deploy. These can be taken from the specified pomFile, and overriden or specified using the command line. When the pomFile contains a parent section, the parent's groupId can be considered if the groupId is not specified further for the current project or on the command line.
•The repository information: the url to deploy to and the repositoryId mapping to a server section in the settings.xml file. If you don't specify a repositoryId, Maven will try to extract authentication information using the id 'remote-repository'.


More about maven:
1. Plugins
2. Maven & Source Code








Saturday, June 2, 2012

J B O S S

EAP: Enterprise Application Platform

JBoss Developer Studio:
Configure Maven in JBoss Developer Studio:
Click Window→Preferences, expand JBoss T ools and select JBoss Maven Integration.

Add a repository [jboss-earlyaccess-repository] > 
Profile Id: jboss-ga-repository
Repository: ID: jboss-ga-repository; Name:jboss-ga-repository; URL: http://maven.repository.redhat.com/techpreview/all

Add early access repository[jboss-earlyaccess-repository]>
Profile Id:jboss-earlyaccess-repository
Repository: ID:jboss-earlyaccess-repository ; Name:jboss-earlyaccess-repository ; URL:http://maven.repository.redhat.com/earlyaccess/all/


First Time when we start JBOSS EAP Server, it will give following message:
- - - - - - - - - - - - - - - - - - - - - 
Welcome to EAP 6
The Enterprise Application Platform 6 is running.
However you have not yet added any users to be able to access the admin console.
To add a new user execute the add-user.sh script within the bin folder of your EAP 6 installation and enter the requested information.
By default the realm name used by EAP is "ManagementRealm" this is already selected by default.
After you have added the user follow this link to Try Again.
- - - - - - - - - - - - - - - - - - - - - 

Sunday, May 27, 2012

Packaging Programs in JAR Files

The Java™ Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.

The JAR file format provides many benefits:

  • Security: You can digitally sign the contents of a JAR file. Users who recognize your signature can then optionally grant your software security privileges it wouldn't otherwise have.
  • Decreased download time: If your applet is bundled in a JAR file, the applet's class files and associated resources can be downloaded to a browser in a single HTTP transaction without the need for opening a new connection for each file.
  • Compression: The JAR format allows you to compress your files for efficient storage.
  • Packaging for extensions: The extensions framework provides a means by which you can add functionality to the Java core platform, and the JAR file format defines the packaging for extensions. By using the JAR file format, you can turn your software into extensions as well.
  • Package Sealing: Packages stored in JAR files can be optionally sealed so that the package can enforce version consistency. Sealing a package within a JAR file means that all classes defined in that package must be found in the same JAR file.
  • Package Versioning: A JAR file can hold data about the files it contains, such as vendor and version information.
  • Portability: The mechanism for handling JAR files is a standard part of the Java platform's core API.

Using JAR File

JAR files are packaged with the ZIP file format, so you can use them for tasks such as lossless data compression, archiving, decompression, and archive unpacking. These tasks are among the most common uses of JAR files, and you can realize many JAR file benefits using only these basic features.
Even if you want to take advantage of advanced functionality provided by the JAR file format such as electronic signing, you'll first need to become familiar with the fundamental operations.
To perform basic tasks with JAR files, you use the Java Archive Tool provided as part of the Java Development Kit (JDK). Because the Java Archive tool is invoked by using the jar command, this tutorial refers to it as 'the Jar tool'.
As a synopsis and preview of some of the topics to be covered in this section, the following table summarizes common JAR file operations:
Common JAR file operations
OperationCommand
To create a JAR filejar cf jar-file input-file(s)
To view the contents of a JAR filejar tf jar-file
To extract the contents of a JAR filejar xf jar-file
To extract specific files from a JAR filejar xf jar-file archived-file(s)
To run an application packaged as a JAR file (requires the Main-class manifest header)java -jar app.jar
To invoke an applet packaged as a JAR file
<applet code=AppletClassName.class
archive="JarFileName.jar"
width=width height=height>
</applet>
This section shows you how to perform the most common JAR-file operations, with examples for each of the basic features:

  1. Creating a JAR File: This section shows you how to use the Jar tool to package files and directories into a JAR file.
  2. Viewing the Contents of a JAR File: You can display a JAR file's table of contents to see what it contains without actually unpacking the JAR file.
  3. Extracting the Contents of a JAR File: You can use the Jar tool to unpack a JAR file. When extracting files, the Jar tool makes copies of the desired files and writes them to the current directory, reproducing the directory structure that the files have in the archive.
  4. Updating a JAR File: This section shows you how to update the contents of an existing JAR file by modifying its manifest or by adding files.
  5. Running JAR-Packaged Software: This section shows you how to invoke and run applets and applications that are packaged in JAR files.

Working With Manifest File

JAR files support a wide range of functionality, including electronic signing, version control, package sealing, and others. What gives a JAR file this versatility? The answer is the JAR file's manifest. The manifest is a special file that can contain information about the files packaged in a JAR file. By tailoring this "meta" information that the manifest contains, you enable the JAR file to serve a variety of purposes.

This lesson will explain the contents of the manifest file and show you how to work with it, with examples for the basic features:

Signing and Verifying JAR File

You can optionally sign a JAR file with your electronic "signature." Users who verify your signature can grant your JAR-bundled software security privileges that it wouldn't ordinarily have. Conversely, you can verify the signatures of signed JAR files that you want to use.
This lesson shows you how to use the tools provided in the JDK to sign and verify JAR files:

Understanding Signing and Verification: If you're not familiar with the concepts of signing and verification, this section will help to bring you up to speed. It contains definitions of the relevant terms, explanations of some of the benefits provided by signing, and an outline of the signing mechanism used by the Java platform as it relates to JAR files.

Signing JAR Files: In this section, you'll learn how to use the JDK™ tools to digitally sign your JAR files.

Verifying Signed JAR Files:This section shows you how to use the JDK tool set to verify signed JAR files.
Typically, verification of signed JAR files will be the responsibility of your Java™ Runtime Environment. Your browser will verify signed applets that it downloads. Signed applications invoked with the -jar option of the interpreter will be verified by the runtime environment.

However, you can verify signed JAR files yourself by using the Jarsigner tool. You might want to do this, for example, to test a signed JAR file that you've prepared.
The basic command to use for verifying a signed JAR file is:
jarsigner -verify jar-file
This command will verify the JAR file's signature and ensure that the files in the archive haven't changed since it was signed. You'll see the following message if the verification is successful:
jar verified.
If you try to verify an unsigned JAR file, the following message results:
jar is unsigned. (signatures missing or not parsable)
If the verification fails, an appropriate message is displayed. For example, if the contents of a JAR file have changed since the JAR file was signed, a message similar to the following will result if you try to verify the file:
jarsigner: java.lang.SecurityException: invalid SHA1 
signature file digest for test/classes/Manifest.class

Using JAR related API

The Java platform contains several classes for use with JAR files. Some of these APIs are:

  1. The java.util.jar package
  2. The java.net.JarURLConnection class
  3. The java.net.URLClassLoader class
To give you an idea of the possibilities that are opened up by these new APIs, this lesson guides you through the inner workings of a sample application called JarRunner.

An Example - The JarRunner Application
JarRunner enables you to run an application that's bundled in a JAR file by specifying the JAR file's URL on the command line. For example, if an application called TargetApp were bundled in a JAR file at http://www.example.com/TargetApp.jar, you could run the application using this command:
$ java JarRunner http://www.example.com/TargetApp.jar
In order for JarRunner to work, it must be able to perform the following tasks, all of which are accomplished by using the new APIs:
  • Access the remote JAR file and establish a communications link with it.
  • Inspect the JAR file's manifest to see which of the classes in the archive is the main class.
  • Load the classes in the JAR file.
The JarRunner application consists of two classes, JarRunner and JarClassLoader. JarRunner delegates most of the JAR-handling tasks to the JarClassLoader class. JarClassLoader extends the java.net.URLClassLoader class. You can browse the source code for the JarRunner and JarClassLoader classes before proceeding with the lesson:
  • JarRunner.java
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import java.lang.reflect.InvocationTargetException;

/**
 * Runs a jar application from any url. Usage is 'java JarRunner url [args..]'
 * where url is the url of the jar file and args is optional arguments to
 * be passed to the application's main method.
 */
public class JarRunner {
    public static void main(String[] args) {
        if (args.length < 1) {
            usage();
        }
        URL url = null;
        try {
            url = new URL(args[0]);
        } catch (MalformedURLException e) {
            fatal("Invalid URL: " + args[0]);
        }
        // Create the class loader for the application jar file
        JarClassLoader cl = new JarClassLoader(url);
        // Get the application's main class name
        String name = null;
        try {
            name = cl.getMainClassName();
        } catch (IOException e) {
            System.err.println("I/O error while loading JAR file:");
            e.printStackTrace();
            System.exit(1);
        }
        if (name == null) {
            fatal("Specified jar file does not contain a 'Main-Class'" +
                  " manifest attribute");
        }
        // Get arguments for the application
        String[] newArgs = new String[args.length - 1];
        System.arraycopy(args, 1, newArgs, 0, newArgs.length);
        // Invoke application's main class
        try {
            cl.invokeClass(name, newArgs);
        } catch (ClassNotFoundException e) {
            fatal("Class not found: " + name);
        } catch (NoSuchMethodException e) {
            fatal("Class does not define a 'main' method: " + name);
        } catch (InvocationTargetException e) {
            e.getTargetException().printStackTrace();
            System.exit(1);
        }
    }

    private static void fatal(String s) {
        System.err.println(s);
        System.exit(1);
    }

    private static void usage() {
        fatal("Usage: java JarRunner url [args..]");
    }
}
  • JarClassLoader.java
import java.net.URL;
import java.net.URLClassLoader;
import java.net.JarURLConnection;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.InvocationTargetException;
import java.util.jar.Attributes;
import java.io.IOException;

/**
 * A class loader for loading jar files, both local and remote.
 */
class JarClassLoader extends URLClassLoader {
    private URL url;

    /**
     * Creates a new JarClassLoader for the specified url.
     * @param url the url of the jar file
     */
    public JarClassLoader(URL url) {
        super(new URL[] { url });
        this.url = url;
    }

    /**
     * Returns the name of the jar file main class, or null if
     * no "Main-Class" manifest attributes was defined.
     */
    public String getMainClassName() throws IOException {
        URL u = new URL("jar", "", url + "!/");
        JarURLConnection uc = (JarURLConnection)u.openConnection();
        Attributes attr = uc.getMainAttributes();
        return attr != null ? attr.getValue(Attributes.Name.MAIN_CLASS) : null;
    }

    /**
     * Invokes the application in this jar file given the name of the main class and an array of arguments. The class must define a
     * static method "main" which takes an array of String arguments and is of return type "void".
     *
     * @param name the name of the main class
     * @param args the arguments for the application
     * @exception ClassNotFoundException if the specified class could not be found
     * @exception NoSuchMethodException if the specified class does not contain a "main" method
     * @exception InvocationTargetException if the application raised an exception
     */
    public void invokeClass(String name, String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
        Class c = loadClass(name);
        Method m = c.getMethod("main", new Class[] { args.getClass() });
        m.setAccessible(true);
        int mods = m.getModifiers();
        if (m.getReturnType() != void.class || !Modifier.isStatic(mods) ||
            !Modifier.isPublic(mods)) {
            throw new NoSuchMethodException("main");
        }
        try {
            m.invoke(null, new Object[] { args });
        } catch (IllegalAccessException e) {
            // This should not happen, as we have disabled access checks
        }
    }
}
This lesson has two parts:
The JarClassLoader Class: This section shows you how JarClassLoader uses some of the new APIs to perform tasks required for the JarRunner application to work.

The JarRunner Class: This section summarizes the JarRunner class that comprises the JarRunner application.


Question & Answer


Q: How do you invoke an applet that is packaged as a JAR file?
Ans: To invoke an applet packaged as a JAR file, open a page containing the applet:
<applet code="AppletClassName.class" archive="JarFileName.jar" width=320 height=240></applet>

Q: What is the purpose of the -e option in a jar command?
Ans: This option is available since Java SE 6. It sets the entry point as the application entry point for stand-alone applications bundled into executable jar file. The use of this option creates or overrides the Main-Class attribute value in the manifest file. This option can be used during creation of jar file or while updating the jar file. This option specifies the application entry point without editing or creating the manifest file. For example, this command creates Main.jar where the Main-Class attribute value in the manifest is set to Main: 
$ jar cfe Main.jar Main Main.class

Q: What is the significance of the manifest in a JAR file?
Ans: A JAR file's manifest provides meta-information about the other contents of the JAR file. The manifest itself resides in META-INF/MANIFEST.mf. The meta-information can include:
  • Dependencies on other jar files
  • The name of a class to run when "java -jar file.jar" is invoked
  • versioning information
  • Security information

Q: How do you modify a JAR's manifest file?
Ans: Typically, modifying the default manifest involves adding special-purpose headers to the manifest that allow the JAR file to perform a particular desired function.
To modify the manifest, you must first prepare a text file with a complete and valid manifest file. You then use the JAR tool's m option to add the information in your file to the manifest.
The manifest file your prepare must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Monday, April 30, 2012

Installing MySQL on Linux (centOS)


Following are steps to install MySQL on CenOS 5/6.

  1. Check the OS Versions and download respective installables from Oracle / Mysql Sites.
    1. cat /proc/version
    2. cat /etc/issue
    3. cat /etc/redhat-release
    4. lsb_release -a
  2. For my CentOS system download following to your Linux System:
    Output of $ lsb_release -a
    1. MySQL Cluster 7.3.4 RPM for Oracle Linux / RHEL 6 x86 (64bit) V43767-01 330M
    2. MySQL Cluster Manager 1.3.0+Cluster RPM for Oracle Linux/RHEL 5+6 x86 (64bit) V42979-01 140M
    3. or download: MySQL-Cluster-gpl-7.3.5-1.rhel5.x86_64.rpm-bundle.tar
  3. Important RPM Command for Installing RPM Package.
    1. Install: $ rpm -ivh mcm-1.3.0-cluster-7.3.3-linux-rhel5-x86-64bit.rpm
      1. -i : install a package
      2. -v : verbose for a nicer display
      3. -h : print hash mark as the package archive is unpacked.
    2. Check Signature: $ rpm --checksig mcm-1.3.0-cluster-7.3.3-linux-rhel5-x86-64bit.rpm
    3. Check dependency of rpm package before installing:[rpm -qPR *.rpm]
      1. -q: query a package
      2. -p: list capabilities this package provides
      3. -R: list capabilities on which this package depends
    4. Install a RPM package without dependencies: [rpm -ivh --nodeps *.rpm]
    5. Check an install rpm package: rpm -q mysql
    6. List (query list) all files of an installed rpm package: [ $ rpm -ql mysql]
    7. List recently installed rpm packages: [$ rpm -qa --last]
    8. List all installed rpm packages: [$ rpm -qa]
    9. Upgrade a rpm package: [rpm -Uvh *.rpm]
    10. Remove a package: [$ rpm -evv mysql]
    11. Remove a rpm package without dependencies: [$ rpm -ev --nodeps mysql]
    12. Query a file that belongs which rpm package: [$ rpm -qf /usr/bin/htpasswd]
    13. Query an info for installed rpm package: [ $ rpm -qi mysql]
    14. Get info of rpm package before installing: [ $ rpm -qip *mysql*.rpm] # query info package
    15. Query documentation of installed RPM Package: [ $ rpm -qdf /usr/bin/vmstat] (query document file)
    16. Verify a RPM package: (verify package) $ rpm -vP *mysql*.rpm
    17. Verify all RPM package: rpm -Va
    18. Import RPM GPG Key: $ rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CENTOS-6
    19. List all imported RPM GPG Key: ( $ rpm -qa gpg-pubkey*)
    20. Rebuild corrupted RPM database: Sometimes rpm database gets corrupted and stops all the functionality of RPM and other applications on the system, so at that time we need to rebuild the RPM Database and restore it with the help of following commands:
      1. cd /var/lib
      2. rm __db*
      3. rpm --rebuilddb
      4. rpmdb_verify Packages
  4. Installation Steps:
    1. Create required users / group on CentOS & unarchive file on all hosts:
      1. $ groupadd mysql
      2. $ useradd –g mysql mysql
      3. Artifacts.
        1. tar –zxvf  /usr/local/ mysql-cluster-gpl-7.3.2-linux-glibc2.5-x86_64.tar.gz or
        2. tar -zvf /usr/local/ MySQL-Cluster-gpl-7.3.5-1.rhel5.x86_64.rpm-bundle.tar [ wget http://cdn.mysql.com/Downloads/MySQL-Cluster-7.3/MySQL-Cluster-gpl-7.3.5-1.rhel5.x86_64.rpm-bundle.tar to download file]
      4. mv /usr/local/ mysql-cluster-gpl-7.3.2-linux-glibc2.5-x86_64 /opt/mysql_cluster
      5. chown mysql.mysql –R /opt/mysql_cluster
    2. We have list of following Servers:
      1. 10.253.92.154 - ndb(192.168.1.196) & mgm (192.168.1.144)
      2. 10.253.92.155 - ndb(192.168.1.197)
      3. 10.252.168.174 - mysql (192.168.1.152)
      4. 10.252.168.173 - mysql (192.168.1.193)
    3. On Server '10.253.92.154' & '10.253.92.155' create a new folder - Data Node.
      1. mkdir  /opt/mysql_cluster/ndbdata
      2. chown mysql.mysql –R /opt/mysql_cluster
    4.  MGM Node: (10.253.92.154) configuration:
      1.  cd /opt/mysql_cluster/ 
      2. vi config.ini
    5. Install and configure mysql on two mysqld node (10.252.168.173, 10.252.168.174)
      1. cd /opt/mysql_cluster/
      2. scripts/mysql_cluster_install --user=mysql --datadir=/opt/mysql_cluster/data --basedir=/opt/mysql_cluster/
      3. mv /opt/mysql_cluster/my.cnf /etc/my.cnf
      4. vi /etc/my.cnf 
      5. Modify the /opt/mysql_cluster/support-files/mysql.server, replace datadir and basedir
        1. datadir=/opt/mysql_cluster/data
        2. basedir=/opt/mysql_cluster/
    6. Start all cluster and mgm node:
      1. Startup data node(10.253.92.154, 10.253.92.155)
      2. [root@Node1]# /opt/mysql_cluster/bin/ndbd --defaults-file=/opt/mysql_cluster/my.cnf --initial
      3. 2013-10-02 13:17:36 [ndbd] INFO     -- Angel connected to '10.253.92.154:1186'
      4. 2013-10-02 13:17:36 [ndbd] INFO     -- Angel allocated nodeid: 11
      5. Startup mysqld node(10.252.168.173, 10.252.168.174)
      6. Startup the mgm node:
        1. /opt/mysql_cluster/bin/ndb_mgmd -f /opt/mysql_cluster/config.ini --configdir=/opt/mysql_cluster
    7. Check status:

Sunday, April 29, 2012

Installing MySQL (noinstall Zip file) on Windows 7 (64)

Users who are installing from the noinstall package can use the instructions in this section to manually install MySQL. The process for installing MySQL from a Zip archive is as follows:
  1. Extract the archive to the desired install directory: Traditionally MySQL server is installed in C:\mysql and MySQL installation Wizard installs MySQL under C:\Program Files\MySQL, if we do not install MySQL at C:\mysql, we must specify the part to the install directory during startup or in an option file.
  2. Create an option file: If we need to specify startup options when we run the server, we can indicate them on command line or place them in an option file.
    1. The installation or data directory locations are different from the default locations (C:\Program Files\MySQL\MySQL Server 5.5 and C:\Program Files\MySQL\MySQL Server 5.5\data)
    2. We need to tune the server settings, such as memory , cache or InnoDB configuration information.
    3. When MySQL Server starts on Windows, it looks for option files in several locations, such as:
      1. Locations:
        1. Windows Directory [C:\> echo %WINDIR%]
        2. C:\
        3. MySQL Installation Directory.
      2. MySQL looks for options first in (my.ini) file then in (my.cnf) file each location, we can use both files but to avoid confusion better to use one file, as follows:
        1. %PROGRAMDATA%\MySQL\MySQL Server 5.5\my.ini,%PROGRAMDATA%\MySQL\MySQL Server 5.5\my.cnf
        2. %WINDIR%\my.ini, %WINDIR%\my.cnf
        3. C:\my.ini, C:\my.cnf
        4. INSTALLDIR\my.ini, INSTALLDIR\my.cnf
        5. defaults-extra-file The file specified with --defaults-extra-file=path, if any
      3. Use a --datadir option to specify the new data directory location each time you start the server.
  3. Choose a MySQL server type:
    1. SHOW [STORAGE] ENGINES: displays status information about the server's storage engines, same information can also be obtained from INFORMATION_SCHEMA_ENGINES tables.
  4. Starting the Server for the First Time:
    1. Clients have two options. They can use TCP/IP, or they can use a named pipe if the server supports named-pipe connections.
    2. MySQL for Windows also supports shared-memory connections if the server is started with the --shared-memory option. Clients can connect through shared memory by using the --protocol=MEMORY option.
    3. START: C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqld" --console
      1. C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin>mysqld.exe --console --explicit_defaults_for_timestamp
      2. If you omit the --console option, the server writes diagnostic output to the error log in the data directory by default. The error log is the file with the .err extension, or may be specified by passing in the --log-error option.
    4. STOP: C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqladmin" -u root shutdown
      1. If the MySQL root user account has a password, you need to invoke mysqladmin with the -p option and supply the password when prompted.
      2. The last option is to start mysqld with the --standalone and --debug options. In this case, mysqld writes a log file C:\mysqld.trace that should contain the reason why mysqld doesn't start.
    5. Use mysqld --verbose --help to display all the options that mysqld supports.
  5. Secure the default user accounts.
  6. Customize the Path for MySQL Tools: To make it easier to invoke MySQL programs, you can add the path name of the MySQL bin directory to your Windows system PATH environment variable:
    1. On the Windows desktop, right-click the My Computer icon, and select Properties.
    2. Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.
    3. Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.
    4. Add Mysql/bin to PATH environment variables.
  7. Starting MySQL as Windows Service: A MySQL server installed as a service can also be controlled from the command line using NET commands, or with the graphical Services utility. Generally, to install MySQL as a Windows service you should be logged in using an account that has administrator rights.
    1. The Services utility (the Windows Service Control Manager) can be found in the Windows Control Panel (under Administrative Tools on Windows 2000, XP, Vista, and Server 2003). To avoid conflicts, it is advisable to close the Services utility while performing server installation or removal operations from the command line.
    2. Before installing MySQL as a Windows service, you should first stop the current server if it is running by using the following command:
      1. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqladmin" -u root shutdown.
      2. Note: If the MySQL root user account has a password, you need to invoke mysqladmin with the -p option and supply the password when prompted.
    3. Install the server as a service using this command:
      1. C:\> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --install
      2. set mysql/bin to windows PATH
        1. On the Windows desktop, right-click the My Computer icon, and select Properties.
        2. Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.
        3. Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.
        4. IMP NOTE: You should not add the MySQL bin directory to your Windows PATH if you are running multiple MySQL servers on the same machine.
      3. The following additional arguments can be used when installing the service:
        1. You can specify a service name immediately following the --install option. The default service name is MySQL.
        2. If a service name is given, it can be followed by a single option. By convention, this should be --defaults-file=file_name to specify the name of an option file from which the server should read options when it starts.
        3. The use of a single option other than --defaults-file is possible but discouraged. --defaults-file is more flexible because it enables you to specify multiple startup options for the server by placing them in the named option file.
        4. You can also specify a --local-service option following the service name. This causes the server to run using the LocalService Windows account that has limited system privileges. This account is available only for Windows XP or newer. If both --defaults-file and --local-service are given following the service name, they can be in any order.
        5. For a MySQL server that is installed as a Windows service, the following rules determine the service name and option files that the server uses:
          1. If the service-installation command specifies no service name or the default service name (MySQL) following the --install option, the server uses the a service name of MySQL and reads options from the [mysqld] group in the standard option files.
          2. If the service-installation command specifies a service name other than MySQL following the --install option, the server uses that service name. It reads options from the [mysqld] group and the group that has the same name as the service in the standard option files. This enables you to use the [mysqld] group for options that should be used by all MySQL services, and an option group with the service name for use by the server installed with that service name.
          3. If the service-installation command specifies a --defaults-file option after the service name, the server reads options the same way as described in the previous item, except that it reads options only from the the named file and ignores the standard option files.
        6. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqld" --install MySQL --defaults-file=C:\my-opts.cnf
      4. Once a MySQL server has been installed as a service, Windows starts the service automatically whenever Windows starts, The service also can be started immediately from the Services utility, or by using:
        1. NET START MySQL command
        2. NET STOP MySQL
        3. You also have the choice of installing the server as a manual service if you do not wish for the service to be started automatically during the boot process. To do this, use the --install-manual option rather than the --install option:
          1. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqld" --install-manual
        4. Removing the service: To remove a server that is installed as a service, first stop it if it is running by executing NET STOP MySQL. Then use the --remove option to remove it:
          1. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqld" --remove
  8. Testing MySQL Installation: You can test whether the MySQL server is working by executing any of the following commands:
    1. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqlshow"
    2. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqlshow" -u root mysql
    3. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysqladmin" version status proc
    4. C:\> "C:\CCC\mysql\mysql-advanced-5.6.16-winx64\bin\mysql" test
  9. Windows Useful Commands:
    1. Service Control: SC COMMAND ( SC [\\server] [command] [service_name] [Options] )
      1. server       : The machine where the service is running.
      2. service_name : The KeyName of the service, this is often but not always the same as the DisplayName shown in Control Panel, Services. You can get the KeyName by running: SC GetKeyName <DisplayName>
      3. commands:
        1. query  [qryOpt]   Show status
        2. queryEx [qryOpt]  Show extended info - pid, flags
        3. GetDisplayName    Show the DisplayName
        4. GetKeyName        Show the ServiceKeyName
        5. EnumDepend        Show Dependencies
        6. qc                Show config - dependencies, full path etc
        7. start          START a service.
        8. stop           STOP a service
        9. pause          PAUSE a service.
        10. continue       CONTINUE a service.
        11. create         Create a service. (add it to the registry)
        12. config         permanently change the service configuration
        13. delete         Delete a service (from the registry)
        14. control        Send a control to a service
        15. interrogate    Send an INTERROGATE control request to a service
        16. Qdescription   Query the description of a service
        17. description    Change the description of a service
        18. Qfailure       Query the actions taken by a service upon failure
        19. failure        Change the actions taken by a service upon failure
        20. sdShow         Display a service's security descriptor using SDDL
        21. SdSet          Sets a service's security descriptor using SDDL
      4. qryOpt:
        1. type= driver|service|all - Query specific types of service
        2. state= active|inactive|all - Query services in a particular state only
        3. bufsize= bytes 
        4. ri= resume_index_number (default=0)
        5. group= groupname - Query services in a particular group
      5. Misc commands that don’t require a service name:
        1. SC  QueryLock  Query the LockStatus for the ServiceManager Database. this will show if a service request is running
        2. SC  Lock       Lock the Service Database
        3. SC  BOOT       Values are {ok | bad} Indicates whether to save the last restart configuration as the `last-known-good` restart configuration
      6. Options:
        1. The CREATE and CONFIG commands allow additional options to be set see the build-in help: 'SC create' and 'SC config'
    2. Windows check who is using a particular port:
      1. C:\> netstat -aon | find /i "listening" | find "3306"
      2. C:\> netstat -abno



Wednesday, April 4, 2012

Adding Classes to the JAR File's Classpath

You may need to reference classes in other JAR files from within a JAR file.
For example, in a typical situation an applet is bundled in a JAR file whose manifest references a different JAR file (or several different JAR files) that serves as utilities for the purposes of that applet.
You specify classes to include in the Class-Path header field in the manifest file of an applet or application. The Class-Path header takes the following form:
Class-Path: jar1-name jar2-name directory-name/jar3-name
By using the Class-Path header in the manifest, you can avoid having to specify a long -classpath flag when invoking Java to run the your application.

Note: The Class-Path header points to classes or JAR files on the local network, not JAR files within the JAR file or classes accessible over internet protocols. To load classes in JAR files within a JAR file into the class path, you must write custom code to load those classes. For example, if MyJar.jar contains another JAR file called MyUtils.jar, you cannot use the Class-Path header in MyJar.jar's manifest to load classes in MyUtils.jar into the class path.

An Example

We want to load classes in MyUtils.jar into the class path for use in MyJar.jar. These two JAR files are in the same directory.
We first create a text file named Manifest.txt with the following contents:
Class-Path: MyUtils.jar

Warning: The text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

We then create a JAR file named MyJar.jar by entering the following command:
jar cfm MyJar.jar Manifest.txt MyPackage/*.class
This creates the JAR file with a manifest with the following contents:
Manifest-Version: 1.0
Class-Path: MyUtils.jar
Created-By: 1.7.0_06 (Oracle Corporation)
The classes in MyUtils.jar are now loaded into the class path when you run MyJar.jar.

Tuesday, March 27, 2012

The JarClassLoader Class

The JarClassLoader Class

The JarClassLoader class extends java.net.URLClassLoader. As its name implies, URLClassLoader is designed to be used for loading classes and resources that are accessed by searching a set of URLs. The URLs can refer either to directories or to JAR files.
In addition to subclassing URLClassLoaderJarClassLoader also makes use of features in two other new JAR-related APIs, the java.util.jar package and thejava.net.JarURLConnection class. In this section, we'll look in detail at the constructor and two methods of JarClassLoader.

The JarClassLoader Constructor

The constructor takes an instance of java.net.URL as an argument. The URL passed to this constructor will be used elsewhere in JarClassLoader to find the JAR file from which classes are to be loaded.
public JarClassLoader(URL url) {
super(new URL[] { url });
this.url = url;
}
The URL object is passed to the constructor of the superclass, URLClassLoader, which takes a URL[] array, rather than a single URL instance, as an argument.

The getMainClassName Method

Once a JarClassLoader object is constructed with the URL of a JAR-bundled application, it's going to need a way to determine which class in the JAR file is the application's entry point. That's the job of the getMainClassName method:
public String getMainClassName() throws IOException {
URL u = new URL("jar", "", url + "!/");
JarURLConnection uc = (JarURLConnection)u.openConnection();
Attributes attr = uc.getMainAttributes();
return attr != null
? attr.getValue(Attributes.Name.MAIN_CLASS)
: null;
}
You may recall from a previous lesson that a JAR-bundled application's entry point is specified by the Main-Class header of the JAR file's manifest. To understand howgetMainClassName accesses the Main-Class header value, let's look at the method in detail, paying special attention to the new JAR-handling features that it uses:

The JarURLConnection class and JAR URLs

The getMainClassName method uses the JAR URL format specified by the java.net.JarURLConnection class. The syntax for the URL of a JAR file is as in this example:
jar:http://www.example.com/jarfile.jar!/
The terminating !/ separator indicates that the URL refers to an entire JAR file. Anything following the separator refers to specific JAR-file contents, as in this example:
jar:http://www.example.com/jarfile.jar!/mypackage/myclass.class
The first line in the getMainClassName method is:
URL u = new URL("jar", "", url + "!/");
This statement constructs a new URL object representing a JAR URL, appending the !/ separator to the URL that was used in creating the JarClassLoader instance.

The java.net.JarURLConnection class

This class represents a communications link between an application and a JAR file. It has methods for accessing the JAR file's manifest. The second line of getMainClassNameis:
JarURLConnection uc = (JarURLConnection)u.openConnection();
In this statement, URL instance created in the first line opens a URLConnection. The URLConnection instance is then cast to JarURLConnection so it can take advantage ofJarURLConnection's JAR-handling features.

Fetching Manifest Attributes: java.util.jar.Attributes

With a JarURLConnection open to a JAR file, you can access the header information in the JAR file's manifest by using the getMainAttributes method ofJarURLConnection. This method returns an instance of java.util.jar.Attributes, a class that maps header names in JAR-file manifests with their associated string values. The third line in getMainClassName creates an Attributes object:
Attributes attr = uc.getMainAttributes();
To get the value of the manifest's Main-Class header, the fourth line of getMainClassName invokes the Attributes.getValue method:
return attr != null
? attr.getValue(Attributes.Name.MAIN_CLASS)
: null;
The method's argument, Attributes.Name.MAIN_CLASS, specifies that it's the value of the Main-Class header that you want. (The Attributes.Name class also provides static fields such as MANIFEST_VERSIONCLASS_PATH, and SEALED for specifying other standard manifest headers.)

The invokeClass Method

We've seen how JarURLClassLoader can identify the main class in a JAR-bundled application. The last method to consider, JarURLClassLoader.invokeClass, enables that main class to be invoked to launch the JAR-bundled application:
public void invokeClass(String name, String[] args)
throws ClassNotFoundException,
NoSuchMethodException,
InvocationTargetException
{
Class c = loadClass(name);
Method m = c.getMethod("main", new Class[] { args.getClass() });
m.setAccessible(true);
int mods = m.getModifiers();
if (m.getReturnType() != void.class || !Modifier.isStatic(mods) ||
!Modifier.isPublic(mods)) {
throw new NoSuchMethodException("main");
}
try {
m.invoke(null, new Object[] { args });
} catch (IllegalAccessException e) {
// This should not happen, as we have disabled access checks
}
}
The invokeClass method takes two arguments: the name of the application's entry-point class and an array of string arguments to pass to the entry-point class's main method. First, the main class is loaded:
Class c = loadClass(name);
The loadClass method is inherited from java.lang.ClassLoader.
Once the main class is loaded, the reflection API of the java.lang.reflect package is used to pass the arguments to the class and launch it. You can refer to the tutorial onThe Reflection API for a review of reflection.