Wednesday, 27 November 2013

Use of Java for Inserting data to MongoDB


Example for MongoDB  : Use of Java for Inserting data to MongoDB.

MongoClient mongoClient = null ;
try {
mongoClient = new MongoClient( "localhost" , 27017 );
} catch (UnknownHostException e) {
e.printStackTrace();
}

DB db = mongoClient.getDB( "mongoDB" );
DBCollection documents = db.getCollection("Documents");
BasicDBObject document = new BasicDBObject();
document.put("Id", 12345);
document.put("Name", "abcdhijk");
document.put("Age", 25);
try {
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").parse("1984-05-08T8:30:00.000Z");
document.put("DateOfBirth", date);
} catch (ParseException e) {
e.printStackTrace();
}

String [] interests = {"Reading", "Politics", "Basketball"};
document.put("Interests", interests);

documents.insert(document);



The output on the mongo shell is like :
connect MongoDB using "mongo" command
> show dbs

local 0.078125GB
mongoDB 0.203125GB

> use mongoDB
switched to db mongoDB

> show collections
Documents
system.indexes

> db.Documents.find();
{ "_id" : ObjectId("5296db7e91098e64f3c4faa8"), "Id" : 12345, "Name" : "abcdhijk", "Age" : 25, "DateOfBirth" : ISODate("1984-05-08T03:00:00Z"), "Interests" : [ "Reading", "Politics", "Basketball" ] }

> db.Documents.find().pretty();
{
"_id" : ObjectId("5296db7e91098e64f3c4faa8"),
"Id" : 12345,
"Name" : "abcdhijk",
"Age" : 25,
"DateOfBirth" : ISODate("1984-05-08T03:00:00Z"),
"Interests" : [
"Reading",
"Politics",
"Basketball"
]
}



Friday, 8 November 2013

Solr 4.5.1 set up issues with Tomcat

I tried installing Solr 4.5.1

I faced couple of issues while setting up the environment.

The first issue is I was not able access the as it was throwing an error
SEVERE: Error filterStart....

when I checked for more information I got this ....
SEVERE: Exception starting filter SolrRequestFilter

This is occurring because org.apache.solr.common.SolrException: Could not find necessary SLF4j logging jars. Need to add the jars on the containers.


Add the jars in the tomcat
1. slf4j-log4j12-1.6.6.jar
2. slf4j-api-1.6.6.jar
3. log4j-1.2.16.jar
4. jcl-over-slf4j-1.6.6.jar

The above issue got resolved after adding the jars.

The second issue is "msg=SolrCore 'collection1' is not available due to init failure: Unable to use updateLog: _version_field must exist in schema".

To resolve the above issue ...need to Add below in the <fields> tag in schema.xml

<field name="_version_" type="long" indexed="true" stored="true"/>


Saturday, 31 August 2013

Split a large array into smaller arrays...


Split a large array into smaller arrays...

import java.util.Arrays;


public class Test {
public static void main(String[] args) {
int[] original = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
int sizeOfNewArray = 5;
int quotient = original.length / sizeOfNewArray;
boolean isRemainder = original.length % sizeOfNewArray == 0;
if(!isRemainder){
quotient ++;
}
int startPoint = 0;
for (int i = 0 ; i < quotient ; i ++ ) {
int arrayLength = ((startPoint + sizeOfNewArray) > original.length) ? original.length : (startPoint + sizeOfNewArray) ;
int[] smallerArray = Arrays.copyOfRange(original, startPoint, arrayLength);
for (int j : smallerArray) {
System.out.println("Array " + i + " ::" + j);
}
startPoint = startPoint + sizeOfNewArray ;
}
}
}

*Here in the example "original" array size is smaller. 

Wednesday, 24 April 2013

Panel which dynamically opens and closes in Wicket




Panel which dynamically opens and closes in Wicket

import java.text.MessageFormat;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.util.value.IValueMap;

public class CustomPanel extends Panel {
  private static final String SHOW_ALL_SCRIPT = "jQuery('a.panel-open').click()";

  private static final String HIDE_ALL_SCRIPT = "jQuery('a.panel-close').click()";

  public CustomPanel(final String id, final Component component) {
    this(id, component, new Model<Boolean>(true));
  }

  public CustomPanel(final String id, final Component component, final IModel<Boolean> open) {
    super(id, open);
    component.setOutputMarkupId(true);

    final WebMarkupContainer link = new WebMarkupContainer("link") {
      private static final String SCRIPT = "var panel = jQuery(''#{0}'');"
          + "var link = jQuery(this); var span = link.children();"
          + "link.toggleClass(''panel-close'').toggleClass(''panel-open'');"
          + "if (panel.css(''display'') == ''none'') "
          + "'{' panel.show(); span.text(''{1}''); link.attr(''title'', ''{3}''); '}'" + "else "
          + "'{' panel.hide(); span.text(''{2}''); link.attr(''title'', ''{4}''); '}'" + "return false;";

      @Override
      protected void onComponentTag(final ComponentTag tag) {
        super.onComponentTag(tag);
        if (!tag.isClose()) {
          final IValueMap attributes = tag.getAttributes();

          final Boolean isPanelOpen = getModel().getObject();
          if (isPanelOpen != null && isPanelOpen) {
            attributes.put("class", "panel-close");
            attributes.put("title", getCloseText());
          } else {
            attributes.put("class", "panel-open");
            attributes.put("title", getOpenText());
          }
          attributes.put("onclick", MessageFormat.format(SCRIPT, component.getMarkupId(), getCloseText(),
              getOpenText(), getClosePanelText(), getOpenPanelText()));
        }
      }

    };
    add(link);
    link.add(new Label("text", new AbstractReadOnlyModel<String>() {
      private static final long serialVersionUID = 1045024635866272771L;

      @Override
      public String getObject() {
        final Boolean isPanelOpen = getModel().getObject();
        if (isPanelOpen != null && isPanelOpen) {
          return getCloseText();
        } else {
          return getOpenText();
        }
      }
    }));
  }

  @Override
  protected void onComponentTagBody(final MarkupStream markupStream, final ComponentTag openTag) {
    renderComponentTagBody(markupStream, openTag);
    super.onComponentTagBody(markupStream, openTag);
    // Render the body of the link

  }

  @SuppressWarnings("unchecked")
  protected IModel<Boolean> getModel() {
    return (IModel<Boolean>) getDefaultModel();
  }

  private String getCloseText() {
    return getString("close");
  }

  private String getOpenText() {
    return getString("open");
  }

  private String getClosePanelText() {
    return getString("closePanel");
  }

  private String getOpenPanelText() {
    return getString("openPanel");
  }

  public static AttributeAppender getShowAllBehavior() {
    return new AttributeAppender("onclick", true, new Model<String>(SHOW_ALL_SCRIPT), " ");
  }

  public static AttributeAppender getHideAllBehavior() {
    return new AttributeAppender("onclick", true, new Model<String>(HIDE_ALL_SCRIPT), " ");
  }

}


CustomPanel.html

<wicket:panel xmlns:wicket="http://wicket.apache.org/dtds.data/wicket-xhtml1.4-strict.dtd">
<a wicket:id="link" href="#">
<span wicket:id="text"></span>
</a>

</wicket:panel>

Friday, 30 November 2012

JavaScript Calculator


JavaScript Calculator
  • Calculator should have 0 to 9 digits , clear , backspace , . , and = buttons.
  • Operators buttons are : + , - , / , *.
  • Layout should be div based. No tables should be used.
  • It should perform all valid calculations.
  • Use CSS to design buttons & not images or html button element.
  • Button should change in given states ( i. e. normal , disabled, hover and clicked ). Use CSS effect for each state

style.css
body{
overflow: scroll;
}
INPUT{
padding: 2px;
margin: 10px 0px 0px 5px;
}
.calci{
background-color: #aaa;
width: 200px;
height: 250px;
border: 5px !important;
border-color: #000 !important;
}
.btn{
background-color: #ccc;
margin: 1px;
padding: 2px;
min-width: 30px;
text-align: center;
float: left;
border: 2px !important; 
border-color: black;
border-style: solid;
}
.btn:HOVER {
background-color: #cdd;
cursor: pointer;
}

Index.html


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<script type="text/javascript" src="js/Calculations.js"></script>
</head>
<body onload="loadComponents()">
<noscript>
Javascript not enabled
</noscript>

<div class="calci" >
<div style="margin-left: 10px">
<div>
<input id="text_input" value="" type="text" readonly="readonly" style="left:0px"/>
</div><br>
<div style="width: 100%">
<div id="clear_btn" class="btn" > Clear </div>
<div id="del_btn" class="btn">Backspace</div>
</div>
<br><br>
<div style="width: 100%">
<div id="btn_one" class="btn"> 1 </div>
<div id="btn_two" class="btn">2</div>
<div id="btn_three" class="btn">3</div>
<div id="btn_div" class="btn">/</div>
</div>
<br><br>
<div style="width: 100%">
<div id="btn_four" class="btn"> 4 </div>
<div id="btn_five" class="btn">5</div>
<div id="btn_six" class="btn">6</div>
<div id="btn_mul" class="btn">*</div>
</div>
<br><br>
<div style="width: 100%">
<div id="btn_seven" class="btn">7</div>
<div id="btn_eight" class="btn">8</div>
<div id="btn_nine" class="btn">9</div>
<div id="btn_sub" class="btn">-</div>
</div>
<br><br>
<div style="width: 100%">
<div id="btn_dot" class="btn">.</div>
<div id="btn_zero" class="btn">0</div>
<div id="btn_eq" class="btn">=</div>
<div id="btn_plus" class="btn">+</div>
</div>
</div>
</div>

</body>
</html>

Calculations.js

function numberClicked(num){
if(newNumberFlag == true){
document.getElementById("text_input").value = num;
newNumberFlag = false;
}else {
var value = document.getElementById("text_input").value;
value += num;
document.getElementById("text_input").value = value;
}
}
function oneClicked(){
numberClicked(1);
}

function twoClicked(){
numberClicked(2);
}
function threeClicked(){
numberClicked(3);
}
function fourClicked(){
numberClicked(4);
}
function fiveClicked(){
numberClicked(5);
}
function sixClicked(){
numberClicked(6);
}
function operatorClicked(op){
operator = op;
newNumberFlag = true;
result = parseFloat(document.getElementById("text_input").value);
}
function sevenClicked(){
numberClicked(7);
}
function eightClicked(){
numberClicked(8);
}
function nineClicked(){
numberClicked(9);
}
function zeroClicked(){
numberClicked(0);
}

function dotClicked(){
var value = document.getElementById("text_input").value;
if(value == null || value == undefined || value == "" ){
value = "0.";
}else if(value.indexOf(".")!= -1){
return;
}else {
value += ".";
}
document.getElementById("text_input").value = value;
}
function loadComponents(){
clear();
var clearBtn=document.getElementById("clear_btn");
clearBtn.onclick = clear;
document.getElementById("del_btn").onclick = backspaceClicked;
document.getElementById("btn_one").onclick = oneClicked;
document.getElementById("btn_two").onclick = twoClicked;
document.getElementById("btn_three").onclick = threeClicked;
document.getElementById("btn_four").onclick = fourClicked;
document.getElementById("btn_five").onclick = fiveClicked;
document.getElementById("btn_six").onclick = sixClicked;
document.getElementById("btn_seven").onclick = sevenClicked;
document.getElementById("btn_eight").onclick = eightClicked;
document.getElementById("btn_nine").onclick = nineClicked;
document.getElementById("btn_zero").onclick = zeroClicked;
document.getElementById("btn_dot").onclick = dotClicked;
document.getElementById("btn_plus").onclick = function(){
operatorClicked("+");
};
document.getElementById("btn_sub").onclick = function(){
operatorClicked("-");
};
document.getElementById("btn_div").onclick = function(){
operatorClicked("/");
};
document.getElementById("btn_mul").onclick = function(){
operatorClicked("*");
};
document.getElementById("btn_eq").onclick = calculate;
}

function clear(){
document.getElementById("text_input").value="";
result = 0;
operator = "";
// num1 = "";
newNumberFlag = true;
}
function backspaceClicked (){
var value = document.getElementById("text_input").value;
if(null != value && value != undefined && value != ""){
var origLen = value.length , newValue;
newValue = value.substring(0,origLen-1);
document.getElementById("text_input").value = newValue;
}
}

function calculate(){
var num2 = parseFloat(document.getElementById("text_input").value);
if(result == 0 || operator == ""){
result = num2;
}else {
if(operator == "+"){
result = result + num2;
}else if(operator == "-"){
result = result - num2;
}else if(operator == "/"){
result = result / num2;
}else if(operator == "*"){
result = result * num2;
}
}
document.getElementById("text_input").value = result;
}


Thursday, 11 October 2012

Component Frameworks


Welcome to the world of components!!!

Today, we are heading towards the component world. Everything we get in terms of component.Rather we are building everything as a component. Why I am saying this is because the kind of frameworks I came across.

I started my carrier with Struts framework. This is most popular MVC framework of that time. As it is today as well.But there were very few other frameworks competing with Struts.

At that time i didn't heard anything in terms of component.But later on I moved to other organizations and  started working on JSF.At that time JSF was the emerging framework. It was known as the component framework for fast web application development.It also had in built support for Ajax.

After that I came across another framework Apache Wicket. This is another frame that I learnt. This framework was quite different from JSF. As a Java developer u need not have to write anything on the HTML side or in JSP. There is a VERY nice separation of presentation and logic. Here HTML will remain as HTML. I enjoyed working on this framework.

Currently I am using the ExtJS which is another JavaScript framework which is also a component framework.

Yesterday I read about some other framework like "Vaadin", "KendoUI".These are the other emerging component based framework.There are many more in the market which are known as component framework. By using which u can fasten the development and it eases the maintenance of software.

I m not comparing these frameworks here. Just wanted share and highlight that the Technology world is moving fast and everything in coming to us in terms of "Component"...

Wednesday, 26 September 2012

MultiKeyMap

It uses multiple keys to store the value.

This MultiKeyMap is not synchronized and is not thread-safe.

Add the jar "commons-collections-3.2.1.jar".

Example is :


MultiKeyMap multiKeyMap = new MultiKeyMap();
multiKeyMap.put("DocumentName","DocumentRef","DocumentAuthor");
multiKeyMap.put("DocumentName1","DocumentRef1","DocumentAuthor1");
multiKeyMap.put("DocumentName2","DocumentRef2","DocumentAuthor2");
multiKeyMap.put("DocumentName3","DocumentRef3","DocumentAuthor3");

// later retireve the value
System.out.println(multiKeyMap.get("DocumentName","DocumentRef"));  
System.out.println(multiKeyMap.get("DocumentName1","DocumentRef1"));
System.out.println(multiKeyMap.get("DocumentName2","DocumentRef2"));
System.out.println(multiKeyMap.get("DocumentName3","DocumentRef3"));

the output is :


DocumentAuthor
DocumentAuthor1
DocumentAuthor2
DocumentAuthor3