Showing posts with label ANT. Show all posts
Showing posts with label ANT. Show all posts

Ant: Compiling Using Specific JDK


The Problem
In some cases, when use ant to compile code, we may have to use a specific JDK version which may be different than the default jdk in the system: for example, the project may use some jdk internal code which is not good, but sometimes we have to deal with the legacy project. 
Solution 1: Using JAVACMD Environment Variable
We can define a system environment variable: JAVACMD which points to full path of the Java executable. Ant will use the JVM defined by JAVACMD instead of JAVA_HOME/bin/java
set "JAVACMD=C:\Program Files\Java\jdk1.6.0_45\bin\java.exe"

export "JAVACMD=/Library/Java/JavaVirtualMachines/jdk1.7.0_75.jdk/Contents/Home/jre/bin/java"

But this will make all ant project uses same JVM defined by JAVACMD.
Solution 2: Using javac executable and fork
We can define specify system environment to specific JDK, for example JAVA6_HOME to point to JDK6.
Then in the ant build.xml, define a property env.java.home which point to JAVA6_HOME, then in javac task, set fork=yes and sepecify executable to ${env.java.home}/bin/javac

  <property environment="env"/>
 <property name="env.java.home" value="${env.JAVA6_HOME}"/>
 <javac destdir="${dest-path}/main" fork="yes" executable="${env.java.home}/bin/javac" source="1.6" target="1.6" debug="on" encoding="utf8" classpathref="common.classpath">
  <src path="./src/main" />
 </javac>
javac executable
Complete path to the javac executable to use in case of fork="yes". Defaults to the compiler of the Java version that is currently running Ant. Ignored if fork="no".

Resources
Running Apache Ant
Ant javac

Create Extensible Ant Script


When we write code, we need consider flexibility, extensibility and maintainability. These rules also applies when we write ant script or batch files.
The Task
In our solr related project, there are multiple cores, and we may add more cores in future. All cores share some common configuration files as the default core collection1. Every core has its own schema.xml and solrconfig.xml. 
So we put the default and shared core configuration files in solr.zip. The file structure looks like below:
solr.zip
solr/collection1/conf/schema.xml
solr/collection1/conf/solrconfig.xml
solr/core-app1/conf/schema.xml
solr/core-app1/conf/solrconfig.xml

As we may add more cores in future, so we want our ant build.xml stays stable: we don't have to update build.xml when we add new cores.

The Solution
In ant build.xml script, we use ant-contrib's foreach task to iterate all core folders: the folder name starts with core-, execute create-core task for each core folder.
<ac:foreach target="create-core" param="coreFolder">
  <path>
    <dirset id="cores" dir="solr/">
      <include name="core-*"/>
    </dirset>
  </path>
</ac:foreach>
The complete Ant Script
<project name="SolrProject" basedir="." default="all" xmlns:ac="antlib:net.sf.antcontrib">
  <dirname  property="project-basedir"  file="${ant.file.SolrProject}"/>
  <taskdef resource="net/sf/antcontrib/antlib.xml" uri="antlib:net.sf.antcontrib">
    <classpath>
      <pathelement location="BuildTools\apache-ant-1.8.4\lib\ant-contrib-1.0b3.jar"/>
    </classpath>
  </taskdef>
  <property name="application-name" value="SolrProject" />
  <property name="main-build-path" value="${project-basedir}/build" />
  <property name="project-build-path" value="${main-build-path}/${application-name}" />
  <property name="solr-zip" value="solr.zip" />
  <target name="clean">
    <delete dir="${main-build-path}" />
    <delete dir="${main-dist-path}" />
  </target>
  <target name="init">
    <mkdir dir="${main-build-path}" />
    <mkdir dir="${project-build-path}" />
  </target>
  <target name="build-package" depends="clean, init">
    <!-- copy configuration files to default core: collection1 -->
    <unzip src="${solr-zip}" dest="${project-build-path}/solr/collection1/conf" >
      <mapper>
        <globmapper from="collection1/conf/*" to="*"/>
      </mapper>
    </unzip>
    <!-- 
    <dirset id="cores" dir="solr/">
      <include name="core-*"/>
    </dirset>
    The pathconvert task can be used to format a dirset with arbitrary separators 
    <pathconvert dirsep="/" pathsep="," property="dirs" refid="cores"/>
    <echo message="${dirs}"/>
    -->
    <ac:foreach target="create-core" param="coreFolder">
      <path>
        <dirset id="cores" dir="solr/">
          <include name="core-*"/>
        </dirset>
      </path>
    </ac:foreach>
  </target>
  <target name="create-core">
    <basename property="basename" file="${coreFolder}"/>
    <echo message="file: ${coreFolder}, basename: ${basename}" />
    <mkdir dir="${project-build-path}/solr/${basename}/conf" />
    <unzip src="${solr-zip}" dest="${project-build-path}/solr/${basename}/conf" >
      <mapper>
        <globmapper from="collection1/conf/*" to="*"/>
      </mapper>
    </unzip>
  </target>
</project>

Ant: Different Ways to Call Another Target


AntCall Task
Call another target within the same buildfile optionally specifying some properties.
<target name="default">
  <antcall target="doSomethingElse">
    <param name="param1" value="value"/>
  </antcall>
</target>
Ant antfile
Call target in another file.
<ant antfile="${liteLucene-project-basedir}/shrink-solr.xml" target="shrink">
<property name="original.home" value="${main-build-path}\${application-name}" />
<property name="shrinked.home" value="${main-build-path}\shrinked-${application-name}" />
<property name="shrinked.tmp" value="${main-build-path}\shrinked-tmp" />
</ant>
Ant Include
Include another build file into the current project.
<include file="${parent-project-build-imp-xml}" as="parent"/>
<target name="package" depends="parent.init, parent.build-package, overwrite-solr-home, create-template, parent.post-clean"/>
How is <import> different from <include>?
The short version: Use import if you intend to override a target, otherwise use include.

Subant Task
Calls a given target for all defined sub-builds.
Example-Solr's build file:

<target name="compile" description="Compile Lucene and Solr">
    <sequential>
      <subant target="compile" inheritall="false" failonerror="true">
        <fileset dir="lucene" includes="build.xml" />
        <fileset dir="solr" includes="build.xml" />
      </subant>
    </sequential>
</target>

Part 3: Use Pack200 to Shrink Solr Application Size


Part 1: Shrink Solr Application Size
Part 2: Use Proguard to Shrink Solr Application Size
Part 3: Use Pack200 to Shrink Solr Application Size
In order to continue to reduce the installation file, I decide to use pack200 to shrink jar size.

Please refer to http://docs.oracle.com/javase/1.5.0/docs/guide/deployment/deployment-guide/pack200.html
https://blogs.oracle.com/manveen/entry/pack200_and_compression_through_ant

This can remove all jars from 6.02mb to 4.44mb: 27% less.

The following is the ANT scrip to pack all jars:
<property name="jarpack-task.jar" value="C:\pathto\Pack200Task.jar" />
<taskdef name="pack200" classname="com.sun.tools.apache.ant.pack200.Pack200Task" classpath="${jarpack-task.jar}" />
<taskdef name="unpack200" classname="com.sun.tools.apache.ant.pack200.Unpack200Task" classpath="${jarpack-task.jar}" />

<target name="pack.all.jars">
 <ac:foreach target="pack.jar" param="file.name">
  <path>
   <fileset dir="${final.jars.output}" includes="*.jar" />
  </path>
 </ac:foreach>
</target>

<target name="pack.jar" description="Applying the pack utility on jars">
 <basename property="file.basename" file="${file.name}" />
 <echo message="pack ${file.name} to ${final.jars.output}/${file.basename}.pack" />
 <pack200 src="${file.name}" destfile="${final.jars.output}/${file.basename}.pack" stripdebug="true" deflatehint="keep" unknownattribute="pass" keepfileorder="true" />
 <delete file="${file.name}" />
</target>

We can use ANT to unpack these jars:
<target name="unpack.all.jars" >
  <ac:foreach target="unpack.jar" param="file.name">
   <path>
    <fileset dir="${runtime.home}" includes="*.pack" />
    <fileset dir="${runtime.home.lib}" includes="*.pack" />
    <fileset dir="${runtime.home}" includes="*.pack" />
    <fileset dir="${runtime.solr.war.lib}" includes="*.pack" />
    <fileset dir="${runtime.solr.core.lib}" includes="*.pack" />
   </path>
  </ac:foreach>
 </target>

 <target name="unpack.jar">
  <propertyregex property="file.unpack.name" input="${file.name}" regexp="(.*).pack" select="\1" />
  <echo message="unpack file ${file.name} to ${file.unpack.name}" />
  <unpack200 src="${file.name}" dest="${file.unpack.name}" />
  <delete file="${file.name}" />
 </target>
Or we can use windows(linux) script to do this:
@ECHO OFF 

echo "Unpack startjetty.jar.pack"
CALL :unpackjar startjetty.jar.pack 

echo "Unpack jars in folder ./lib"
For %%X in (lib\*.pack) do CALL :unpackjar %%X

echo "Unpack jars in folder ./solr.war\WEB-INF\lib"
For %%X in (solr.war\WEB-INF\lib\*.pack) do CALL :unpackjar %%X

echo "Unpack jars in folder ./solr-home\collection1\lib"
For %%X in (solr-home\collection1\lib\*.pack) do CALL :unpackjar %%X

GOTO :EOF

:unpackjar
set packedfile=%1
set unpackedfile=%packedfile:~0,-5%
echo unpack file: %unpackedfile% %packedfile%
unpack200 %packedfile% %unpackedfile%
DEL /Q %packedfile%
GOTO :EOF

@ECHO ON

After all these steps, we use 7zip to zip the application, size is 1,779 kb.
You can view all source code from github:
https://github.com/jefferyyuan/tools/tree/master/ant-scripts/shrink-solr

Part 2: Use Proguard to Shrink Solr Application Size


See: Part 1: Shrink Solr Application Size
4. Use proguard to shrink jar size.
http://proguard.sourceforge.net/
proguard detects and removes unused classes, fields, methods, and attributes. It optimizes bytecode and removes unused instructions.

we need use "Trial and error": run it, if report NoClassDefFoundError, or NoSuchMethodException, modify the configuration file like below:
-keep public class org.apache.solr.servlet.SolrDispatchFilter
-keepclassmembers public class org.apache.solr.servlet.SolrDispatchFilter {
    *;
}
Then redo previous steps.

We can use ANT to do these tasks, the script will copy original jars to some places, use proguard to shrink them, copy shrinked jars to solr application, start the server, and run some tests.
<taskdef resource="proguard/ant/task.properties"
  classpath="<proguard4.8>\lib\proguard.jar" />
<target name="shrinkJetty" depends="postProcess">
 <proguard configuration="conf-jetty.txt"/>
</target>

<target name="shrinkSolr" depends="postProcess">
 <proguard configuration="conf-solr.txt"/>
</target>

5. Use ANT to shrink XML files
First we need remove all unneeded configuration from solrconfig.xml, Solr.xml, web.xml, and xml under /conf are very verbose: remove comments, and white spaces.
<target name="shrinkRuntimeXMLs">
 <path id="orignal.xmls.path">
  <fileset dir="${runtime.solr.core.home}/conf/">
   <include name="*.xml" />
  </fileset>
 </path>
 <property name="orignal.xmls" refid="orignal.xmls.path" />
 <echo message="orignal.xmls: ${orignal.xmls}" />
 <ac:foreach list="${orignal.xmls};${runtime.solr.home}/solr.xml;${runtime.solr.war}/WEB-INF/web.xml" delimiter=";" param="original.xml" target="shrinkXml"/>
</target>
<target name="shrinkXml">
 <basename property="original.xml.basename" file="${original.xml}"/>
 <dirname property="original.xml.dirname" file="${original.xml}"/>
 <echo message="original.xml: ${original.xml}"/>
 <xslt basedir="${original.xml.dirname}" includes="${original.xml.basename}" destdir="${shrinked.xml.output}"
   extension=".xml" style="shrink.xslt"/>
 <move file="${shrinked.xml.output}/${original.xml.basename}" tofile="${original.xml}"/>
</target>

shrink.xslt:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:strip-space elements="*"/>
 <xsl:template match="node()|@*">
  <xsl:copy>
   <xsl:apply-templates select="@*"/>
   <xsl:apply-templates/>
  </xsl:copy>
 </xsl:template>
 <xsl:template match="comment()"/>
</xsl:stylesheet>
6. Use ANT to shrink property files
We can also remove comment, empty lines from property files.
<target name="shrinkPropertyFiles">
 <path id="orignal.properties.path">
  <fileset dir="${runtime.solr.core.home}/conf/">
   <include name="*.txt" />
  </fileset>
 </path>
 <property name="orignal.properties" refid="orignal.properties.path" />
 <ac:foreach list="${orignal.properties}" delimiter=";" param="original.propertyFile" target="shrinkPropertyFile"/>
</target>
<target name="shrinkPropertyFile">
 <replaceregexp file="${original.propertyFile}"
     match="^#.*"
     replace=""
     byline="true"/>
 <copy file="${original.propertyFile}" toFile="${original.propertyFile}-tmp">
  <filterchain>
   <ignoreblank/>
  </filterchain>
 </copy>
 <move file="${original.propertyFile}-tmp" tofile="${original.propertyFile}"/>
</target>
After all these steps, we remove the whole application from 16.6mb to 7.3 mb.
You can view all source code from github:
https://github.com/jefferyyuan/tools/tree/master/ant-scripts/shrink-solr

Part 1: Shrink Solr Application Size




We want to run solr application in client side, client need download and install it, so we need try best to reduce the application's size.

From high level architecture view, we run solr.war in embedded jetty.


1. Reduce Jetty Size Jar:

Refer to: http://wiki.eclipse.org/Jetty/Tutorial/Jetty_HelloWorld
We only need download jetty-all-8.1.8.v20121106.jar from 
http://repo1.maven.org/maven2/org/eclipse/jetty/aggregate/jetty-all/8.1.8.v20121106/,or other jetty version.
Then download http://repo1.maven.org/maven2/javax/servlet/servlet-api/3.0-alpha-1/

Size of jetty-all-8.1.8.v20121106.jar is 1,785 kb + servlet-api-3.0.jar 196 kb = 1,981 kb.


As we will just run servlet in our embedded jetty, some functions are not needed, we can continue to reduce jetty seize.

http://stackoverflow.com/questions/4223597/libraries-for-embedding-jetty

So we download jetty-distribution-8.1.8.v20121106 from eclipse jetty site, just keep the following 9 jars:

jetty-http-8.1.8.v20121106.jar
jetty-io-8.1.8.v20121106.jar
jetty-security-8.1.8.v20121106.jar
jetty-server-8.1.8.v20121106.jar
jetty-servlet-8.1.8.v20121106.jar
jetty-util-8.1.8.v20121106.jar
jetty-webapp-8.1.8.v20121106.jar
jetty-xml-8.1.8.v20121106.jar
servlet-api-3.0.jar

Copy them to a temporary directory, unzip them all to current directory then just zip javax and or directory to a new jar jetty.min-8.1.8.jar: size 1,297 kb, decrease 0.7 mb.


2. Reduce Solr.war size

Download apache-solr-4.1-2012-11-17_23-18-40.zip from https://builds.apache.org/job/Solr-Artifacts-4.x/lastSuccessfulBuild/artifact/solr/package/.

Size of apache-solr-4.1-2012-11-17_23-18-40.war is 14,732 KB.


Our solr application use DataImportHandler to fetch index perodically from remote solr server, and provide http services(/solr/select) to local client.

So we remove all unneeded files from solr.war:
remove folder: csss, img, js, META-INF, tpl, admin.html, favicon.ico, WEB-INF\weblogic.xml.

Next big step is to remove unneeded jars from WEB-INF\lib.

Solr didn't do a good job at modularization: for example if I don't use Spatial Search function, we can't just remove spatial4j-0.3.jar.

So each time, we try to remove one jar, start server and run our tests, see whether the tests run well. If so, remove it, if not, keep it.


For our application, we can remove lucene-analyzers-kuromoji, lucene-grouping, lucene-memory, lucene-spatial, commons-cli, commons-lang, commons-codec, wstx-asl, httpmime, guava. 


As I don't use  solrcloud function, so I think I can remove zookeeper-3.4.5.jar, but after I remove it, it reports exception:

SEVERE: null:java.lang.NoClassDefFoundError: org/apache/zookeeper/KeeperException
        at org.apache.solr.core.CoreContainer$Initializer.initialize(CoreContainer.java:315)
So I remove all other classes from zookeeper.jat except KeeperException related classes.

This step reduces 8.63 mb.


3. Reduce size of Solr.Home

In Solr.Home, we only keep the modules(jars) we need: apache-solr-dataimporthandler.jar, remove all unnecessay files from \\conf.


You can view all source code from github: 
https://github.com/jefferyyuan/tools/tree/master/ant-scripts/shrink-solr

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)