Java TidBits

Misc Java Tidbits 

(commonly used/helpful tips)

Also see My WebApp Blog Post for Java WebApps (Servlets/JSP's)

Prompt for user input (String) on commandline


import java.util.Scanner;
public class MainClass {
public static void main(String[] args){
  System.out.println("*************************************************************");
  System.out.println("  This is a cool app");
  System.out.println("  JavaDocs are found at http://localhost:8080/Docs_for_MyApp    ");
  System.out.println("*************************************************************");
java.util.Scanner reader = new Scanner(System.in);  
System.out.println("Press enter to continue");
reader.nextLine(); // Reading/Scan from System.in
reader.close();

Convert StackTrace to String

/**
* Convert an exceptions StackTrace to a string
* @param e Exception to pull the stacktrace from
* @return
*/
public static String getStringFromStackTrace(Exception e){
StringWriter sw=new StringWriter();
e.printStackTrace(new PrintWriter(sw));
return sw.toString(); 
}

Trick to piping java command line output

Java writes version info to standard error (channel 2)
 rather than standard output
  so to pipe java cmd output to a txt file::
    java.exe -version   2> jVer.txt

JTextPane (swing)

JTextPane mainOutputArea=new JTextPane(); mainOutputArea.setBounds(100,100,20,35); 
mainOutputArea.setName(MAIN_OUTPUT); mainOutputArea.setEditable(false); mainOutputArea.setBackground(Color.GREEN);
mainOutputArea.setFont(Font10); mainOutputArea.setContentType("text/html");

logIt("<span style='font-size:48px;'>Ready for action!</span>"+System.lineSeparator());
    public static void logIt(String msg){
    try{HTMLDocument doc = (HTMLDocument)mainOutputArea.getDocument();
    HTMLEditorKit editorKit = (HTMLEditorKit)mainOutputArea.getEditorKit();
    editorKit.insertHTML(doc, doc.getLength(), msg, 0, 0, null);
      } catch(Exception exc) { System.out.println(exc);
         exc.printStackTrace();
      }
    System.out.println(msg);
    DefaultCaret caret=(DefaultCaret)mainOutputArea.getCaret();
    mainOutputArea.setCaretPosition(mainOutputArea.getDocument().getLength()); //goto scroll bottom
    }

Java 8 Lambda's

abstract class cannot be instantiated, but can be subclassed
 declared abstract may or may not include abstract methods. 

abstract method is a method that is declared w/o an implementation 
 (w/o curly braces, and followed by a semicolon):

any class w/abstract method(s) must be declared abstract!

public abstract class GraphicObject {
   // declare fields & nonabstract methods
   abstract void draw();
}

abstract class subclasses usually provides implementations 
 for ALL of parent abstract methods (else it must also be declared abstract)

lambdas work on interfaces w/ONLY 1 abstract method
  such as: actionlistener actionPerformed()
  or like thread which only has RUN()

new thread(() -> dostuff()).start();

the long way
 thread class
   new thread(new runnable{
     run(){
      dostuff();
   }.start();

Java 1.7 Switch Case Stmt allows String!


switch(infoParm){
   case "Pscs": printIframeSourceHtml(pw,DashHelper.getPscsEtlInfo()); break; 
   case "Etl": printIframeSourceHtml(pw,DashHelper.getEtlInfo()); break; 
   case "Ari": printIframeSourceHtml(pw,DashHelper.getAriesFilesInDir()); break; 
   default: break;
}

For/While loop notes:

The continue statement skips the current iteration of a for, while , or do-while loop
 or continue statement skips the rest of the loop.

Simple for loop with colon syntax

FTPFile[] files=getFileListing("ftp.myserver.com"...);
for (FTPFile file : files) {
    //do something with file
}


JavaDoc Method Comments:

 /**
  * <span style='font-size:200%;color:red;'> Some Red Text:</span>
  * <p>Don't use br for line breaks and don't self-enclose tags
  *  <ul>
  *  <li>A list item</li>
  *  <li>Another list item</li>
  *  </ul>

@see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

  *   @see #srcMetaTableToMapButton
  *   @see #metaTable label
  *   @see #mappingLabel
  *   @see #getPscsEtlInfo()
  *   @see MainClass#logIt(String)

{@link reports.uniform.InfoHelper#getPscsTopLeftPortion(InfoBean, javax.sql.DataSource, String, String, HttpSession, boolean)}


  * @param path_n_filename
  * @return String
  * @author mdockery
  */



put code samples inside your java docs as follows:

  /**
    <div style='font-size:200%;color:red;'> Sample usage: </div>
    in doGet <pre>{@code
    String randomTokenString=getRandomString(req);
    req.getSession().setAttribute(CaptchaServlet.RANDOM_CAPTCHA_KEYNAME, randomTokenString);
    response.setContentType("image/jpeg");
    OutputStream responseOutputStream = response.getOutputStream();    
    ImageIO.write(getCaptchaImage(randomTokenString), "jpeg", responseOutputStream);    
    responseOutputStream.close();
}</pre>
*/





Referencing a member of the current class@see  #field
@see  #method(Type, Type,...)
@see  #method(Type argname, Type argname,...)
@see  #constructor(Type, Type,...)
@see  #constructor(Type argname, Type argname,...)

Referencing another class in the current or imported packages
@see  Class#field
@see  Class#method(Type, Type,...)
@see  Class#method(Type argname, Type argname,...)
@see  Class#constructor(Type, Type,...)
@see  Class#constructor(Type argname, Type argname,...)
@see  Class.NestedClass
@see  Class

Referencing an element in another package (fully qualified)
@see  package.Class#field
@see  package.Class#method(Type, Type,...)
@see  package.Class#method(Type argname, Type argname,...)
@see  package.Class#constructor(Type, Type,...)
@see  package.Class#constructor(Type argname, Type argname,...)
@see  package.Class.NestedClass
@see  package.Class
@see  package

Note: Package level javaDoc descriptions can be put into package-info.java (in the root of the package).  The java file need ONLY contain the package declaration and the comments

/**
 * <span style='font-size:200%;color:Green;'> Uniform Report (Servlet, JSP, infoHelper) Package </span>
 * @author mdockery
 */
package reports.uniform;
When you create a NEW package in eclipse, there is a checkbox to auto-create this file.  You can also do it later via file explorer, then you can edit it in eclipse.

Eclipse Notes

Collapse source code blocks  Ctrl+Shift+NUM_KEYPAD_DIVIDE

Expand source code blocks Ctrl+Shift+NUM_KEYPAD *

Show line numbers


Tasks/Todo:

Show your TODO tasks!  (to track what is left to be done inside an app)

Compiler compliance level


JavaDoc stuff:


Source code formatting import/export:



External Jar Updates/Refreshes

If you change/update an external jar file, then you may need to right-click "refresh" your project(s) to force them to use the new(er) version of the external jar

Eclipse - ant build error during javadoc generation

H:\workspace\IP\src\ip\Main.java:7: error: package com.maxmind.geoip2.model does not exist
  [javadoc] import com.maxmind.geoip2.model.City;
  [javadoc]                                ^

Simply make sure the java build path used for your eclipse project (properties)
 matches the classpath tab on the external tool gui box (for ant)

In other words, ensure both reference the same set of external jar files

Nice/Useful Tasks/Build.xml scripts:

 If ant cannot build because it cant find the javadoc command, simply add the java\bin to your system path env var.

 includes ant features such as:
  • leverage project name (to avoid duplication)
  • timestamping with military 24hr HH
  • backup source code
  • echo to display info
  • copy fileset with overwrite/replace option
  • javadoc

Simple Build.xml (easily reused/copied between projects ...just change the top lines)

build xml for war file (and its main class which can be run from commandline)
Added auto copy of the MainClass to the root of the war, so it can be run like a java -jar


<project default="Task03_Backup" basedir="." name="Search" >
<property name="MAIN-CLASS" value="MainClass" />    
<property name="TOMCAT" value="C:/Program Files/tomcat9/" />
<description>${ant.project.name}</description>
<tstamp> <format property="noww" pattern="yyyyMMdd_HHmm" locale="en,GB"/> </tstamp>

<target name="Task01_WarJar"  description="gen/send the war" >
       <record name="build_log.txt" append="true" action="start"/>
       <echo message="Building/Jaring War file of entire eclipse project"/>
       <record name="build_log.txt" action="stop"/> 
  <!-- Run/Execute the MAIN-CLASS like this:  C:\Program Files\Tomcat9\webapps>java -jar Search.war -->
   <copy   toDir="${basedir}" overwrite="true" >
    <fileset dir="${basedir}/WEB-INF/classes" includes="*.class"/>
    </copy> 
       <jar jarfile="${TOMCAT}webapps/${ant.project.name}.war" basedir=".">
     <manifest> <!-- a nice to have if you want to click/run the jar file directly -->
             <attribute name="Main-Class" value="${MAIN-CLASS}"/>
         <attribute name="Built-By" value="${manifest.built.by}"/> 
    </manifest>
   </jar>
</target>

<target name="Task02_Docs" description="generate documentation" depends="Task01_WarJar">
<echo message="Generating javadocs"/>
<javadoc sourcepath="src" destdir="${TOMCAT}webapps/ROOT/Docs_for_${ant.project.name}"
windowtitle="${ant.project.name} API as of ${noww}">
     <header>${ant.project.name} API as of ${noww}</header>
     <bottom>${ant.project.name} API as of ${noww}</bottom>
   </javadoc>
</target>

<target name="Task03_Backup"  description="backup source" depends="Task02_Docs">
<echo message="Backing up source"/>
<copy toDir="${TOMCAT}/Backups/${ant.project.name}_as_of_${noww}"><fileset dir="."/></copy> 
</target>
</project>




import java.util.Scanner;
/**
   Copy this compiled .class file to the main/root folder in your WAR file, so it can be run via command line.
   Notice this is NOT in a package, since the build.xml copies it to the root of the war file

  For example:
  
C:\Program Files\tomcat9\webapps>java -jar maps.war
 *************************************************************
  Map app to leverage Oracle Map Viewer
  JavaDocs are found at http://localhost:8080/Docs_for_MyApp
 *************************************************************
 Press enter to continue
*/
public class MainClass {
 public static void main(String[] args){
  System.out.println("*************************************************************");
  System.out.println("  Map app to leverage Oracle Map Viewer ");
  System.out.println("  JavaDocs are found at http://localhost:8080/Docs_for_MyApp    ");
  System.out.println("*************************************************************");
  java.util.Scanner reader = new Scanner(System.in);  // Reading from System.in
  System.out.println("Press enter to continue");
  reader.nextLine();  
  reader.close();
 }
}

Simple JavaDoc and Jar File tasks (includes a simple copy file function)

<project name="Utils" default="Task_GenJar" basedir=".">
    <description>${ant.project.name}</description>
    <property name="DEST_PATH" value="C:/Program Files/tomcat8/lib/" />
    <property name="COPY_PATH1" value="C:/app/jars" />
    <property name="COPY_PATH2" value="Y:/Div.systems Technology/DW_Projects/DOC_Dashboard" />
    <property name="MAIN-CLASS" value="utils.MainUtilsClass" />
    <tstamp>   <format property="noww" pattern="yyyy-MM-dd_HHmm" locale="en,GB"/> </tstamp>

   <target name="Task_GenJar"  description="Gen the JAR file" depends="Task_Docs">
      <echo message="Generating ${DEST_PATH}${ant.project.name}.jar with Main-class ${MAIN-CLASS}"/>
         <echo message="java -jar ${DEST_PATH}${ant.project.name}.jar"/>
      <jar jarfile="${DEST_PATH}${ant.project.name}.jar" basedir="./bin">
        <manifest>
                <attribute name="Main-Class" value="${MAIN-CLASS}"/>
             <attribute name="Built-By" value="${manifest.built.by}"/>
       </manifest>
      </jar>
      <echo message="Copying jar to ${COPY_PATH1}"/>
           <copy file="${DEST_PATH}${ant.project.name}.jar" todir="${COPY_PATH1}"/>
         <echo message="Copying jar to ${COPY_PATH2}"/>
              <copy file="${DEST_PATH}${ant.project.name}.jar" todir="${COPY_PATH2}"/>
     </target>

    <target name="Task_Docs" description="generate documentation">
        <echo message="Generating javadocs to ${COPY_PATH1}/${ant.project.name}_docs"/>
        <javadoc sourcepath="src" destdir="${COPY_PATH1}/${ant.project.name}_docs"
            windowtitle="${ant.project.name} API as of ${noww}">
                 <bottom>${ant.project.name} API as of ${noww}</bottom>
          </javadoc>
    </target>
</project>

Not as simple


<project name="Reports" default="Task04_WarIt" basedir=".">
    <description>${ant.project.name}</description>
    <property name="DEST_PATH" value="Y:/Div.systems Technology/DW_Projects/${ant.project.name}/" />
    <property name="BKUP_PATH" value="C:/product/Backups/" />
    <property name="WAR__FILE" value="C:/Program Files/tomcat8/webapps/${ant.project.name}.war" />
    <property name="MAIN-CLASS" value="reports.MainClass" />
    <tstamp>   <format property="noww" pattern="yyyy-MM-dd_HHmm" locale="en,GB"/> </tstamp>

    <target name="Task01_Doc" description="generate documentation">
        <echo message="Generating javadocs to ${BKUP_PATH}${ant.project.name}_${noww}_docs"/>
        <javadoc sourcepath="src" destdir="${BKUP_PATH}${ant.project.name}_${noww}_docs"
            windowtitle="${ant.project.name} API as of ${noww}">
                 <bottom>${ant.project.name} API as of ${noww}</bottom>
          </javadoc>   
        <echo message="Generating javadocs to ${DEST_PATH}docs"/>
        <javadoc sourcepath="src" destdir="${DEST_PATH}docs"
            windowtitle="${ant.project.name} API as of ${noww}">
                 <bottom>${ant.project.name} API as of ${noww}</bottom>
          </javadoc>   
    </target>

    <target name="Task02_backup"  description="backup source" depends="Task01_Doc">
        <echo message="${ant.project.name} running at ${noww}"/>
        <echo message="Backing up source to ${BKUP_PATH}${ant.project.name}_${noww}"/>
        <copy   toDir="${BKUP_PATH}${ant.project.name}_${noww}"><fileset dir="."/></copy>
    </target>
   <!-- jar classes to DW_Projects dir -->
   <target name="Task03_GenJar"  description="Gen the JAR file" depends="Task02_backup">
    <echo message="Generating ${DEST_PATH}${ant.project.name}.jar with Main-class ${MAIN-CLASS}"/>
    <jar jarfile="${DEST_PATH}${ant.project.name}.jar" basedir="./WEB-INF/classes">
        <manifest>
                <attribute name="Main-Class" value="${MAIN-CLASS}"/>
             <attribute name="Built-By" value="${manifest.built.by}"/>
       </manifest>
    </jar>
       <echo message="Copying jpg, bat, html, and txt files to ${DEST_PATH}"/>
       <copy   toDir="${DEST_PATH}" overwrite="true" >
           <fileset dir="${basedir}" includes="*.jpg *.html *.bat *.txt"/>
       </copy> 

      <copy   toDir="${DEST_PATH}" file="./ETL.bat"></copy>
   </target>
  <!-- jar entire proj for tomcat -->
   <target name="Task04_WarIt"  description="gen/send the war" depends="Task03_GenJar">
       <record name="build_log.txt" action="start"/>
           <echo message="Building/Jaring War file ${WAR__FILE} at ${noww}"/>
       <record name="build_log.txt" action="stop"/>   
       <jar jarfile="${WAR__FILE}" basedir=".">
        <manifest>
                <attribute name="Main-Class" value="${MAIN-CLASS}"/>
             <attribute name="Built-By" value="${manifest.built.by}"/>
       </manifest>
    </jar>
   </target>

</project>



build.xml:208: Javadoc failed: java.io.IOException: Cannot run program "javadoc.exe": CreateProcess error=2, The system cannot find the file
modify path in Eclipse.
  Open build.xml
   Right-click the task in the Outline View
    Select Run As->Ant Build … click the ellipsis at the end
see Eclipse launch config dialog. Give your new launch configuration a name, like “Build <Project Name>” or something
      and switch to the Environment tab. Here you can
         specify the environment for Ant.
prepend javadoc.exe to it.
  click New… enter Path:
   ${env_var:JAVA_HOME}/bin;${env_var:Path}
This prepends JAVA_HOME/bin to the current system path.

or on the jre tab, simply select a JRE



JavaFX eclipse plugin
help - > install new software...
http://download.eclipse.org/efxclipse/updates-released/2.0.0/site


Notes about storing in session var on apache tomcat:

"implements Serializable" for any object/bean u store in a HttpSession!
 else you may/will get the dreded:

 WARNING [ContainerBackgroundProcessor[StandardEngine[Catalina]]]
org.apache.catalina.session.StandardSession.doWriteObject 
       Cannot serialize session attribute MappingBeans for session C9934DBBF2EDB827C5D33D304ED3E16C

  java.io.NotSerializableException: mappings.MappingBean at 
           java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)


Comments

Popular Posts