Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, March 26, 2012

HashMap in Xpages - CheckBox group many times will Issue.,

I got an Issue with checkBoxGroup in Xpage.,

I can add the value in checkBoxGroup and also I can retrive...

But the Label value I can not retrive...

I have used the following code for getting the keyvalue...

getcomponent("id").getAttributes().get("xxx")

getcomponent("id").getAttributes().values()

Each time I got failed...

Finally I got an idea to implement the HashMap with SSJS.,

In client side java script we can get the values very easily.,

But in server side Java script It is difficult.,

I am not teling It is Impossible. We can (Please tell If you can :) )

The following code will make some idea to use HashMap...

try
{
if((sessionScope.db !="" ))
{
var view12=getComponent("view").getValue();
var db=session.getDatabase(sessionScope.server,sessionScope.db)
var vw:NotesView=db.getView(view12);
var colName= vw.getColumnNames().toArray();
var count=0;
var listCount:java.util.HashMap=new java.util.HashMap();
if(listCount.isEmpty() == false)
{
listCount.clear()
}

while(colName.length>count)
{
listCount.put(count,colName[count]);
count++;
}
return listCount.keySet().toArray()
}
else
{
return ""
}
}
catch(e)
{
return "You did not choose any column"
}

Wednesday, January 4, 2012

Html to Pdf using Java

The following Java Code is used to convert the HTML content into PDF

import java.io.*;

import java.io.FileOutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
public class pdfCreation {

/**
* @Purpose : Converting html file into PDF.
* External jar file used iText-2.0.8.jar, core-renderer.jar
* xml-apis-xerces-2.9.1.jar
*/
public static void main(String[] args) {
try{
//html file path
String inputFile=”C:\\workspace\\html2Pdf\\src\\pack1\\sample.html”;
//Output pdf file path
String outputFP=”C:\\sample.pdf”;
File inputHTMLFile=new File(inputFile);
if(!inputHTMLFile.exists()){
System.out.println(”Input html File does not exists!”);
System exit(0);
}
String url=inputHTMLFile.toURI().toURL().toString();
OutputStream os=new FileOutputStream(outputFP);
ITextRenderer renderer=new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(os);
os.close();
System.out.println(”HTML file was converted into PDF”);
}
catch(Exception e){
e.printStackTrace();
}
}
}

Friday, December 30, 2011

Create document from Text file in Lotus Notes

This article about import data from txt document .

Step 1:

create one .txt document like below.

“mahendran”,”9003544190″
“Ramya”,”9948484884″
“hi”, “8585885858″

“mahendran”,”9003544190″

“Ramya”,”9948484884″

“krishna”, “8585885858″

and save name as test

Step 2:

create one form and name as “mahe” and create two field (i) name1 (II) mobile

save the form and map this form to one view and also map field to columns

Step3:

create one lotus script agent and paste following code

Option Public

Sub Initialize

Dim session As New NotesSession

Dim db As NotesDatabase

Set db = session.CurrentDatabase

Dim uiws As New NotesUIWorkspace

Dim fileCSV As Variant

‘Declare variables to hold data

Dim Name1 As String

Dim mobile As String

Dim counter As Integer

Dim doc As NotesDocument

counter =0

’setup file number

filenum% = FreeFile()

‘Ask user for file location

fileCSV = uiws.OpenFileDialog(False, “Choose the CSV file”,”*.txt” ,”c:\temp”)

‘If the user chose a file then process

If Not IsEmpty(fileCSV ) Then

Open fileCSV(0) For Input As filenum%

Do Until EOF(filenum%)

‘Read a line of data

Input #filenum%, name1, mobile

‘Create Notes document and write values to it

Set doc = db.CreateDocument

With doc

.name1=name1

.mobile=mobile

.form=”mahe”

End With

’save document

Call doc.save(False, False)

counter = counter +1

Loop

MsgBox “You imported ” & counter & ” records.”

End If

End Sub

Step 4:

run the agent and select test.txt and go back to view you can see imported file

Iterator methods for Java

This is one of the most useful interface in java collection framework. It is similar to vector but it is unsynchronized .

Also it is similar to Enumeration in the Java collections framework. But it differ from enumerations in two ways

Iterators allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

There are powerful methods for traversing elements.

Methods:

hasNext()
next()
remove()

Stpes:
1. First, obtain iterator to the start of the collection by calling the collection’s iterator( ) method
2. Then call the hasNext( ) method to find wethear nest item is available or not.
3. Finally, within the loop, obtain each element by calling next( ).

ListIterator

With help of this class traverse the elements in both ways, modify & adding new element in list during iteration, and obtain the iterator’s current position in the list.

Additional methods:

hasPrevious()
previous()
nextIndex()
previousIndex()

Java File Reader and File Writer

Here i want to discuss about how to read data from a file and

to append that content to another file by java program. Here

i use FileReader class for reading content from file and FileWriter

for append data to file. Also BufferedReader class is used to

getting input from keyboard at run time.

Coding:

import java.io.*;

public class DemoFileCreation{

public static void main(String[] args) throws IOException {

FileReader inputStream = null;

FileWriter outputStream = null;

BufferedReader dataIn = new BufferedReader( new InputStreamReader(System.in) );

System.out.println(”Enter Roll No:”);

String sno=dataIn.readLine();

System.out.println(”Enter Name:”);

String name=dataIn.readLine();

try {

File f=new File(”demo.txt”);

if(!f.exists())

{

f.createNewFile();

}

inputStream = new FileReader(f);

outputStream = new FileWriter(”characteroutput.doc”,true);

outputStream.write(”\n”);

outputStream.write(”Roll No: “+sno);

outputStream.write(”\tName: “+name);

}

finally {

if (inputStream != null) {

inputStream.close();

}

if (outputStream != null) {

outputStream.close();

}

}

}

}

JUNIT testing

JUNIT testing is a unit testing framework for java Programming Language. Which is one of the family of unit testing frameworks collectively known as xUnit and organized with sUnit.

Unit test = “Individual unit of Testing”.

xUnit : Various code-driven testing frameworks have come to be known collectively as xUnit. These frameworks allow testing of different elements (units) of software, such as functions and classes. The main advantage of xUnit frameworks is that they provide an automated solution with no need to write the same tests many times, and no need to remember what should be the result of each test.

Code Driven Testing : It checks the Expected output comes or not for all modules.

SUnit : SUnit is a unit testing framework for the programming language Smalltalk.

Small Talk : Smalltalk is an object-oriented, dynamically typed, reflective programming language.

JUnit Testing Example:

* Write Class for testing

* Testcase

* Test Suite

Example:

Class{

§public class TestClass {

public static int testfunction(int a,int b){

return(a+b); }

public static void main(String[] as){

TestClass1 obj=new TestClass1();

System.out.print(obj.testfunction(2,3));

}

}

Test case:

§Test case class should starts with test and should be the subclass testCase class.

public class TestClass1Test extends TestCase {

§

protected void setUp() throws Exception {

super.setUp();

}

protected void tearDown() throws Exception {

super.tearDown();

}

public void testTestfunction() {

int c=TestClass1.testfunction(5, 3);

assertEquals("Test Fails",8,c);

}

}

TestSuite:

§public class AllTests { §

public static Test suite() {

TestSuite suite = new TestSuite(AllTests.class.getName());

//$JUnit-BEGIN$

suite.addTestSuite(TestClass1Test.class);

//$JUnit-END$

return suite;

}

}

Batch file Creation

Batch file creation is nothing but the action which is done in MS-DOS

Example :
Running a java file...
//********************************
e:
cd javap
javac
javac hello.java
java hello
//****************************************
SVAE IT AS .bat extension

How to stop a running thread

Example for stopping the Running thread in simple java Coding

public class ThreadStop extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread");
}
public void shutdown() {
running = false;
}
public static void main(String[] args)
throws InterruptedException {
ThreadStop t = new ThreadStop();
t.start();
Thread.sleep(5000);
t.shutdown();
}
}

XSLT and XML

XSLT is a specialized programming language for transforming XML documents. Even though it is part of XSLand as such intended to be used for transforming XMLdocuments into XSL-FO for presentation purposes...
Fro example :

XML Data :

<?xml-version = "1.0" ?>
<?xml-stylesheet type="text/xsl" href="samplexslt.xsl"?>
<sample>
<a>
<Name>Ramkumar</Name>
<age>23</age>
<occupation>SE</occupation>
</a>
<a>
<Name>Ramya</Name>
<age>21</age>
<occupation>SE</occupation>
</a>
<a>
<Name>Mahe</Name>
<age>21</age>
<occupation>SE</occupation>
</a>
</sample>

XSLT example:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>XSLT test</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Name</th>
<th>Age</th>
<th>Occupation</th>
</tr>
<xsl:for-each select="sample\a">
<tr>
<td><xsl:value-of select="age"/></td>
<xsl:choose>
<xsl:when test="age &gt; 21">
<td bgcolor="#ff00ff">
<xsl:value-of select="Name"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="Name"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

XSL,XSLT,XSL-FO and XML

Xsl:

(eXtensible Stylesheet Language) A style sheet standard from the W3C that is used to convert an XML document into many formats for publishing and printing. XSL is similar to the Cascading Style Sheets (CSS) in HTML and is compatible with CSS2. An XML document is converted by an "XSLT Processor," also called an "XSLT Transformation Engine," into the new format based on three sets of XSL description languages, as follows:


XSL-FO - Convert to Page Formats
The XSL Formatting Objects (XSL-FO) language is used to apply page formatting to an XML document and produce an XSL-FO document. The resulting XSL-FO file, or simply "FO file," serves as a paginated master file for conversion to page-oriented formats such as PDF, PostScript, AFP or PCL. The conversion is handled by a third-party program such as XML Engine for Print (XEP) from RenderX (www.renderx.com) or Apache Formatting Objects Processor (http://xmlgraphics.apache.org/fop).

When a user selects a PDF document on a Web page, the file may actually reside in XSL-FO format and be rendered on the fly to PDF for that user in real time. The XSL-FO format was designed to outlive proprietary page description languages and is a good choice for archiving paginated documents.

XSLT - Convert to XML, HTML and Text
The XSL Transformation Language (XSLT) is used to convert an XML document into an HTML or text document or to another XML document with a different structure. The most common XSLT transformations are from XML to HTML for rendering in a Web browser. Unlike the paginated format of XSL-FO, HTML pages are structured as scrollable windows of infinite vertical length.

If the XSLT to transform XML to HTML is embedded in an XML document, the document can be converted to HTML on the fly for rendering, just as XSL-FO can be turned into PDF on the fly for downloading.

Xpath - Select and Calculate
The XML Path Language (Xpath) is used in conjunction with XSL-FO and XSLT to select elements within an XML document. Xpath can also be used to count items; for example, how many times a particular tag occurs in the document. See xquery, xml and css

Java pdfwriter and Document

With the use of Java Document class, We can easily create pdf file in a efficient manner.

And also we can use to Lotus notes Java Agent.,

Sample Code for Header and Footer is in below,

If we want to put a logo in all pages, In headerfooter class's objects are helping us...

Image img1=Image.getInstance("C:\\Documents and Settings\\maarga_trainees\\Desktop\\test\\maarga_logo.jpg");
HeaderFooter header= new HeaderFooter(new Phrase(new Chunk((Image) img1,0,0)), false);
HeaderFooter footer = new HeaderFooter(new Phrase("Footer"), new Phrase("."));
docpdf.setHeader(header);
docpdf.setFooter(footer);

Here we have header and footer. And also we can add a new table in header and footer for proper order.

Table in header and footer of PDF file...

Using Java Agent...

We can make a table in HeaderFooter class for a proper alignment of PDF generation.

We can manipulate the header and footer section using that Table.,

There we can put our Lotus notes document also.,

Table t=new Table(1,1);
t.addCell("Hai It is Header...|");
t.setBackgroundColor(Color.blue);
ph.add(t);
HeaderFooter header= new HeaderFooter(ph, true);
header.setBorder(100);
header.setTop(500);
HeaderFooter footer = new HeaderFooter(new Phrase("Footer"), new Phrase("."));
docpdf.setHeader(header);
docpdf.setFooter(footer);

Anchor link page-citation in iText

We can give the link and page citation for or PDF file using itext....

For instead of generating pdf via xml and xslt, We can get from itext,

here also we can give link and page citation use of following classes.,

Font font = new Font();
font.setColor(Color.GREEN);
font.setStyle(Font.UNDERLINE);
docpdf.add(new Chunk("Chapter 1"));
docpdf.add(new Paragraph(new Chunk("Press here to go chapter 2", font).setLocalGoto("2")));// Code 2
docpdf.newPage();
docpdf.add(new Chunk("Chapter 2").setLocalDestination("2"));
docpdf.add(new Paragraph(new Chunk("http://www.maargasystems.com", font).setAnchor("http://www.maargasystems.com")));//Code 3
docpdf.add(new Paragraph( new Chunk("Open CreatePDFInlotus.pdf chapter 3", font).setRemoteGoto("D:\\Ram\\CreatePDFInlotus.pdf", "3")));//Code 4

Concatenating the pdf files

With the use of iText, We can concatenate pdf files.

PdfReader and PdfCopyFields classes are used for this purpose.,

In java Agent we can upload it into lotus notes also...


PdfReader reader1 = new PdfReader("1PDF.pdf");
PdfReader reader2 = new PdfReader("2PDF.pdf");
PdfCopyFields copy =new PdfCopyFields(new FileOutputStream("concatenatedPDF.pdf"));
copy.addDocument(reader1);
copy.addDocument(reader2);

Can change the version of the PDF? "YES"

Can we change the version of our PDF?

Definitely "YES"...
With the use of PdfReader class in iText, we can easily change the version of the PDF file.

For Older version supports in some functionalities in proper alignment. But in our new version, Sometimes it does not hear our commands... At that time we can use the following for changing the pdf version...

PdfWriter.getInstance(doc1, new FileOutputStream("D:\\pdf\\pdf1.pdf"));
doc1.open();
doc1.add(new Paragraph("For checking Version"));
doc1.close();
PdfReader reader1 = new PdfReader("D:\\pdf\\pdf1.pdf");
System.out.println("Version of PDF1:"+reader1.getPdfVersion());
char str1=reader1.getPdfVersion();
PdfWriter writer=PdfWriter.getInstance(doc, new FileOutputStream("D:\\pdf\\pdf2.pdf"));
writer.setPdfVersion(PdfWriter.VERSION_1_2);
doc.open();
doc.add(new Paragraph("Version Of PDF1-->>"+str1));
doc.close();
PdfReader reader = new PdfReader("D:\\pdf\\pdf2.pdf");
System.out.println("Version of PDF2:"+reader.getPdfVersion());

Rotation of Text (depends upon the angle)

We can rotate the text in which direction we want., Using skew() in iText.

There we can give some text design and good look for our input text....


Paragraph p = new Paragraph("Ram");
document.add(p);
Chunk chunk = new Chunk("Raj");
chunk.setSkew(45f, 0f);
document.add(chunk);
document.add(Chunk.NEWLINE);
chunk.setSkew(0f, 45f);
document.add(chunk);
document.add(Chunk.NEWLINE);
chunk.setSkew(-45f, 0f);
document.add(chunk);

Make Text - SubText - Subsub Text (1, 1.1, 1.1.1)

Here the Chunk class has different type of functions for manipulating our Input text in PDF.

There is an very useful function for putting the hierarchical numbering in our PDF... Which is in below.,

document.open();
Chunk c1,c2,c3;
c1 = new Chunk("Ram");
c1.setTextRise(7.0f);
document.add(c1);
c2 = new Chunk("Raj");
c2.setTextRise(3.0f);
document.add(c2);
c3 = new Chunk(".java");
c3.setTextRise(-2.0f);
document.add(c3);
document.close();

Ordered contents in iText (PDF generation)

We can use the List for adding the contents in our document.

So with the use of that List object we can easily manipulate the I/P data or data that are taken from any external resource.

doc.open();
//Create a numbered List with 30-point field for the numbers.
List list=new List(true,30);
list.add(new ListItem("Ramt"));
list.add(new ListItem("Raj"));
list.add(new ListItem("Kamal"));
doc.add(list);
//Add a separator.
doc.add(Chunk.NEWLINE);
//Create a symboled List with a 30-point field for the symbols.
list=new List(false,30);
list.add (new ListItem ("Hello"));
list.add (new ListItem ("World"));
list.add (new ListItem ("Hai"));
list.add (new ListItem ("Kumar"));
// Add the list to the document.
doc.add (list);
doc.close ();