Tuesday, May 3, 2016

XMPP chat Java client with smack

XMPP Chatting

1. Connection
2. Register User
3. Login
4. Display user list
5. Send message
6. Change password
7. disconnect


import java.io.IOException;
import java.util.Collection;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class ChatClient implements {

XMPPConnection connection;

public void login(String userName, String password) throws XMPPException {
ConnectionConfiguration cc = new ConnectionConfiguration("127.0.0.1", 5222, "127.0.0.1");

connection = new XMPPConnection(cc);
try {
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login(userName, password, "resource");// Login
System.out.println(connection.isAuthenticated());

} catch (Exception e) {

}

}

public void addUser(String userName, String password) throws XMPPException {
AccountManager accountManager = new AccountManager(connection);
try {
accountManager.createAccount(userName, password); // Create User
System.out.println("User Created");
accountManager.changePassword("12345"); // Change password
} catch (XMPPException e1) {
System.out.println(e1.getMessage());
}

}

public void changePassword(String password) throws XMPPException {
AccountManager accountManager = new AccountManager(connection);
try {
accountManager.changePassword("12345"); // Change password
System.out.println("Password Changed");

} catch (XMPPException e1) {
System.out.println(e1.getMessage());
}

}

public void sendMessage(String message, String to) throws XMPPException {
Chat chat = connection.getChatManager().createChat(to, this);
chat.sendMessage(message);
}

public void displayBuddyList() {
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();

System.out.println("\n\n" + entries.size() + " buddy(ies):");
for (RosterEntry r : entries) {
System.out.println(r.getUser());
}
}

public void disconnect() {
connection.disconnect();
}



public static void main(String args[]) throws XMPPException, IOException {
ChatClient c = new ChatClient();
String msg = "hello";
XMPPConnection.DEBUG_ENABLED = false;
c.addUser("hswain", "12345");
c.login("hswain@127.0.0.1", "12345");
c.displayBuddyList();
c.sendMessage(msg, "test@127.0.0.1"); // Send Message
c.changePassword("54321");
c.disconnect();
System.exit(0);
}


}

How to convert Html to Pdf using itextpdf

In Below code you can can convert pure html to PDF using Itextpdf.

You can specify custom header ,footer and page end content with page no.

<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.0.6</version>
</dependency>



import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zkoss.zul.Filedownload;

import com.itextpdf.text.BadElementException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.codec.Base64;
import com.itextpdf.tool.xml.Pipeline;
import com.itextpdf.tool.xml.XMLWorker;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.itextpdf.tool.xml.css.CssFile;
import com.itextpdf.tool.xml.css.StyleAttrCSSResolver;
import com.itextpdf.tool.xml.html.Tags;
import com.itextpdf.tool.xml.parser.XMLParser;
import com.itextpdf.tool.xml.pipeline.css.CSSResolver;
import com.itextpdf.tool.xml.pipeline.css.CssResolverPipeline;
import com.itextpdf.tool.xml.pipeline.end.PdfWriterPipeline;
import com.itextpdf.tool.xml.pipeline.html.AbstractImageProvider;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipeline;
import com.itextpdf.tool.xml.pipeline.html.HtmlPipelineContext;

public class PDFUtil{
static final Logger LOG = LoggerFactory.getLogger(PDFUtil.class);
static final String ENDTEXT = "<div><div align=\"" + "center" + "\""
+ "><hr/><b>PROHIBITION ON REDISCLOSURE OF CONFIDENTIAL INFORMATION</b></div> This notice accompanies a disclosure of information concerning an individual in alcohol/drug treatment, made to you with the consent of such individual. </div>";

public void exportPDF(String src, String fileName) {
String prci = FHSessionUtil.getOptionValueByKey("prci");
if (prci != null) {
src = src + prci;
} else {
src = src + ENDTEXT;
}
try {
InputStream is = new ByteArrayInputStream(src.getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A3);
PdfWriter writer = PdfWriter.getInstance(document, baos);
writer.setInitialLeading(12.5f);
MyFooter event = new MyFooter();
writer.setPageEvent(event);
writer.setStrictImageSequence(true);
document.open();
document.addTitle(fileName);
document.addCreationDate();
document.addCreator("By Himanshu");
document.addAuthor(FHSessionUtil.getCurrentUser().getFirstName());
document.setJavaScript_onLoad(FHSessionUtil.getAppResourcePath() + "/resources/js/bootstrap.min.js");
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.setImageProvider(new Base64ImageProvider());

Pipeline<?> pipeline = new CssResolverPipeline(getCSSResolver(), new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));

XMLWorker worker = new XMLWorker(pipeline, true);
XMLParser p = new XMLParser(worker);
p.parse(is);
document.close();

Filedownload.save(baos.toByteArray(), "application/pdf", fileName + ".pdf");
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
} catch (DocumentException e) {
// e.printStackTrace();
}

}

class MyFooter extends PdfPageEventHelper {
Font ffont = new Font(Font.FontFamily.UNDEFINED, 15, Font.ITALIC);

@Override
public void onEndPage(PdfWriter writer, Document document) {
PdfContentByte cb = writer.getDirectContent();
// Phrase header = new Phrase(FHSessionUtil.getOptionValueByKey("title"), ffont);
Phrase footer = new Phrase(FHSessionUtil.getOptionValueByKey("title"), ffont);
Phrase pageNo = new Phrase(String.valueOf(writer.getPageNumber()), ffont);

// ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, header, (document.right() - document.left()) / 2 + document.leftMargin(),
// document.top() + 10, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.right() - document.left()) / 2 + document.leftMargin(),
document.bottom() - 10, 0);
ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, pageNo, (document.right() - 10), document.bottom() - 10, 0);
}

@Override
public void onCloseDocument(PdfWriter writer, Document document) {
LOG.info("#######################");
Phrase footer = new Phrase(FHSessionUtil.getOptionValueByKey("title") + "", ffont);

PdfContentByte cb = writer.getDirectContent();

ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.right() - 10), document.bottom() - 10, 0);
}

}

class Base64ImageProvider extends AbstractImageProvider {

@Override
public Image retrieve(String src) {
int pos = src.indexOf("base64,");
try {
if (src.startsWith("data") && pos > 0) {
byte[] img = Base64.decode(src.substring(pos + 7));
return Image.getInstance(img);
} else {
return Image.getInstance(src);
}
} catch (BadElementException ex) {
return null;
} catch (IOException ex) {
return null;
}
}

@Override
public String getImageRootPath() {
return null;
}
}

// private String getHtmlString(String src) {
// StringBuilder sb = new StringBuilder();
// sb.append("<html><head><title></title></head><body >");
// sb.append(src);
// sb.append("</body></html>");
// return sb.toString();
// }

private CSSResolver getCSSResolver() {
CSSResolver cssResolver = new StyleAttrCSSResolver();
String resourcePath = FHSessionUtil.getAppResourcePath();
for (String cssFile : getCSSFiles()) {
InputStream fis;
try {
fis = new URL(resourcePath + cssFile).openStream();
CssFile cssfiletest = XMLWorkerHelper.getCSS(fis);
cssResolver.addCss(cssfiletest);
} catch (IOException e) {

}
}
return cssResolver;
}

private List<String> getCSSFiles() {
List<String> cssFiles = new ArrayList<>();
cssFiles.add("/resources/css/bootstrap.min.css");
cssFiles.add("/zkau/web/ccf53197/zul/css/zk.wcs");
cssFiles.add("/resources/css/plugins/iCheck/custom.css");
cssFiles.add("/resources/font-awesome/css/font-awesome.css");
cssFiles.add("/resources/css/animate.css");
cssFiles.add("/resources/css/plugins/toastr/toastr.min.css");
cssFiles.add("/resources/css/plugins/switch/bootstrap-switch.css");
cssFiles.add("/resources/css/mystyle.css");
cssFiles.add("/resources/css/style.css");
return cssFiles;
}


}

How to show java web project version using Maven

1. Pom.xml


<maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>

<plugin>
<artifactId>maven-war-plugin</artifactId>
<groupId>org.apache.maven.plugins</groupId>
<version>2.1.1</version>
<configuration>
<archive>
<manifestEntries>
<SCM-Revision>${maven.build.timestamp}</SCM-Revision>
</manifestEntries>
</archive>
</configuration>

</plugin>

2. Java code.

public static String getProjectVersion() {
ServletContext application = Sessions.getCurrent().getWebApp().getServletContext();
InputStream inputStream = application.getResourceAsStream("/META-INF/MANIFEST.MF");
Manifest manifest;
try {
manifest = new Manifest(inputStream);
Attributes attr = manifest.getMainAttributes();
return attr.getValue("SCM-Revision");
} catch (IOException e) {
e.printStackTrace();
}
return "";
}


How to Print in Zk

1. Print full page.

<button label="Print" onClick="Clients.print()" />

2. Print selected div.

Create PrintUtil  java class.


import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.util.Clients;

public class PrintUtil {

public static void print(Component comp) {
print(comp, "/MedXEMR/zk/template/template.zul", null);
}

public static void print(Component comp, String cssuri) {
print(comp, "/MedXEMR/zk/template/template.zul", cssuri);
}

public static void print(Component comp, String uri, String cssuri) {
String script = "printDiv('" + comp.getUuid() + "', '" + uri + "'";
if (cssuri != null) {
if (uri.contains("zkau") && !cssuri.startsWith("/"))
cssuri = "/" + cssuri; // absolute path if using default template.zul within jar file
script += ", '" + cssuri + "');";
} else {
script += ");";
}
Clients.evalJavaScript(script);

}
}

ZUL Code.

template.zul.

<zk xmlns:n="native">
<style src="${param.printStyle}" media="print" />
<html content="${param.printContent}" />
<div>
<div align="center">
<n:hr />
<n:b>
PROHIBITION ON REDISCLOSURE OF CONFIDENTIAL INFORMATION
</n:b>
</div>
</div>


</zk>



Javascript Code.

function printDiv(uuid, uri, cssuri) {
if (uuid && uri) {
var wgt = zk.Widget.$(uuid), body = document.body, ifr = jq('#zk_printframe');
if (!ifr[0]) {
jq(body).append('<iframe id="zk_printframe" name="zk_printframe"' + ' style="width:0;height:0;border:0;position:fixed;"' + '></iframe>');
ifr = jq('#zk_printframe');
}
// wait form submit response then call print function
// reference: http://isometriks.com/jquery-ajax-form-submission-with-iframes
ifr.unbind('load.ajaxsubmit').bind('load.ajaxsubmit', function() {
var iw = ifr[0].contentWindow || ifr[0];
iw.document.body.focus();
iw.print();
});

jq(body).append('<form id="zk_printform" action="' + uri + '" method="post" target="zk_printframe"></form>');
var form = jq('#zk_printform'), content = '<div style="width: ' + wgt.$n().offsetWidth + 'px">' + jq(wgt.$n())[0].outerHTML + '</div>';
form.append(jq('<input/>').attr({
name : 'printContent',
value : content
}));
if (cssuri) {
form.append(jq('<input/>').attr({
name : 'printStyle',
value : cssuri
}));
}
form.submit().remove();
} else {
window.print();
}
}

how to call Print in zul?

<a
class="btn btn-sm btn-default fa fa-print btn-group-btn"
onClick="com.swain..PrintUtil.print(sampleform)"
tooltiptext="Print">
Print
</a>






jQuery export PDF with jspdf api in Zk

1. Download jspdf api https://mrrio.github.io/jsPDF/examples/basic.html

2. Download  html2canvas api. https://html2canvas.hertzen.com/

3. If you need multiple page PDF then download canvas2image api. https://github.com/hongru/canvas2image

Javascript code.


var form;
function initPDF(target) {
form = $('.' + target), cache_width = form.width(), a4 = [ 595.28, 841.89 ]; // for a4 size paper width and height

}
// create pdf
function createPDF(fileName) {
$('body').scrollTop(0);
getCanvas().then(function(canvas) {
var img = canvas.toDataURL("image/png"), doc = new jsPDF({
unit : 'px',
format : 'a4'
});
doc.addImage(img, 'JPEG', 20, 20);
var image = new Image();
image = Canvas2Image.convertToJPEG(canvas);

var croppingYPosition = 1095;
count = (image.height) / 1095;

for (var i = 1; i < count; i++) {
doc.addPage();
var sourceX = 0;
var sourceY = croppingYPosition;
var sourceWidth = image.width;
var sourceHeight = 1095;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = 0;
var destY = 0;
var canvas1 = document.createElement('canvas');
canvas1.setAttribute('height', destHeight);
canvas1.setAttribute('width', destWidth);
var ctx = canvas1.getContext("2d");
ctx.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
var image2 = new Image();
image2 = Canvas2Image.convertToJPEG(canvas1);
image2Data = image2.src;
doc.addImage(image2Data, 'JPEG', 20, 20);
croppingYPosition += destHeight;
}
doc.save(fileName + '.pdf');
form.width(cache_width);
});
}

// create canvas object
function getCanvas() {
form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
return html2canvas(form, {
imageTimeout : 2000,
removeContainer : true
});

}

ViewModel Code.

Just pass the div css class name.

public void initPDF(String className) {
Clients.evalJavaScript("initPDF('" + className + "');");
}

public void exportHTMLTOPDF(String className) {
Clients.evalJavaScript("createPDF('" + className + "');");
}




jQuery Full calendar implemented in ZK


Full calendar


1. Download http://fullcalendar.io/download/

2. Document http://fullcalendar.io/docs/

3.  Javascript code.

function initCalendar(data, date) {
var decodedString = $.parseJSON(Base64.decode(data));

$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar('render');
// $('#calendar').fullCalendar('rerenderEvents');
// var obj = $.parseJSON(document.getElementById('json').getAttribute("value"));
$('#calendar').fullCalendar({
header : {
left : 'prev,next today',
center : 'title',
right : 'month,agendaWeek,agendaDay'
},
defaultView : 'agendaWeek',
minTime : "07:00:00",
maxTime : "19:00:00",
defaultDate : date,
selectable : true,
selectHelper : true,
select : function(start, end) {
var title = "New Appointment";
var eventData;
eventData = {
title : title,
start : start,
end : end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); // stick? = true
zAu.send(new zk.Event(zk.Widget.$('$json'), "onCreateCalendar", eventData, {
toServer : true
}));
$('#calendar').fullCalendar('unselect');
},
eventDrop : function(event, delta, revertFunc) {

// alert(event.title + " was dropped on " + event.start.format());
//
// if (!confirm("Are you sure about this change?")) {
// revertFunc();
// }
eventData = {
id : event.id,
title : event.title,
start : event.start,
end : event.end
};
zAu.send(new zk.Event(zk.Widget.$('$json'), "onUpdateCalendar", eventData, {
toServer : true
}));

},
eventResize : function(event, delta, revertFunc) {

// alert(event.title + " end is now " + event.end.format());
//
// if (!confirm("is this okay?")) {
// revertFunc();
// }
eventData = {
id : event.id,
title : event.title,
start : event.start,
end : event.end
};
zAu.send(new zk.Event(zk.Widget.$('$json'), "onUpdateCalendar", eventData, {
toServer : true
}));

},
eventClick : function(calEvent, jsEvent, view) {

eventData = {
id : calEvent.id,
title : calEvent.title,
start : calEvent.start,
end : calEvent.end
};
zAu.send(new zk.Event(zk.Widget.$('$json'), "onUpdateCalendar", eventData, {
toServer : true
}));
},
editable : true,
eventLimit : true, // allow "more" link when too many events
events : decodedString
});


}

4.  Code.

<div class="col-md-9">
<h:include id="json" type="hidden"></h:include>
<n:div id="calendar"></n:div>
</div>

5. ViewModel Code.

Just call it inside init method with JSON String.

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Clients.evalJavaScript("initCalendar(\"'" + Base64.encode(json) + "'\",\"'" + format.format(new Date()) + "'\");");

update event.

@Listen("onUpdateCalendar=#json")
public void onUpdateCalendar(org.zkoss.zk.ui.event.Event event) {
//code here.
}

create event.

@Listen("onCreateCalendar=#json")
public void onCreateCalendar(org.zkoss.zk.ui.event.Event event) {
//code here.
}




How ChatGPT can Benefit Coding: Your Guide to Leveraging an AI Language Model

 Introduction: Hello, coders! Welcome to this blog post on how ChatGPT, an AI language model, can benefit your coding skills and projects. A...