When you need to protect PDF files using password, you can use following iText codes to encrypt PDF using passwords.
String ownerPasswd="owner";
String userPasswd="user";
PdfReader reader = new PdfReader("/apps/abc.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("/apps/abc_pw.pdf"));
stamper.setEncryption(userPasswd.getBytes(), ownerPasswd.getBytes(),
PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
stamper.close();
reader.close();
Library versions used,
itextpdf-5.5.10.jar
bcprov-ext-jdk14-1.47.jar
You can use preferred encryption algorithms. Refer documentations.
Showing posts with label API. Show all posts
Showing posts with label API. Show all posts
Thursday, June 21, 2018
Tuesday, July 18, 2017
JAVA Web Start (JWS) JNLP Example
JWS is introduced to use client side application processing through web. Clients are downloading JNLP application and execute the application to process data.
- Create JAR file that you want to execute it in client side (TestJNLP.jar)
- Sign the file using your certificate
- keytool -genkey -keystore testKeys -alias test
- jarsigner -keystore testKeys TestJnlp.jar test
- Create JNLP file (Test.jnlp)
- Deploy JNLP file and signed JAR file in web server
- Download JNLP file and execute application (http://localhost:8080/Test.jnlp)
Sample JNLP file
<?xml version="1.0" encoding="utf-8"?><jnlp spec="1.0+" codebase="http://localhost:8080/" href="Test.jnlp">
<information>
<title>Jnlp Testing</title>
<vendor>Testing</vendor>
<homepage href="http://localhost:8080/" />
<description>Testing Testing</description>
</information>
<security>
<all-permissions/>
</security>
<resources>
<j2se version="1.6+" />
<jar href="TestJnlp.jar" />
</resources>
<application-desc main-class="com.test.TestJnlp" />
</jnlp>
For Windows OS, change OS type in resource XML tag as follows.
<resources os="Windows">
For native library access, you have to create DLL into JAR file and then signed the JAR file using certificate and deploy into web server. Then, you have to change JNLP file as follows.
<resources os="Windows">
<j2se version="1.6+" />
<jar href="TestJnlp.jar" />
<nativelib href="DLLtoJAR.jar" />
</resources>
Create DLL into a JAR file using single command
jar cvf DLLtoJAR.jar testDLL.dll
Resource
https://dzone.com/articles/java-web-start-jnlp-hello
Tuesday, November 29, 2016
Change enum values by passing values
Following code can be used to change the enum return value as required by passing parameters.
import java.text.MessageFormat;
public enum Errors {
USERNAME_NOT_FOUND("User not found"),
USERNAME_EXISTS("Username {0} already exists."),
USERNAME_CONTAINS_INVALID_CHARS("Username {0} contains invalid characters {1}.");
private final String message;
Errors(String message) {
this.message = message;
}
@Override
public String toString() {
return message;
}
public String getMessage(Object... args) {
return MessageFormat.format(message, args);
}
public static void main(String args[]) {
System.out.println(Errors.USERNAME_NOT_FOUND); System.out.println(Errors.USERNAME_EXISTS.getMessage("username")); System.out.println(Errors.USERNAME_CONTAINS_INVALID_CHARS.getMessage("us%ername", "%"));
}
}
import java.text.MessageFormat;
public enum Errors {
USERNAME_NOT_FOUND("User not found"),
USERNAME_EXISTS("Username {0} already exists."),
USERNAME_CONTAINS_INVALID_CHARS("Username {0} contains invalid characters {1}.");
private final String message;
Errors(String message) {
this.message = message;
}
@Override
public String toString() {
return message;
}
public String getMessage(Object... args) {
return MessageFormat.format(message, args);
}
public static void main(String args[]) {
System.out.println(Errors.USERNAME_NOT_FOUND); System.out.println(Errors.USERNAME_EXISTS.getMessage("username")); System.out.println(Errors.USERNAME_CONTAINS_INVALID_CHARS.getMessage("us%ername", "%"));
}
}
Monday, July 25, 2016
HTTP Request/ Response capture in JAVA
Following properties can be used to enable console output of http requests and responses in JAVA.
System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump",
"true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump",
"true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump",
"true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump",
"true");
Tuesday, May 26, 2015
Set email priority in JAVA
Following code can be used to set priority in email server. This is tested and worked fine.JAVA mail API is used for the development.
// Setting the priority of an email is simply a matter of setting the X-Priority header field.
// Values of 1 through 5 are acceptable
// 1 = highest priority, 3 = normal, and 5 = lowest priority.
// Set the email's priority to high:
email.AddHeaderField("X-Priority","1");
// Setting the priority of an email is simply a matter of setting the X-Priority header field.
// Values of 1 through 5 are acceptable
// 1 = highest priority, 3 = normal, and 5 = lowest priority.
// Set the email's priority to high:
email.AddHeaderField("X-Priority","1");
Monday, January 12, 2015
Check sever status using Socket in JAVA
In some cases, you have to check server status whether server is running or not using telnet command before executing commands on the server application. This code can be used to check whether there is a running something on the given IP and Port.
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.*;
public class Telnet {
public static void main(String args[]) {
try {
String ip = "192.168.*.*";
int port = 23;
Socket s1 = new Socket(ip, port);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
if (dis != null) {
System.out.println("Connected IP : " + ip + ", Port : " + port);
} else {
System.out.println("Connection Invalid.");
}
dis.close();
s1.close();
} catch (Exception e) {
System.out.println("Not Connected, check Ip and Port.");
}
}
}
import java.io.DataInputStream;
import java.io.InputStream;
import java.net.*;
public class Telnet {
public static void main(String args[]) {
try {
String ip = "192.168.*.*";
int port = 23;
Socket s1 = new Socket(ip, port);
InputStream is = s1.getInputStream();
DataInputStream dis = new DataInputStream(is);
if (dis != null) {
System.out.println("Connected IP : " + ip + ", Port : " + port);
} else {
System.out.println("Connection Invalid.");
}
dis.close();
s1.close();
} catch (Exception e) {
System.out.println("Not Connected, check Ip and Port.");
}
}
}
Wednesday, September 24, 2014
JAVA Server Socket Server & Client Program
Following code can be used to run a server socket application. This socket application listen requests on "locathost" port "10225" .
Socket Server Program
public class SocketServer {
ServerSocket m_ServerSocket;
Logger logger;
int SERVER_PORT = 10225;
public SocketServer() {
try {
m_ServerSocket = new ServerSocket(SERVER_PORT);
} catch (IOException ioe) {
System.out.println("Could not create server socket " + SERVER_PORT + " Quitting. " + ioe);
System.exit(-1);
}
int id = 0;
while (true) {
try {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
} catch (Exception ioe) {
System.out.println("Constructor : " + ioe);
}
}
}
public String process(String input) {
String response = "";
// your process logic
return response;
}
class ClientServiceThread extends Thread {
Socket m_clientSocket;
int m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID) {
m_clientSocket = s;
m_clientID = clientID;
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
System.out.println("Accepted Client ID - " + m_clientID + " |Address - " + m_clientSocket.getInetAddress().getHostName());
try {
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
while (m_bRunThread) {
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if (!clientCommand.equalsIgnoreCase("Quit")) {
out.println(process(clientCommand));
}
if (clientCommand.equalsIgnoreCase("quit")) {
m_bRunThread = false;
} else {
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
} catch (IOException ioe) {
System.out.println("ClientServiceThread.run " + ioe);
}
}
}
}
public static void main(String[] args) {
new ChargeSocket();
}
}
Socket Client Program
public String connectToSocket(String ip, int port, String request) {
String response = null;
Socket socket = null;
try {
socket = new Socket(ip, port);
} catch (UnknownHostException unknownhostexception) {
System.out.println("Unknown Host :localhost");
socket = null;
} catch (IOException ioexception) {
System.out.println("Cant connect to server at " + ip + " " + port + " Make sure it is running.");
socket = null;
}
if (socket == null) {
return null;
}
BufferedReader bufferedreader = null;
PrintWriter printwriter = null;
try {
bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printwriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printwriter.println(request);
printwriter.flush();
response = bufferedreader.readLine();
System.out.println("Server Says : " + response);
printwriter.println("Quit");
printwriter.flush();
} catch (IOException ioexception) {
System.out.println("Exception during communication. Server probably closed connection.");
ioexception.printStackTrace();
} finally {
try {
printwriter.close();
bufferedreader.close();
socket.close();
} catch (Exception exception1) {
exception1.printStackTrace();
}
}
return response;
}
Socket Server Program
public class SocketServer {
ServerSocket m_ServerSocket;
Logger logger;
int SERVER_PORT = 10225;
public SocketServer() {
try {
m_ServerSocket = new ServerSocket(SERVER_PORT);
} catch (IOException ioe) {
System.out.println("Could not create server socket " + SERVER_PORT + " Quitting. " + ioe);
System.exit(-1);
}
int id = 0;
while (true) {
try {
Socket clientSocket = m_ServerSocket.accept();
ClientServiceThread cliThread = new ClientServiceThread(clientSocket, id++);
cliThread.start();
} catch (Exception ioe) {
System.out.println("Constructor : " + ioe);
}
}
}
public String process(String input) {
String response = "";
// your process logic
return response;
}
class ClientServiceThread extends Thread {
Socket m_clientSocket;
int m_clientID = -1;
boolean m_bRunThread = true;
ClientServiceThread(Socket s, int clientID) {
m_clientSocket = s;
m_clientID = clientID;
}
public void run() {
BufferedReader in = null;
PrintWriter out = null;
System.out.println("Accepted Client ID - " + m_clientID + " |Address - " + m_clientSocket.getInetAddress().getHostName());
try {
in = new BufferedReader(new InputStreamReader(m_clientSocket.getInputStream()));
out = new PrintWriter(new OutputStreamWriter(m_clientSocket.getOutputStream()));
while (m_bRunThread) {
String clientCommand = in.readLine();
System.out.println("Client Says :" + clientCommand);
if (!clientCommand.equalsIgnoreCase("Quit")) {
out.println(process(clientCommand));
}
if (clientCommand.equalsIgnoreCase("quit")) {
m_bRunThread = false;
} else {
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
m_clientSocket.close();
System.out.println("...Stopped");
} catch (IOException ioe) {
System.out.println("ClientServiceThread.run " + ioe);
}
}
}
}
public static void main(String[] args) {
new ChargeSocket();
}
}
Socket Client Program
public String connectToSocket(String ip, int port, String request) {
String response = null;
Socket socket = null;
try {
socket = new Socket(ip, port);
} catch (UnknownHostException unknownhostexception) {
System.out.println("Unknown Host :localhost");
socket = null;
} catch (IOException ioexception) {
System.out.println("Cant connect to server at " + ip + " " + port + " Make sure it is running.");
socket = null;
}
if (socket == null) {
return null;
}
BufferedReader bufferedreader = null;
PrintWriter printwriter = null;
try {
bufferedreader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
printwriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
printwriter.println(request);
printwriter.flush();
response = bufferedreader.readLine();
System.out.println("Server Says : " + response);
printwriter.println("Quit");
printwriter.flush();
} catch (IOException ioexception) {
System.out.println("Exception during communication. Server probably closed connection.");
ioexception.printStackTrace();
} finally {
try {
printwriter.close();
bufferedreader.close();
socket.close();
} catch (Exception exception1) {
exception1.printStackTrace();
}
}
return response;
}
Tuesday, July 22, 2014
Set Password in PDF in Jasper Report
Following code snip can be used to create protected PDF. This authentication is enabled in jasper report 5.6 onward.
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setEncrypted(true);
configuration.set128BitKey(true);
configuration.setUserPassword("jasper");
configuration.setOwnerPassword("reports");
configuration.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
exporter.setConfiguration(configuration);
exporter.exportReport();
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
configuration.setEncrypted(true);
configuration.set128BitKey(true);
configuration.setUserPassword("jasper");
configuration.setOwnerPassword("reports");
configuration.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
exporter.setConfiguration(configuration);
exporter.exportReport();
Thursday, March 20, 2014
HTTP GET/POST Example
Following example can be used to send HTTP GET or POST request to web server using JAVA application.
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://seguide.blogspot.com";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://seguide.blogspot.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
List urlParameters = new ArrayList();
urlParameters.add(new BasicNameValuePair("name", "sujith"));
urlParameters.add(new BasicNameValuePair("pass", "abc123"));
urlParameters.add(new BasicNameValuePair("param1", "param1"));
urlParameters.add(new BasicNameValuePair("param2", "param2"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://seguide.blogspot.com";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://seguide.blogspot.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
List
urlParameters.add(new BasicNameValuePair("name", "sujith"));
urlParameters.add(new BasicNameValuePair("pass", "abc123"));
urlParameters.add(new BasicNameValuePair("param1", "param1"));
urlParameters.add(new BasicNameValuePair("param2", "param2"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
}
Wednesday, September 18, 2013
JAVA Resultset metadata information
In JAVA, you can use retrieve information about resultset using following code.
String str ="select * from table001";
ResultSet rs = st.executeQuery(str);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Number of columns - " + rsmd.getColumnCount());
System.out.println("JAVA data type for Table field 3 - "+rsmd.getColumnClassName(3));
System.out.println("Database Table field 3 type - "+rsmd.getColumnTypeName(3));
String str ="select * from table001";
ResultSet rs = st.executeQuery(str);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println("Number of columns - " + rsmd.getColumnCount());
System.out.println("JAVA data type for Table field 3 - "+rsmd.getColumnClassName(3));
System.out.println("Database Table field 3 type - "+rsmd.getColumnTypeName(3));
Tuesday, November 20, 2012
Java Trigger ( Quartz )
Quartz is a library that can be used to implement scheduler in JAVA application.
This library supports for modify Triggering in many variations.
You have to implement your class implementing Job class as "TestJob.java".
TestJob.java
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TestJob implements Job {
@Override
public void execute(JobExecutionContext jec) throws JobExecutionException {
System.out.println("Hello Quartz!");
}
}
Schedule.java
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class Schedule {
public static void main(String[] args) throws Exception {
JobDetail job = JobBuilder.newJob(TestJob.class).withIdentity("testJob", "group1").build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5).repeatForever())
.build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
And you can use Quartz as a cron job.
Cron.java
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class Cron
{
public static void main( String[] args ) throws Exception
{
JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity("testJobName", "group1").build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
.build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
Following libraries must be added to the projects.
This library supports for modify Triggering in many variations.
You have to implement your class implementing Job class as "TestJob.java".
TestJob.java
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class TestJob implements Job {
@Override
public void execute(JobExecutionContext jec) throws JobExecutionException {
System.out.println("Hello Quartz!");
}
}
This "Schedule.java" will be triggered by 5 seconds.
Schedule.java
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class Schedule {
public static void main(String[] args) throws Exception {
JobDetail job = JobBuilder.newJob(TestJob.class).withIdentity("testJob", "group1").build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName", "group1")
.withSchedule(
SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5).repeatForever())
.build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
And you can use Quartz as a cron job.
Cron.java
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class Cron
{
public static void main( String[] args ) throws Exception
{
JobDetail job = JobBuilder.newJob(TestJob.class)
.withIdentity("testJobName", "group1").build();
Trigger trigger = TriggerBuilder
.newTrigger()
.withIdentity("dummyTriggerName", "group1")
.withSchedule(
CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
.build();
Scheduler scheduler = new StdSchedulerFactory().getScheduler();
scheduler.start();
scheduler.scheduleJob(job, trigger);
}
}
Following libraries must be added to the projects.
- quartz-2.1.6.jar
- log4j-1.2.16.jar
- c3p0-0.9.1.1.jar
- slf4j-log4j12-1.6.1.jar
- slf4j-api-1.6.1.jar
Split large TEXT file in JAVA
In some cases, large files has to be split into smaller ones for the fast processing. In my case, file contained about 10 million records. Processing 10 million is bit low than parallel processing smaller files.
Split.java can be used to create files with number of predefined lines.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Split {
private final static String NEWLINE = System.getProperty("line.separator");
public static void readFileData(String filename, int lines) throws IOException {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(
filename));
StringBuffer stringBuffer = new StringBuffer();
String line;
int i = 0;
int counter = 1;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append(NEWLINE);
i++;
if (i >= lines) {
saveFile(stringBuffer, filename + counter);
stringBuffer = new StringBuffer();
i = 0;
counter++;
}
}
bufferedReader.close();
} catch (IOException e) {
throw new IOException("read file error " + filename);
}
}
private static void createFile(StringBuffer stringBuffer, String filename) {
String path = (new File("")).getAbsolutePath();
File file = new File(path + "/" + filename);
FileWriter output = null;
try {
output = new FileWriter(file);
output.write(stringBuffer.toString());
System.out.println("file " + path + filename + " written");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
}
}
}
public static void main(String[] args) {
String fileName = "/usr/sujith/filename.txt"
int lines = 1000000;
try {
readFileData(fileName, lines);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Split.java can be used to create files with number of predefined lines.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Split {
private final static String NEWLINE = System.getProperty("line.separator");
public static void readFileData(String filename, int lines) throws IOException {
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(
filename));
StringBuffer stringBuffer = new StringBuffer();
String line;
int i = 0;
int counter = 1;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append(NEWLINE);
i++;
if (i >= lines) {
saveFile(stringBuffer, filename + counter);
stringBuffer = new StringBuffer();
i = 0;
counter++;
}
}
bufferedReader.close();
} catch (IOException e) {
throw new IOException("read file error " + filename);
}
}
private static void createFile(StringBuffer stringBuffer, String filename) {
String path = (new File("")).getAbsolutePath();
File file = new File(path + "/" + filename);
FileWriter output = null;
try {
output = new FileWriter(file);
output.write(stringBuffer.toString());
System.out.println("file " + path + filename + " written");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
}
}
}
public static void main(String[] args) {
String fileName = "/usr/sujith/filename.txt"
int lines = 1000000;
try {
readFileData(fileName, lines);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Monday, November 19, 2012
Call AXIS web service with security
AXIS web service uses .wsdd XML file to read username & passwordCallbackClass. Here, it shown sample .wsdd file.
client_deploy.wsdd
<deployment xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<transport name="http" pivot="java:org.apache.axis.transport.http.HTTPSender"/>
<globalConfiguration >
<requestFlow >
<handler type="java:org.apache.ws.axis.security.WSDoAllSender" >
<parameter name="action" value="UsernameToken"/>
<parameter name="user" value="M_TICKET"/>
<parameter name="passwordType" value="PasswordText" />
<parameter name="passwordCallbackClass"
value="PWCallBackClass"/>
</handler>
</requestFlow >
</globalConfiguration >
</deployment>
Then you have to implement "PWCallBackClass" class as below.
PWCallBackClass .java
Following code can be used to call web service with security implemented with AXIS.
import java.rmi.Remote;
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import org.apache.axis.AxisFault;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;
import com.comverse_in.prepaid.ccws.ServiceLocator;
import com.comverse_in.prepaid.ccws.ServiceSoap;
import com.comverse_in.prepaid.ccws.ServiceSoapProxy;
import com.comverse_in.prepaid.ccws.ServiceSoapStub;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.message.token.UsernameToken;
public class TestWS {
public static void main(String args[]) throws ServiceException, RemoteException{
EngineConfiguration config = new FileProvider("client_deploy.wsdd");
ServiceLocator locator = new ServiceLocator(config);
Remote remote = locator.getPort(ServiceSoap.class);
Stub axisPort = (Stub)remote;
axisPort._setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
axisPort._setProperty(UsernameToken.PASSWORD_TYPE, WSConstants.PASSWORD_TEXT);
axisPort._setProperty(WSHandlerConstants.USER, "sujith");
axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, "PWCallBackClass");
ServiceSoap service = (ServiceSoapStub)axisPort;
System.out.println("Calling service...");
int ver = service.getVersionId();
System.out.println("get version id service returned " + ver);
}
}
Reference :- http://ws.apache.org/wss4j/package.html
Following jars needed to run web service client than AXIS jars.
client_deploy.wsdd
<deployment xmlns="http://xml.apache.org/axis/wsdd/"
xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<transport name="http" pivot="java:org.apache.axis.transport.http.HTTPSender"/>
<globalConfiguration >
<requestFlow >
<handler type="java:org.apache.ws.axis.security.WSDoAllSender" >
<parameter name="action" value="UsernameToken"/>
<parameter name="user" value="M_TICKET"/>
<parameter name="passwordType" value="PasswordText" />
<parameter name="passwordCallbackClass"
value="PWCallBackClass"/>
</handler>
</requestFlow >
</globalConfiguration >
</deployment>
Then you have to implement "PWCallBackClass" class as below.
PWCallBackClass .java
public class PWCallBackClass implements CallbackHandler {
private static final byte[] key = {
(byte)0x31, (byte)0xfd, (byte)0xcb, (byte)0xda,
(byte)0xfb, (byte)0xcd, (byte)0x6b, (byte)0xa8,
(byte)0xe6, (byte)0x19, (byte)0xa7, (byte)0xbf,
(byte)0x51, (byte)0xf7, (byte)0xc7, (byte)0x3e,
(byte)0x80, (byte)0xae, (byte)0x98, (byte)0x51,
(byte)0xc8, (byte)0x51, (byte)0x34, (byte)0x04,
};
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof WSPasswordCallback) {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
/*
* here call a function/method to lookup the password for
* the given identifier (e.g. a user name or keystore alias)
* e.g.: pc.setPassword(passStore.getPassword(pc.getIdentfifier))
* for testing we supply a fixed name/fixed key here.
*/
if (pc.getUsage() == WSPasswordCallback.KEY_NAME) {
pc.setKey(key);
}
else {
pc.setPassword("Hsy84#ep$8&@v");
}
} else {
throw new UnsupportedCallbackException(
callbacks[i], "Unrecognized Callback");
}
}
}
Following code can be used to call web service with security implemented with AXIS.
TestWS.java
import java.rmi.RemoteException;
import javax.xml.rpc.ServiceException;
import org.apache.axis.AxisFault;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;
import com.comverse_in.prepaid.ccws.ServiceLocator;
import com.comverse_in.prepaid.ccws.ServiceSoap;
import com.comverse_in.prepaid.ccws.ServiceSoapProxy;
import com.comverse_in.prepaid.ccws.ServiceSoapStub;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.handler.WSHandlerConstants;
import org.apache.ws.security.message.token.UsernameToken;
public class TestWS {
public static void main(String args[]) throws ServiceException, RemoteException{
EngineConfiguration config = new FileProvider("client_deploy.wsdd");
ServiceLocator locator = new ServiceLocator(config);
Remote remote = locator.getPort(ServiceSoap.class);
Stub axisPort = (Stub)remote;
axisPort._setProperty(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
axisPort._setProperty(UsernameToken.PASSWORD_TYPE, WSConstants.PASSWORD_TEXT);
axisPort._setProperty(WSHandlerConstants.USER, "sujith");
axisPort._setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, "PWCallBackClass");
ServiceSoap service = (ServiceSoapStub)axisPort;
System.out.println("Calling service...");
int ver = service.getVersionId();
System.out.println("get version id service returned " + ver);
}
}
Reference :- http://ws.apache.org/wss4j/package.html
Following jars needed to run web service client than AXIS jars.
- opensaml-1.0.1.jar
- wss4j-2.1.jar
- ws-security-5.1.0-M1.jar
- xmlsec-1.3.0.jar
Thursday, October 4, 2012
Random String (ID) generate in JAVA
java.util.UUID package contains random String generation feature.
Refer below code.
UUID uuid = UUID.randomUUID();
uuid.toString();
Generated Strings
a5b74c68-41de-4605-affb-882e97e33779
8d615a58-8899-4d94-9bf0-b79e411d06b6
Refer below code.
UUID uuid = UUID.randomUUID();
uuid.toString();
Generated Strings
a5b74c68-41de-4605-affb-882e97e33779
8d615a58-8899-4d94-9bf0-b79e411d06b6
Monday, October 1, 2012
export EDITOR=vi
In some cases, it is not shown data in Linux terminal window. In that case, you can use "vi editor" to view hidden data.
Following command can be used to export data to vi editor.
export EDITOR=vi
This is most commonly used for crontab edition.
Following command can be used to export data to vi editor.
export EDITOR=vi
This is most commonly used for crontab edition.
Tuesday, September 25, 2012
byte[] to Object in java
If data must be sent over network, it is needed to send
data as byte stream. In these cases, it can be used object serialize method as follows. Below method can be used to convert Object to byte stream.
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
return out.toByteArray();
}
Below deserialize method can be used to converted stream back to Object. If Object is specific use Object casting methods further.
public static Object deserialize(byte[] data) {
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
return is.readObject();
}
NOTE :- This can be avoided by using Java RMI technology.
Tuesday, September 11, 2012
Linux crontab Command
crontab is used for executing scheduled processes. For example, you can run database backup everyday using schell script.
crontab -l
Above command list the all available crontab command.
crontab -e
This command can be used to edit crontab command fro your preference.
Sample crontab command is shown below. This script.sh script is executed every day at midnight.
0 0 means zero minute at zero hours(midnight).
0 0 * * * /home/sujith/script.sh
crontab -l
Above command list the all available crontab command.
crontab -e
This command can be used to edit crontab command fro your preference.
Sample crontab command is shown below. This script.sh script is executed every day at midnight.
0 0 means zero minute at zero hours(midnight).
0 0 * * * /home/sujith/script.sh
Monday, April 2, 2012
Create HTTPS Web Service Client
HTTPS web services uses certificate authentication. So, web service clients must be created with SSL.
In netbeans, you can create HTTPS web service client. Follow the steps.
1) Create Java project in Netbeans
2) Copy certificate into project root directory
3) Use Netbeans Web Service Client wizard to create client
This will create web service clients successfully. But, when calling service, it is again needed to create SSL session with service.
Before calling service, certificate needs to be stored in java key store.
Refer article on seguide :- http://seguide.blogspot.com/2009/12/use-keytool-to-generate-keys-in-java.html
Use following code before calling service methods.
System.setProperty("javax.net.ssl.trustStore", "export/home/myTrustStore"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.trustStoreType", "JKS"); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
URL url = new URL("https://~~~~~~~~~~~~~~~~~~~/service.asmx?wsdl");
Service service = new Service(url); service.getServiceSoap().getData();
In netbeans, you can create HTTPS web service client. Follow the steps.
1) Create Java project in Netbeans
2) Copy certificate into project root directory
3) Use Netbeans Web Service Client wizard to create client
This will create web service clients successfully. But, when calling service, it is again needed to create SSL session with service.
Before calling service, certificate needs to be stored in java key store.
Refer article on seguide :- http://seguide.blogspot.com/2009/12/use-keytool-to-generate-keys-in-java.html
Use following code before calling service methods.
System.setProperty("javax.net.ssl.trustStore", "export/home/myTrustStore"); System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
System.setProperty("javax.net.ssl.trustStoreType", "JKS"); System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
URL url = new URL("https://~~~~~~~~~~~~~~~~~~~/service.asmx?wsdl");
Service service = new Service(url); service.getServiceSoap().getData();
Monday, March 26, 2012
USSD menu termination value
Unstructured Supplementary Service Data (USSD) menu designing is more considerable. Since, having issues will lead the USSD server to unstable status.
while submitting menu to mobile, these parameter values must be used.
17 - mobile created session termination
2 - application session creation
3 - application session termination
Sunday, March 25, 2012
Remove log files created by log4j
Add following code segment to configure file in log4j.
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=example.log
log4j.appender.R.MaxFileSize=100KB
log4j.appender.R.MaxBackupIndex=7
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
MaxBackupIndex will hold maximum number of 7 files in the location that files are created.
Subscribe to:
Posts (Atom)