Wednesday, January 11, 2017

Java Program : How to find the relation between a boy and a girl using FLAMES.

It is really a fun game. Below find out Java code for this game.


You can check LOVE Calculator  .


Here is program.


package swain.swain;

public class Flames {

public static String getMatchResult(String fname, String sname) {
String firstName, secondName;
if (fname != null & sname != null) {
firstName = fname.trim().toLowerCase();
secondName = sname.trim().toLowerCase();
String firstNames[] = firstName.split(" ");
String secondNames[] = secondName.split(" ");
firstName = "";
secondName = "";
for (int i = 0; i < firstNames.length; i++) {
firstName = firstName + firstNames[i];
}
for (int i = 0; i < secondNames.length; i++) {
secondName = secondName + secondNames[i];
}
int length = secondName.length() + secondName.length();
boolean namecheck[] = new boolean[secondName.length()];
for (int i = 0; i < secondName.length(); i++) {
namecheck[i] = false;
}
for (int i = 0; i < firstName.length(); i++) {
for (int j = 0; j < secondName.length(); j++) {
if ((namecheck[j] == false) && (firstName.charAt(i) == secondName.charAt(j))) {
namecheck[j] = true;
length = length - 2;
break;
}
}
}
boolean flamescheck[] = new boolean[6];
for (int i = 0; i < 6; i++) {
flamescheck[i] = true;
}
int count = 6;
int k = 1, deleted_letters = 0;
int j;
for (j = 0; j <= count; j++) {
if (k <= length) {
if (j == count) {
j = 0;
}
if (flamescheck[j] == true) {
k = k + 1;
}
}
if ((k - 1) == length) {
deleted_letters = deleted_letters + 1;
flamescheck[j] = false;
k = 1;
}
if (deleted_letters == 6) {
if (j == 0) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are good FRIENDS";
} else if (j == 1) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are LOVERS";
} else if (j == 2) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " have alot of AFFECTION";
} else if (j == 3) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are MARRIED";
} else if (j == 4) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are ENEMIES";
} else if (j == 5) {
return firstName.toUpperCase() + " and " + secondName.toUpperCase() + " are SIBLINGS";
}
break;
}
}
}
return null;
}

public static void main(String args[]) {
System.out.println(Flames.getMatchResult("Rama", "Sita"));
}
}

Output:

How to convert JSON file to String

Below method will return String. You need to pass argument file path.



public static String getStringFromInputStream(String filepath) {

         BufferedReader br = null;
         StringBuilder sb = new StringBuilder();

         String line;
         try {
             br = new BufferedReader(new FileReader(filepath));
             while ((line = br.readLine()) != null) {
                 sb.append(line);
             }

         } catch (IOException e) {
             e.printStackTrace();
         } finally {
             if (br != null) {
                 try {
                      br.close();
                 } catch (IOException e) {
                      e.printStackTrace();
                 }
             }
         }

         return sb.toString();


    }

How to get current week date range and previous week date range using JodaTime .

Here is Joda time Maven dependency.
<dependency>
                                                <groupId>com.fasterxml.jackson.datatype</groupId>
                                                <artifactId>jackson-datatype-joda</artifactId>
                                                <version>2.8.1</version>
                                </dependency>

Below program you can find out current and previous week date range.

package swain.swain;

import java.util.Date;

import org.joda.time.LocalDate;

public class DataUtill {

    public static void main(String[] args) {
         int currentWeekDay = LocalDate.now().getDayOfWeek();
         int startOfWeekInterval = (currentWeekDay - 1) * -1;
         int endOfWeekInterval = 6 - currentWeekDay;
         if (endOfWeekInterval < 0) {
             endOfWeekInterval = 0;
         }
         Date fromDate = LocalDate.now().plusDays(startOfWeekInterval).toDate();
         Date thruDate = LocalDate.now().plusDays(endOfWeekInterval).toDate();

         System.out.println("Current Week From date:" + fromDate);
         System.out.println("Current Week To date:" + thruDate);

         Date preFromDate = LocalDate.now().minusWeeks(1).withDayOfWeek(1).toDate();
         Date preToDate = LocalDate.now().minusWeeks(1).withDayOfWeek(1).plusDays(6).toDate();

         System.out.println("Previous Week From date:" + preFromDate);
         System.out.println("Previuos Week To date:" + preToDate);

    }
}


OutPut.

Current Week From date:Mon Jan 09 00:00:00 IST 2017
Current Week To date:Sat Jan 14 00:00:00 IST 2017
Previous Week From date:Mon Jan 02 00:00:00 IST 2017

Previuos Week To date:Sun Jan 08 00:00:00 IST 2017

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>






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...