Names = "A, B, C, D, E" arrNames = Names.split(",") for x in range(len(arrNames)): print arrNames[x]
Jython Basics
Below are the code sample which shows how to carry out basic tasks in Jython.The Files should be shared as .py extension if your are using eclipse.To know abount configuring jython in eclipse follow the
Link
Printing a Message in Console
print 1 + 1 print "Hello" + " World " print "Hello Jython " print "Jython ", "Scripting"
Simple Jython Function that Takes Argument and Print Values
def displayName(x): print x displayName("Mugil")
Jython Function which Calculates the Factorial of a Number
def factorial(x): if x<=1 : return 1 return x * factorial(x-1) print factorial(3)
Function which compares Two Strings in If Condition
def compareName(FirstName, LastName): if FirstName == LastName: print "They are Equal" else: print "They are Not Equal" compareName("Jython", "Jython")
Conditional Operators
Function which Perform AND, OR and Not Ops
def BoolOps(pOne, pTwo): if pOne and pTwo: print "They are Equal" else: print "They are Not Equal" BoolOps(1,0)
Jython Supports Three Numeric Values as Below
- Integers
- Long
- Floating Point
Array from Delimited String and Looping through It
Names = "A, B, C, D, E" arrNames = Names.split(",") for x in range(len(arrNames)): print arrNames[x]
Array Function
Names = "A,B,C,D,E,F,G,H,I,J,K,L,M" arrNames = Names.split(",") #B print arrNames[1] #['B'] print arrNames[1:2] #['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'] print arrNames[1:] #['A', 'B', 'C', 'D', 'E', 'F'] print arrNames[:6] #['B', 'C', 'D', 'E'] print arrNames[1:5] #['H', 'I', 'J'] print arrNames[-6:-3] #['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M'] print arrNames[:] #['A', 'C', 'E', 'G', 'I', 'K', 'M'] print arrNames[::2]
Concatenating Two Arrays together
Names1 = "A,B,C" Names2 = "D, E, F" arrNames1 = Names1.split(",") arrNames2 = Names2.split(",") arrNames = arrNames1 + arrNames2 for i in range(len(arrNames)): print arrNames[i]
How to create array of String in Jython
import jarray import java myArray = jarray.array(["mugil", "Vannan"], java.lang.Object) rc.logMessage(str(len(myArray))) for value in myArray: rc.logMessage(value)
For Character
myArray = jarray.array(["m", "V"], "c")
For Integer
import jarray import java myArray = jarray.array([1,2,3,4,5,6], java.lang.Integer) rc.logMessage(str(len(myArray))) for value in myArray: rc.logMessage(str(value))
How to Replicte Column in Excel Sheet Jython Scripting
I am having single column in excel sheet which I want to replicate in Jython scripting and place it in adjacent column.The Content of the Column is as in the Pic below
from jxl import * from jxl.write import * from java.io import File workbook = Workbook.getWorkbook(File("$(TargetFolder)\Book2.xls")) targetWorkbook = Workbook.createWorkbook(File("$(TargetFolder)\Book2.xls"), workbook) sheet = targetWorkbook.getSheet(0) columnIndex = 0 rowCount = sheet.getRows() for i in range(rowCount): row = sheet.getRow(i) content = row[columnIndex].getContents() rc.logMessage("Content -> " + content) wc = sheet.getWritableCell(1,i) newLabel = Label(1,i, content) sheet.addCell(newLabel) targetWorkbook.write() targetWorkbook.close() workbook.close()
Before running Script
After running Script
How to find 32 bit or 64 bit java command prompt
java -version 2>&1 | find "64-Bit" >nul: if errorlevel 1 ( echo 32-Bit ) else ( echo 64-Bit )
Java Code Snippets
How to get Total Columns Returned by Query
ResultSet rs = stmt.executeQuery(strSQL); ResultSetMetaData rsmd = rs.getMetaData(); int columnsNumber = rsmd.getColumnCount();
How to get Column Name from Query
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); String name = rsmd.getColumnName(1);
How to get Column Count from Query and Loop Through That
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); // The column count starts from 1 for (int i = 1; i < columnCount + 1; i++ ) { String name = rsmd.getColumnName(i); // Do stuff with name }
To Find a Column with particular Name
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2"); rs.getString(rs.findColumn("fullname"));
How to get List of Column Names from Query and Store it in a Array
ResultSetMetaData meta = resultset.getMetaData(); Integer columncount = meta.getColumnCount(); int count = 1 ; String[] columnNames = null; while(columncount <=count) columnNames [i] = meta.getColumnName(i); System.out.println (columnNames.size());
Using Singleton Class for DB Connection Java
The Servlet which loads the Singleton class should be loaded during the server startup
ConfigServlet.java
public class ConfigServlet extends HttpServlet { @Override public void init() throws ServletException { super.init(); SingletonDBConnection.getInstance(); } }
web.xml
<servlet> <servlet-name>StartUpServlet</servlet-name> <servlet-class>com.mugil.tutor.ConfigServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet>
DBConnection.java
public class DBConnection { public Connection getDBConnection() { Connection connection = null; try { connection = DriverManager.getConnection( "HOST_NAME", "USER_NAME", "PASSWORD"); } catch (SQLException e) { e.getLocalizedMessage(); System.out.println("Connection Failed! Check output console"); e.printStackTrace(); return null; } return connection; } }
SingletonDBConnection.java
import java.sql.Connection; import java.sql.SQLException; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class SingletonDBConnection { private static SingletonDBConnection singleInstance; private static DataSource dataSource; private static Connection dbConnect; private SingletonDBConnection() { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); dataSource = (DataSource) envContext.lookup("jdbc/testdb"); try { dbConnect = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } } catch (NamingException e) { e.printStackTrace(); } } public static SingletonDBConnection getInstance() { if(singleInstance == null) { synchronized (SingletonDBConnection.class) { if(singleInstance == null) { singleInstance = new SingletonDBConnection(); } } } return singleInstance; } public static Connection getConnInst() { try { dbConnect = dataSource.getConnection(); } catch (SQLException e1) { e1.printStackTrace(); } if(dbConnect == null) { try { Context initContext = new InitialContext(); Context envContext = (Context) initContext.lookup("java:/comp/env"); dataSource = (DataSource) envContext.lookup("jdbc/testdb"); try { dbConnect = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } } catch (NamingException e) { e.printStackTrace(); } } return dbConnect; } }
ListUsers.java
public List<User> getUsersList() { Connection conn; Statement stmt = null; ResultSet rs; List<User> arrUsersList = new ArrayList<User>(); conn = SingletonDBConnection.getInstance().getConnInst(); String strSQL = "SELECT UserId, UserName, Gender, UserLocation " + " FROM tblusers"; try { stmt = conn.createStatement(); rs = stmt.executeQuery(strSQL); while(rs.next()) { User objUser = new User(); objUser.setUserId(rs.getString("UserId")); objUser.setUserName(rs.getString("UserName")); objUser.setUserGender(rs.getString("Gender")); objUser.setUserLocation(rs.getString("UserLocation")); arrUsersList.add(objUser); } } catch (SQLException e) { e.printStackTrace(); } finally { if(conn != null) try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return arrUsersList; }
Java Tweaks
How to Avoid unnessecary HTML Code while generating HTML for Mail or HTML File
Method1
DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName)); dosReport.wrtiteBytes("<table><thead>"); dosReport.writeBytes("<th>Column1</th>"); dosReport.writeBytes("<th>Column2</th>"); dosReport.writeBytes("<th>Column3</th>"); dosReport.writeBytes("<th>Column4</th>"); dosReport.writeBytes("<th>Column5</th>"); dosReport.writeBytes("<th>Column6</th>"); dosReport.writeBytes("<th>Column7</th>"); dosReport.writeBytes("<th>Column8</th>"); dosReport.writeBytes("<th>Column9</th>"); dosReport.wrtiteBytes("</thead>");
Method2
Replace with Below
DataOutputStream dosReport = new DataOutputStream(new FileOutputStream(fileName)); dosReport.wrtiteBytes("<table><thead>"); String[] columns = {"Column1", "Column2", "Column3", "Column4", "Column5", "Column6", "Column7", "Column8", "Column9"}; for(int i = 0; i < columns.length; i++) dosReport.writeBytes("<th>" + columns[i] +"</th>"); dosReport.wrtiteBytes("</thead>");
Disadvantage:
In the Method1 you have fine control over individual cell(tds) so you can add properties like align, individual stylings can be applied.
How to read a file in java
The below code reads a Sample.txt file and places the content in a newly created Html file Sample.html.
The file from which the content should be read is placed in a project directory which is printed in the console using the below java code.
System.out.println("Working Directory = " + System.getProperty("user.dir"));
The above code prints the current project directory in console.
package com.mugil.servlets; import java.awt.Desktop; import java.io.*; class GenerateHTML { public static void main(String[] args) throws Exception { System.out.println("Working Directory = " + System.getProperty("user.dir")); BufferedReader br = new BufferedReader(new FileReader("Sample.txt")); File f = new File("source.htm"); BufferedWriter bw = new BufferedWriter(new FileWriter(f)); bw.write("<html>"); bw.write("<body>"); bw.write("<h1>ShowGeneratedHtml source</h1>"); String line; while ((line=br.readLine())!=null) { bw.write(line); bw.newLine(); } bw.write("</body>"); bw.write("</html>"); br.close(); bw.close(); Desktop.getDesktop().browse(f.toURI()); } }
executeupdate vs executequery vs execute
executeupdate vs executequery vs execute
ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.
int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.
boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.