Enlightensoft's Blog

Helping in your each step

  • Categories

  • Authors

Archive for the ‘Core Java’ Category

Pass String (or Custom Object) List into Store Procedure from Java

Posted by Pankil Patel on November 1, 2012

  1. Create type:create or replace
    TYPE STRING_LIST_TYPE AS TABLE OF VARCHAR2(7);
  2. Java Code:ARRAY sqlArrayOfString = getSqlArray(arrayListOfString.toArray(), “STRING_LIST_TYPE”,
    tssPortalDataSource);
  3. Store Procedure input param:P_NAME in STRING_LIST_TYPE,
  4. Use list into IN parameter of query in Store Procedure:

select * from EMPLOY where EMPLOY_NAME in (select column_value from (Table(CAST(P_NAME AS STRING_LIST_TYPE))))

Advertisements

Posted in Core Java, Database, Oracle | Tagged: , | Leave a Comment »

How to Reload Applet or Remove class file Caching for Applet

Posted by Pankil Patel on August 26, 2012

Step1: Add below script to your HTML page after End of Body (After </BODY> tag)

<script type=”text/javascript”>
window.APPLET_WRAPER_TAG = “object”;
//window.APPLET_WRAPER_TAG = “APPLET”;
//window.APPLET_WRAPER_TAG = “EMBED”;

window.TAG_TYPE = “application/x-java-applet”;

window.currectApplet = true;
window.allAppletsHTML = new Array();
window.allApplets = new Array();

reloadApplet();

function reloadApplet() {

var resultListObects = getallAppletsHTML();

if (window.currectApplet) {
for (i = 0; i < resultListObects.length; i++) {
window.allAppletsHTML[i] = resultListObects[i].outerHTML;
var htmls = resultListObects[i].outerHTML.split(‘.class’);
htmls[0] = htmls[0] + ‘.class?PankilPatel’;
var html = htmls[0] + htmls[1];
resultListObects[i].outerHTML = html;
}
window.currectApplet = false;
} else {
for (i = 0; i < resultListObects.length; i++) {
resultListObects[i].outerHTML = window.allAppletsHTML[i];
}
window.currectApplet = true;
}
if (!window.currectApplet) {
reloadApplet(resultListObects);
}
}

function getallAppletsHTML() {
var listObects = document
.getElementsByTagName(window.APPLET_WRAPER_TAG);
var resultListObects = new Array();
for (i = 0, index = 0; i < listObects.length; i++) {
if (window.APPLET_WRAPER_TAG.toUpperCase() == “APPLET”
|| listObects[i].type == window.TAG_TYPE) {
resultListObects[index] = listObects[i];
index++;
}
}
return resultListObects;
}
</script>

 

Step2: Configure value of TAG which is used to display Applet in HTML Page, like object, APPLET or EMBED into first line of script.

Step3: Same way change value of “window.TAG_TYPE” to type given in TAG which is used to display applet, into second line of script.

 

Now no need to restart your any browser after applet change.

Enjoy your hassle free development of Applet……………….. 🙂

 

Note: It will work only if you have used only one way to import applet into your HTML file which is any one of  object, APPLET or EMBED.

Posted in Applet | Tagged: , , , , , , | Leave a Comment »

Override toString to Display all class content (Except Static) Using Apache APIs

Posted by Pankil Patel on August 9, 2012

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}

Posted in Core Java | Tagged: , , , , , | Leave a Comment »

Export to .pdf using Core JAVA

Posted by Pankil Patel on June 22, 2012

Required JAR:

itextpdf-5.3.0.jar

itext-xtra-5.3.0.jar

 

 

File: PDFCreator.java

package co.cc.enlightensoft.pdf;

import java.io.FileOutputStream;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class PDFCreator {
public static void main(String[] args) {
try {

// creation of the document with a certain size and certain margins
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
// HtmlWriter.getInstance(document, System.out);
PdfWriter.getInstance(document,
new FileOutputStream(“text.pdf”));
// we add some meta information to the document
document.addAuthor(“Bruno Lowagie”);
document.addSubject(“This is the result of a Test.”);
// we open the document for writing
document.open();

// ##################### Paragraph : Start #####################
document.add(new Paragraph(“Hello world”));
// ##################### Paragraph : End #####################

// ##################### Chunk : Start #####################
Chunk chunk = new Chunk(“Hello world”, FontFactory.getFont(
FontFactory.COURIER, 20, Font.ITALIC, new BaseColor(
255, 0, 0)));
document.add(chunk);
// ##################### Chunk : End #####################

// ##################### Anchor : Start #####################
Anchor anchor = new Anchor(“\nGoogle\n”);
anchor.setName(“Google”);
anchor.setReference(“http://www.google.com&#8221;);

document.add(anchor);
// ##################### Anchor : End #####################

// ##################### Image : Start #####################
Image image = Image.getInstance(“Photo.JPG”);
image.scaleAbsolute(100, 100);
document.add(image);
// ##################### Image : End #####################

// ##################### Table : Start #####################
PdfPTable table = createTable1();
table.setSpacingBefore(5);
table.setSpacingAfter(5);
document.add(table);

// ##################### Table : End #####################

System.out.println(“File Created…”);
} catch (DocumentException de) {
System.err.println(de.getMessage());
}
document.close();
} catch (Throwable t) {
t.printStackTrace();
}
}

/** The resulting PDF file. */
public static final String RESULT = “text.pdf”;

/**
* Creates a table; widths are set with setWidths().
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable1() throws DocumentException {
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(288 / 5.23f);
table.setWidths(new int[] { 2, 1, 1 });
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 1”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set with setWidths().
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable2() throws DocumentException {
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(288);
table.setLockedWidth(true);
table.setWidths(new float[] { 2, 1, 1 });
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 2”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set in the constructor.
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable3() throws DocumentException {
PdfPTable table = new PdfPTable(new float[] { 2, 1, 1 });
table.setWidthPercentage(55.067f);
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 3”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set with special setWidthPercentage() method.
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable4() throws DocumentException {
PdfPTable table = new PdfPTable(3);
Rectangle rect = new Rectangle(523, 770);
table.setWidthPercentage(new float[] { 144, 72, 72 }, rect);
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 4”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

/**
* Creates a table; widths are set with setTotalWidth().
*
* @return a PdfPTable
* @throws DocumentException
*/
public static PdfPTable createTable5() throws DocumentException {
PdfPTable table = new PdfPTable(3);
table.setTotalWidth(new float[] { 144, 72, 72 });
table.setLockedWidth(true);
PdfPCell cell;
cell = new PdfPCell(new Phrase(“Table 5”));
cell.setColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phrase(“Cell with rowspan 2”));
cell.setRowspan(2);
table.addCell(cell);
table.addCell(“row 1; cell 1”);
table.addCell(“row 1; cell 2”);
table.addCell(“row 2; cell 1”);
table.addCell(“row 2; cell 2”);
return table;
}

}

Posted in Core Java | Tagged: , , , , , , , | 1 Comment »

Pure JDBC Connection for Oracle Database in Core JAVA using Service name & SID

Posted by Pankil Patel on June 22, 2012

Required JAR: classes12.jar

Pure JDBC Connection for Oracle Database in Core JAVA using :  Service name :

Connection con = null;
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection(
“jdbc:oracle:thin:@Hostname:Port/Service name”,
“username”, “password”);

Statement s = con.createStatement();

Pure JDBC Connection for Oracle Database in Core JAVA using :  SID :

Connection con = null;
Class.forName(“oracle.jdbc.driver.OracleDriver”);
con = DriverManager.getConnection(
“jdbc:oracle:thin:@Hostname:Port:SID”,
“username”, “password”);

Statement s = con.createStatement();

Posted in Core Java, Oracle | Tagged: , , , , , | Leave a Comment »

Export to .xls using Core JAVA

Posted by Pankil Patel on June 22, 2012

Required JAR: jxl-2.6.12.jar

File: XlsCreator.java

package co.cc.enlightensoft.xls;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class XlsCreator {
private static WritableSheet s;
private static WritableCellFormat cf;
private static WritableCellFormat cfd;
private static File file;
public static int NUMBER_OF_TIME_QUERY_EXICUTION = 2;

public static WritableWorkbook createFile() throws IOException,
WriteException {
String filename = “QueryResponceTime.xls”;
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale(“en”, “EN”));
XlsCreator.file = new File(filename);
WritableWorkbook workbook = Workbook
.createWorkbook(XlsCreator.file, ws);
XlsCreator.s = workbook.createSheet(“Sheet1”, 0);
// XlsCreator.summary = workbook.createSheet(“Output”, 1);

/* Format the Font */
WritableFont wf = new WritableFont(WritableFont.ARIAL, 12,
WritableFont.BOLD);
WritableFont wfd = new WritableFont(WritableFont.ARIAL, 10,
WritableFont.NO_BOLD);

XlsCreator.cf = new WritableCellFormat(wf);
XlsCreator.cfd = new WritableCellFormat(wfd);

XlsCreator.cf.setWrap(true);
XlsCreator.cfd.setWrap(false);
XlsCreator.cf.setBackground(Colour.AQUA);
XlsCreator.cf.setBorder(Border.ALL, BorderLineStyle.THICK);
XlsCreator.cfd.setBorder(Border.ALL, BorderLineStyle.MEDIUM);

XlsCreator.s.setColumnView(0, 30);
XlsCreator.s.setColumnView(1, 30);
XlsCreator.s.setColumnView(2, 30);

createHeader();
return workbook;
}

public static void closeFile(WritableWorkbook workbook) throws IOException,
WriteException {
workbook.write();
workbook.close();
}

public static void createHeader() throws RowsExceededException,
WriteException {
/* Creates Label and writes date to one cell of sheet */
Label oid = new Label(0, 0, “OID”, XlsCreator.cf);
Label totalTime = new Label(1, 0, “Total Time (Milli Second)”,
XlsCreator.cf);
Label queryTime = new Label(2, 0, “Query Time (Milli Second)”,
XlsCreator.cf);
XlsCreator.s.addCell(oid);
XlsCreator.s.addCell(totalTime);
XlsCreator.s.addCell(queryTime);
}

public static void addRow(long oid, long totalTime, long queryTime,
int index) throws RowsExceededException, WriteException {
Number c1_data = new Number(0, index, oid, cfd);
Number c2_data = new Number(1, index, totalTime, cfd);
Number c3_data = new Number(2, index, queryTime, cfd);
XlsCreator.s.addCell(c1_data);
XlsCreator.s.addCell(c2_data);
XlsCreator.s.addCell(c3_data);
}

public static void main(String[] args) throws WriteException, IOException {
WritableWorkbook wb = XlsCreator.createFile();
addRow(123, 456, 001, 1);
addRow(52468, 123, 010, 2);
addSummary(3);
XlsCreator.closeFile(wb);
System.out.println(“.xls file is created… \n Location: ”
+ XlsCreator.file.getAbsoluteFile());
}

public static void addSummary(int index) throws RowsExceededException,
WriteException {
String avg = “AVERAGE”;
String avgTotalTime = “AVERAGE(B2:B”
+ (NUMBER_OF_TIME_QUERY_EXICUTION + 1) + “)”;
String avgQueryTime = “AVERAGE(C2:C”
+ (NUMBER_OF_TIME_QUERY_EXICUTION + 1) + “)”;

// Create label for average
Label formulaLabel = new Label(0, index, avg, cf);
XlsCreator.s.addCell(formulaLabel);

// Create a formula for average
Formula formulaAvgTotalTime = new Formula(1, index, avgTotalTime, cf);
XlsCreator.s.addCell(formulaAvgTotalTime);

// Create a formula for average
Formula formulaAvgQueryTime = new Formula(2, index, avgQueryTime, cf);
XlsCreator.s.addCell(formulaAvgQueryTime);

String min = “MIN”;
String minTotalTime = “MIN(B2:B” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;
String minQueryTime = “MIN(C2:C” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;

// Create label for average
Label minLabel = new Label(0, index + 1, min, cf);
XlsCreator.s.addCell(minLabel);

// Create a formula for average
Formula formulaMinTotalTime = new Formula(1, index + 1, minTotalTime,
cf);
XlsCreator.s.addCell(formulaMinTotalTime);

// Create a formula for average
Formula formulaMinQueryTime = new Formula(2, index + 1, minQueryTime,
cf);
XlsCreator.s.addCell(formulaMinQueryTime);

String max = “MAX”;
String maxTotalTime = “MAX(B2:B” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;
String maxQueryTime = “MAX(C2:C” + (NUMBER_OF_TIME_QUERY_EXICUTION + 1)
+ “)”;

// Create label for average
Label maxLabel = new Label(0, index + 2, max, cf);
XlsCreator.s.addCell(maxLabel);

// Create a formula for average
Formula formulaMaxTotalTime = new Formula(1, index + 2, maxTotalTime,
cf);
XlsCreator.s.addCell(formulaMaxTotalTime);

// Create a formula for average
Formula formulaMaxQueryTime = new Formula(2, index + 2, maxQueryTime,
cf);
XlsCreator.s.addCell(formulaMaxQueryTime);

}
}

Posted in Core Java | Tagged: , , , , , , , , , | Leave a Comment »

How to convert generic list to array: List to Long[] Array???

Posted by Pankil Patel on April 8, 2011

How to convert generic list to array: List<Long> to Long[] Array???

Main point in this question is to pass one argument (fixed length empty array of specific object type) to “toArray” method of  “Collection” interface.

public static void main(String[] args) {

A a = new A();

List<Long> longList = new ArrayList<Long>();
longList.add(23l);
longList.add(2l);
longList.add(3l);

a.setArrayLong((Long[])longList.toArray(new Long[longList.size()]));

}

public class A {

private Long[] arrayLong;

public Long[] getArrayLong() {
return arrayLong;
}

public void setArrayLong(Long[] arrayLong) {
this.arrayLong = arrayLong;
}

}

Posted in Core Java | 1 Comment »

Audio – wav to mp3, flv to wave, flv to mp3, wav to pm file conversion

Posted by Pankil Patel on August 30, 2010

/**
*          AudioUtils.java File
*/
package co.cc.enlightensoft.util;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* This utils class would provide all Audio operations like convert Flv To Mp3
* etc.
*
* @author Pankil Patel
*
*/
public class AudioUtils {

private static Log LOG = LogFactory.getLog(FileUtils.class);

/**
*
* @param directory
* @return
* @throws IOException
*/
public static boolean convertFlvToMp3(String flvFile, String mp3Folder,
String mp3FileName) throws IOException {
String cmd = “ffmpeg -title \”” + mp3FileName + “\” -i \”” + flvFile
+ “\” -acodec mp3 -ac 2 -ab 128 -vn -y \”” + mp3Folder
+ mp3FileName + “.mp3\””;
LOG.info(“converFlvToMp3 cmd: ” + cmd);
Runtime.getRuntime().exec(cmd.split(” “));
System.out.println(“converFlvToMp3: Done………………”);
// Runtime.getRuntime().exec(cmd.split(” “));
return true;
}

/**
*
* @param directory
* @return
* @throws IOException
*/
public static boolean convertFlvToWav(String flvNameFileWithFullPath,
String wavFileNameWithFullPath) throws IOException {
String cmd = “ffmpeg -i ” + flvNameFileWithFullPath + ” -y ”
+ wavFileNameWithFullPath;
LOG.info(“convertFlvToWav cmd: ” + cmd);
RuntimeUtils.executeCommand(cmd.split(” “));
System.out.println(“convertFlvToWav: Done………………”);
return true;
}

/**
*
* @param directory
* @return
* @throws IOException
*/
public static boolean convertWavToMP3(String wavNameFileWithFullPath,
String mp3FileNameWithFullPath) throws IOException {
String cmd = “lame -V2 ” + wavNameFileWithFullPath + ” ”
+ mp3FileNameWithFullPath;
LOG.info(“convertWavToMP3 cmd: ” + cmd);
RuntimeUtils.executeCommand(cmd.split(” “));
System.out.println(“convertWavToMP3: Done………………”);
return true;
}

/**
* @param wavFileFolderPath
* @param genderCommand
* @return
* @throws IOException
*/
public static boolean convertWavToPM(String wavFileFullPath,
String genderCommand, String pmGeneratorPath) throws IOException {
String cmd = pmGeneratorPath + genderCommand + ” ” + wavFileFullPath;
LOG.info(“convertWavToPM cmd: ” + cmd);
RuntimeUtils.executeCommand(cmd.split(” “));
System.out.println(“convertWavToPM: Done………………”);
return true;
}
}

/**
*         RuntimeUtils.java File
*/
package co.cc.enlightensoft.util;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
* @author Pankil Patel
*
*/
public class RuntimeUtils {
private static final Log LOG = LogFactory.getLog(RuntimeUtils.class);

/**
* Executes the given command and return the results as a list
*
* @param cmd
*            The command that is being executed.
* @return List The list of the out put
*/
public static List<String> executeCommand(String… cmd) {
Process process = null;
try {
process = Runtime.getRuntime().exec(cmd);
} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
BufferedReader localBufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String str;
ArrayList<String> localArrayList = null;
try {
str = localBufferedReader.readLine();

localArrayList = new ArrayList<String>();
while (str != null) {
localArrayList.add(str);
str = localBufferedReader.readLine();
}
} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
return localArrayList;
}

/**
* Executes the given command and return the results as a list
*
* @param cmd
*            The command that is being executed.
* @return List The list of the out put
*/
public static List<String> executeCommand(String cmd) {
Process process = null;
try {
process = Runtime.getRuntime().exec(cmd);

try {// For Printing Error
process.waitFor();
BufferedReader buf = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
String line = “”;
while ((line = buf.readLine()) != null) {
System.out.println(line);
}
} catch (InterruptedException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}

} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
BufferedReader localBufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String str;
ArrayList<String> localArrayList = null;
try {
str = localBufferedReader.readLine();

localArrayList = new ArrayList<String>();
while (str != null) {
localArrayList.add(str);
str = localBufferedReader.readLine();
}
} catch (IOException e) {
LOG.info(e.getMessage() + e);
e.printStackTrace();
}
return localArrayList;
}
}

Posted in Core Java, Other | 1 Comment »

How to Execute command line command from java Application

Posted by Pankil Patel on August 22, 2010

Step 1: Write bellow two line in your code wherever you want to execute command from java application as it is executed from command prompt.

String cmd = “your command”;
Runtime.getRuntime().exec(cmd.split(” “));

Gooooooooooooooooooood Luck………………..

Posted in Core Java | Leave a Comment »

Thread Local

Posted by Pankil Patel on June 3, 2010

How to set & get value in thread specific local?

Step 1:

Create a class like bellow:

Step 2:

Set thread specific value in that.

Like: ABCThreadLocal.set(10);

Step 3:

Get that value in any time during that thread.

Like: ABCThreadLocal.get();

Hureeeeeeeeeeee Ready to use Your Thread Local which persist Object’s ( Integer in this case ) value during the thread execution.

Posted in Core Java | Leave a Comment »