Tuesday, September 28, 2010
Liferay 6- Scheduler Engine design change
Posted by Parth Barot at 11:56 AM 3 comments
Labels: Articles, Design, Development, Liferay, Programming, Quartz
Tuesday, August 17, 2010
Liferay: Make Custom "Add Application" portlet ...
<portlet>
<portlet-name>87</portlet-name>
<icon>/html/icons/default.png</icon>
<struts-path>layout_configuration</struts-path>
<use-default-template>false</use-default-template>
<show-portlet-access-denied>false</show-portlet-access-denied>
<show-portlet-inactive>false</show-portlet-inactive>
<restore-current-view>false</restore-current-view>
<private-request-attributes>false</private-request-attributes>
<private-session-attributes>false</private-session-attributes>
<render-weight>50</render-weight>
<system>true</system>
</portlet>
<portlet>
<portlet-name>87</portlet-name>
<display-name>Layout Configuration</display-name>
<portlet-class>com.liferay.portlet.StrutsPortlet</portlet-class>
<init-param>
<name>view-action</name>
<value>/layout_configuration/view</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
</supports>
<resource-bundle>com.liferay.portlet.StrutsResourceBundle</resource-bundle>
</portlet>
<!-- Layout Configuration -->
<action path="/layout_configuration/templates" forward="portlet.layout_configuration.templates" />
<action path="/layout_configuration/view" forward="portlet.layout_configuration.view" />
<!-- Layout Configuration -->
<definition name="portlet.layout_configuration" extends="portlet">
<put name="portlet_decorate" value="false" />
</definition>
<definition name="portlet.layout_configuration.templates" path="/portlet/layout_configuration/templates.jsp" />
<definition name="portlet.layout_configuration.view" extends="portlet.layout_configuration">
<put name="portlet_content" value="/portlet/layout_configuration/view.jsp" />
</definition>
toggle: function(ppid) {
var instance = this;
var plid = themeDisplay.getPlid();
var doAsUserId = themeDisplay.getDoAsUserIdEncoded();
if (!instance.menu) {
var url = themeDisplay.getPathMain() + '/portal/render_portlet';
var popupWidth = 250;
var body = jQuery('body');
body.addClass('lfr-has-sidebar');
instance._dialog = Liferay.Popup(
{
width: popupWidth,
message: '<div class="loading-animation" />',
position: [5,5],
resizable: false,
title: Liferay.Language.get("add-application"),
onClose: function() {
instance.menu = null;
body.removeClass('lfr-has-sidebar');
}
}
);
jQuery.ajax(
{
url: url,
data: {
p_l_id: plid,
p_p_id: ppid,
p_p_state: 'exclusive',
doAsUserId: doAsUserId
},
success: function(message) {
instance._dialog.html(message);
instance._loadContent();
}
}
);
}
}
PortletCategory portletCategory = (PortletCategory)WebAppPool.get(String.valueOf(company.getCompanyId()), WebKeys.PORTLET_CATEGORY);
<init-param>
<name>includeCategories</name>
<value>myCategory,yours</value> <!-- Comma seperated category names, sub-categories will not be filtered...-->
</init-param>
Posted by Parth Barot at 5:16 PM 1 comments
Labels: Articles, Frameworks, hacks, Liferay, Portlet, Programming, Tutorials
Friday, July 30, 2010
Spring MVC portlet with annotations
<portlet>
<description xml:lang="en">Portlet Description</description>
<portlet-name>portlet-name</portlet-name>
<display-name xml:lang="en">Portlet Display Name</display-name>
<portlet-class>org.springframework.web.portlet.DispatcherPortlet</portlet-class>
<init-param>
<name>contextConfigLocation</name>
<value>/WEB-INF/appContext.xml</value>
</init-param>
<expiration-cache>0</expiration-cache>
<supports>
<mime-type>text/html</mime-type>
<portlet-mode>VIEW</portlet-mode>
</supports>
<portlet-info>
<title>Portlet Name</title>
<short-title>Portlet Name</short-title>
<keywords>Spring Portlet MVC</keywords>
</portlet-info>
</portlet>
@Controller
@RequestMapping
public class MyController {
private static final Logger _LOG = Logger.getLogger(MyController.class);
//Default render method will call this method...
@SuppressWarnings("unchecked")
@RequestMapping({"VIEW","/demoportlet/jsp2.do"})
public Object defaultRender(Model model, PortletRequest request,RenderResponse response) {
response.setContentType("text/html; charset=UTF-8");
String action = request.getParameter("action");
if("action1".equals(action)) {
...
return "demoportlet/jsp1";
} else {
...
return "demoportlet/jsp2";
}
}
// Direct request mapping based on action parameter value = 'someAction'
@RequestMapping(params = "action=someAction")
public Object actionOne(RenderRequest actionRequest, RenderResponse actionResponse) throws Exception {
actionResponse.setContentType("text/html; charset=UTF-8");
...
return "demoportlet/jsp2";
}
}
<servlet>
<servlet-name>view-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.ViewRendererServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>normal</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>normal</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>view-servlet</servlet-name>
<url-pattern>/WEB-INF/servlet/view</url-pattern>
</servlet-mapping>
<context-param>
<description>Spring Context XML location</description>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/spring/global.xml</param-value>
</context-param>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<context:annotation-config />
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="cookieName" value="lang"/>
<!-- in seconds. If set to -1, the cookie is not persisted (deleted when browser shuts down) -->
<property name="cookieMaxAge" value="100000"/>
</bean>
<bean id="localeChangeInterceptor"
class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="locale"/>
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor"/>
</list>
</property>
<property name="order" value="10" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
<context:component-scan base-package="com.spring.controller" />
</beans>
Posted by Parth Barot at 6:06 PM 3 comments
Labels: Articles, Development, Frameworks, Portlet, Programming, Spring, Tutorials
Wednesday, July 28, 2010
Display tag - Opensource JSP paging library...
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
<display:table name="lstObject" defaultsort="1" pagesize="20" sort="external" partialList="true"
size="totalCount" uid="lstObject" id="myObject"
export="false" requestURI="<%=someUrl%>" class="data">
<!-- For detailed understanding for each property, check the link http://displaytag.sourceforge.net/1.2/configuration.html -->
<display:setProperty name="paging.banner.placement" value="both" />
<display:setProperty name="paging.banner.group_size" value="10" />
<display:setProperty name="paging.banner.no_items_found">
<span class="lfloat">No {0} found.</span>
</display:setProperty>
<display:setProperty name="paging.banner.one_item_found">
<span class="lfloat">One {0} found.</span>
</display:setProperty>
<display:setProperty name="paging.banner.all_items_found">
<span class="lfloat">{0} {1} found, displaying all {2}.</span>
</display:setProperty>
<display:setProperty name="paging.banner.some_items_found">
<span class="lfloat">{0} {1} found, displaying {2} to {3}.</span>
</display:setProperty>
<display:setProperty name="paging.banner.full">
<div class="paging_footer">
<div class="rfloat">
<div class="lfloat" style="padding-top:6px;">[<a href="{1}">First</a> | <a href="{2}">Prev</a>]</div>
<div class="paging_wrap lfloat">
{0}
</div>
<div class="rfloat" style="padding-top:6px;">[<a href="{3}">Next</a> | <a href="{4}">Last</a>]</div>
</div>
</div><br>
</display:setProperty>
<display:setProperty name="paging.banner.first">
<div class="paging_footer">
<div class="rfloat">
<div class="lfloat" style="padding-top:6px;">[First | Prev]</div>
<div class="paging_wrap lfloat">
{0}
</div>
<div class="rfloat" style="padding-top:6px;">[<a href="{3}">Next</a> | <a href="{4}">Last</a>]</div>
</div>
</div><br>
</display:setProperty>
<display:setProperty name="paging.banner.last">
<div class="paging_footer">
<div class="rfloat">
<div class="lfloat" style="padding-top:6px;">[<a href="{1}">First</a> | <a href="{2}">Prev</a>]</div>
<div class="paging_wrap lfloat">
{0}
</div>
<div class="rfloat" style="padding-top:6px;">[Next | Last]</div>
</div>
</div><br>
</display:setProperty>
<display:setProperty name="paging.banner.onepage" value="" /> <!-- Because dont want to show any value if only one page...-->
<display:setProperty name="paging.banner.page.selected">
<div class="lfloat">
<a onclick="return false;" class="active" href="javascript:void(0);">{0}</a>
</div>
</display:setProperty>
<display:setProperty name="paging.banner.page.link">
<div class="lfloat">
<a href="{1}" title="Goto page {0}">{0}</a>
</div>
</display:setProperty>
<display:setProperty name="paging.banner.page.separator" value=" " /> <!-- Seperator between page numbers ,, i.e this will show "[First | Prev] 1 2 3 [Last | Next]"-->
<% MyObject myObject = (MyObject)pageContext.getAttribute("myObject"); %> <!-- Get the object from pageContext, which is writter in 'id' attribute -->
<display:column title="My title" class="first">
<!-- An y HTMl or jsp scriptlet can be used here... -->
</display:column>
<display:column property="name" title="2nd Column"/>
<display:column title="3rd Column"><%= myObject.getSomeValue() %></display:column>
...
</display:table> -
-
-
-
-
<display:table name="lstObject" defaultsort="1" pagesize="20" sort="external" partialList="true"
size="totalCount" uid="lstObject" id="myObject"
export="false" requestURI="<%=someUrl%>" class="data">
...
</display:table> <display:setProperty name="paging.banner.page.separator" value=" " />Posted by Parth Barot at 5:42 PM 2 comments
Labels: API, Articles, Development, Html, Open Source, paging, Programming, Tutorials
Wednesday, June 9, 2010
Liefray: Using JSONObject for Ajax in Plugin Portlet...
$.ajax({
type: 'POST',
url: getUrl(),
data: {},
success: function(returnData) {
$('#someElementId').html(returnData);
}
}); protected void getSomeDataAsJson(ResourceRequest request, ResourceResponse response)
throws PortletException, IOException {
String myParam = ParamUtil.getString(request, "myParam","");
// Some service call using params from request...
Obj obj = getDataFromSomeService(myParam);
JSONObject jsonObj = JSONFactoryUtil.createJSONObject();
// obj can be anything... Integer,Boolean,String or some custom POJO...
jsonObj.put("testData", obj);
OutputStream os = response.getPortletOutputStream();
try {
os.write(jsonObj.toString().getBytes());
}
finally {
os.close();
}
}
@Override
public void serveResource(ResourceRequest request, ResourceResponse response)
throws PortletException, IOException {
String cmd = ParamUtil.getString(request,Constants.CMD);
if ("getSomeDataAsJson".equals(cmd)) {
getSomeDataAsJson(request, response);
}
} $("input:button[@name='<portlet:namespace />SomeThing']").click (function() {
$('#<portlet:namespace />myDiv').text("");
//URL which goes to your portlet...
var url = "<portlet:resourceURL><portlet:param name='<%=Constants.CMD %>' value='getSomeDataAsJson' /></portlet:resourceURL>";
//Append your hidden input fields in the resourceURL...
url +="&"+$('input:hidden').serialize();
$.ajax({
url: url,
data: {},
dataType: 'json',
success: function(message) {
$('#<portlet:namespace />myDiv').text(message.testData);
}
}
);
}); Posted by Parth Barot at 3:32 PM 2 comments
Labels: API, Articles, Frameworks, Html, javascript, JQuery, Liferay, Open Source, Programming, struts, Tips, web
Friday, June 4, 2010
Javascript-ajax RSS feed reader - using jQuery with jGFeed ...
Check the new version of Ajax feed reader, which is using jQuery with jGFeed.
<html><head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type= "text/javascript" language='javascript'>
//<![CDATA[
(function($) {
$.extend( {
jGFeed : function(url, fnk, num, key) {
// Make sure url to get is defined
if (url == null) return false;
// Build Google Feed API URL
var gurl = "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+url;
if (num != null) gurl += "&num="+num;
if (key != null) gurl += "&key="+key;
// AJAX request the API
$.getJSON(gurl, function(data) {
if (typeof fnk == 'function')
fnk.call(this, data.responseData.feed);
else
return false;
});
}
});
})(jQuery);
var strArr = ['http://www.thinkdigit.com/forum/external.php?type=RSS','http://www.snapfiles.com/feeds/sf20fw.xml',
'http://www.download.com/3410-2001-0-10.xml','http://www.download.com/3412-2001-0-10.xml',
'http://www.download.com/3412-2003-0-25.xml','http://www.videohelp.com/rss/tools',
'http://www.videohelp.com/rss/forum','http://www.pcstats.com/rss/rss.xml','http://feeds.feedburner.com/Techdudes',
'http://feeds.feedburner.com/jQueryHowto'];
var isXml = true;
function loadXml() {
var index = Math.floor(Math.random()*strArr.length);
getJsonData(strArr[index],'targetDiv');
}
//loadXml();
function getJsonData(dataSource, divId) {
$.jGFeed(dataSource,
function(feeds) {
if (!feeds) {
alert('there was an error');
}
var html = "";
for (var i=0;i<feeds.entries.length;i++) {
var entry = feeds.entries[i];
var title = entry.title;
var link = entry.link;
var description = entry.contentSnippet;
var pubDate = entry.publishedDate;
html += "<div class='entry'><h4 class='postTitle'><a class='fancy block' href='" + link + "' target='_blank'>" + title + "</a></h4>";
// html += "<em class='date'>" + pubDate + "</em>";
var categories = " Lables : ";
if (entry.categories && entry.categories.length>0) {
categories += entry.categories[0];
for (var j=1;j<entry.categories.length;j++) {
categories +=", " +entry.categories[j];
}
html += "<p><b>"+categories+"</b></p>";
}
html += "<p class='description'>" + description + "</p></div>";
}
var btn = "<input type='button' value='Reload' onclick='getJsonData(\""+dataSource +"\",\""+divId+"\");' /></br>";
$('#'+divId).html(btn + html);
},
50);
}
function cleartDiv(divId) {
var obj = document.getElementById(divId);
if (obj) {
//obj.style.display = 'none';
obj.innerHTML="";
}
}
function getNewData(url,divId) {
if (url!=0) {
if (!url) {
var index = Math.floor(Math.random()*strArr.length);
getJsonData(strArr[index],divId);
} else {
getJsonData(url,divId);
}
}
}
//window.setInterval("getNewData()", 7000); // update the data every 20 mins
//]]>
</script>
</head>
<body onload="getNewData('http://www.videohelp.com/rss/tools','targetDiv');">
<select onchange="javascript:getNewData(this.options[this.selectedIndex].value,'targetDiv');" size="9" style="width:25%;">
<option value='0' selected="selected">Please Select</option>
<option value='http://www.thinkdigit.com/forum/external.php?type=RSS'>ThinkDigit.com</option>
<option value='http://www.snapfiles.com/feeds/sf20fw.xml'>SnapFiles.com</option>
<option value='http://www.articlecity.com/xml/main.xml'>ArticleCity.com</option>
<option value='http://www.download.com/3410-2001-0-10.xml'>Download.com populars</option>
<option value='http://www.download.com/3412-2001-0-10.xml'>Download.com New</option>
<option value='http://www.download.com/3412-2003-0-25.xml'>Download.com 25 New Titles</option>
<option value='http://feeds.feedburner.com/Techdudes'>TechDudes</option>
</select>
<div id="linkDiv" style="width:98%;height:25px;overflow:auto;"/>
<div id="targetDiv" style="border:dashed 1px;background:#fafafa;width:70%;height:450px;overflow:auto;font-family:verdana;font-size:10px;"/>
</body>
</html> jGFeed: http://plugins.jquery.com/project/jgfeed
Posted by Parth Barot at 2:55 PM 0 comments
Labels: API, Articles, Development, Frameworks, javascript, JQuery, Plugins, Tutorials
Wednesday, June 2, 2010
jQuery - usage of $.bind method...
<script type="text/javascript" src="html/js/jquery.js"></script>
<script type="text/javascript">
//on load, register events for checkboxes...
$(document).ready(
function() {
$('#chk_all').change(checkAll);
$('form[@name="fm"] input:checkbox[@name!="chk_all"]').each (function(index) {
$(this).change(selectForDelete);
});
}
);
function checkAll(){
var isCheck = this.checked;
$('form[@name="fm"] input:checkbox[@name!="chk_all"]').each(function(){
this.checked = isCheck;
$(this).trigger("change");
});
}
function selectForDelete(){
var alertIdsObj = $('form[@name="fm"] input[@name="deleteIds"]');
if (this.checked) {
if (alertIdsObj.val().indexOf(this.value)==-1) {
if(alertIdsObj.val()=='') {
alertIdsObj.val(''+this.value);
} else {
alertIdsObj.val(alertIdsObj.val()+","+this.value);
}
}
} else {
if (alertIdsObj.val().indexOf(this.value)>=0) {
alertIdsObj.val(alertIdsObj.val().replace(this.value+',',''));
alertIdsObj.val(alertIdsObj.val().replace(','+this.value,''));
alertIdsObj.val(alertIdsObj.val().replace(this.value,''));
}
}
}
//Function called for item details...
function viewAlertDetails(alertId) {
$.ajax({
type: 'POST',
url: getUrl()+"&alertId="+alertId+"&cmd=detailed-market-alerts",
data: {},
success: function(returnData) {
$('#-mainDiv').hide();
$('#-detailsDiv').html(returnData);
$('#-detailsDiv').show();
}
});
}
function getUrl() {
var url = new String(document.location);
var index = url.indexOf("?");
if (index!=-1) {
url = url.substring(0,index);
}
return url;
}
//function called from second page to go back to first page with latest data...
//Repalces the old content with new
function viewAlerts() {
$.ajax({
type: 'POST',
url: getUrl(),
data: {},
success: function(returnData) {
var myData = $(returnData).find('#-mainDiv').html();
$('#-mainDiv').html(myData);
$('#chk_all').bind('change', checkAll);
$('form[@name="fm"] input:checkbox[@name!="chk_all"]').each (function(index) {
$(this).bind('change',selectForDelete);
});
$('#-detailsDiv').html("");
$('#-detailsDiv').hide();
$('#-mainDiv').show();
return true;
}
});
return false;
}
</script> $('#chk_all').bind('change', checkAll);
$('form[@name="fm"] input:checkbox[@name!="chk_all"]').each (function(index) {
$(this).bind('change',selectForDelete);
}); Posted by Parth Barot at 2:50 PM 0 comments
Labels: API, Articles, Development, Frameworks, javascript, JQuery, Open Source, Programming, Tips, Tutorials
Thursday, May 27, 2010
Java Wildcards Vs. Generics...
I have never used wildcards in java until i read this.
Let's say I have a super class
List<Vehicle> lstVehicles;Instead, some people are recommending something like:
List<? extends Vehicle> lstVehicles;Why should I use wildcards instead of simple generics?
Because Java generics are invariant.
Suppose we have B extends A:
* B is a subtype of A
* an
Since Java arrays are covariant:
*
* an
However, Java generics are invariant:
*
* a
Wildcards are used to make it more flexible while preserving type safety.
*
References:
Wildcards
Generics
Generics and subtyping
More fun with wildcards
Posted by Parth Barot at 10:18 PM 0 comments
Labels: Articles, Programming, Tips, Tutorials, Wildcards
Friday, May 21, 2010
Java String manipulation: Appending empty string to 'var.subString(x,y)' saves memory...
In java usually we do SubString operation as follows.
String strMainData = "Some long String..." ;
String strSub= strMainData.subString(i,j); // Where i and j are index values...This operation will keep the reference to same object strMainData,but only returns smaller string as per the indexes. So it uses same memory as the original String.
We should use it as follows.
String strSub = new String(strMainData.subString(i,j));OR String strSub = strMainData.subString(i,j) +"";
This will only keep the reference to new smaller String and removes reference to original String variable.Posted by Parth Barot at 3:50 PM 0 comments
Labels: Articles, Development, Programming, Tips, Tutorials
Singleton refactored:Initialization on demand holder idiom...
public class Something {
private Something() {
}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}The static class LazyHolder is only executed when the static method getInstance is invoked on the class Something, and the first time this happens the JVM will load and initialize the LazyHolder class. The initialization of the LazyHolder class results in static variable INSTANCE being initialized by executing the (private) constructor for the outer class Something.
Posted by Parth Barot at 3:14 PM 0 comments
Labels: Articles, Development, Patterns, Programming, Tips
Thursday, May 20, 2010
AXIS2 web service client - without sub/proxy ...
//common interface for response handlers...
//implement this for diff. web service/methods
public interface WSRespHandler{
public Object getMeResp(Object respData);
}
//pass particular handler to client when you call some WS
public class WebServiceClient {
public Object getResp(WSRespHandler respHandler) {
...
return repHandler.getMeResp(xmlData);
}
}Posted by Parth Barot at 5:00 PM 0 comments
Labels: API, Articles, Development, Frameworks, Networking, Programming, Tutorials, Web Service, XML
Facebook integration in your web application...
This is not regarding only java, you can do this on any web application in different languages also.
Facebook is getting popular now a days. Almost every site has facebook login enabled, so that if the user has facebook account he can login using that and can use the site as a registered user. For this the user must allow the site to use his facebook user data (Friends list, profile details etc...). Facebook provides different set of APIs to do such integration with your site.
It basically provides different client APIs which are based on different technologies lke PHP, Java, Javascript etc.. Here i will show you how to integrate facebook only using javascript API, which is the best way to do this.
1. First step is, you have to include the javascript from FB as follows.
<script type="text/javascript"
src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"></script> 2. You have to init the Facebook JS library with you facebook API key and provide the XDReceiver url. XDReceiver.htm is provided by facebook which is to be uploaded on you server to handle the callback to Facebook's javascript functions. It will store facebook cookies on your server so that you can access the facebook session in your site to fetch facebook data for the logged in user.
FB.init("myApiKey","/html/xd_receiver.htm", {
"doNotUseCachedConnectState" : false
,"reloadIfSessionStateChanged" : true //Reloads the page if user logs in OR out
,"ifUserConnected" : showFacebookInviteLink() //Is user connects to FB, executes the provided JS function
}); 3. Now you need to call function which will provide the facebook login popup for user. User can login into facebook and then allows the application to use his/her data.
FB.Connect.requireSession(); // This will give the popup to login
// This will check if FB is initiated with application key and user logged in or not. On user session, it will executes the function.
FB.ensureInit(function() {
FB.Facebook.get_sessionState().waitUntilReady(
function() {
});
}); 4. To logout from Facebook, you just need to call JS function
Now you can access different functions of the FB JS library to acces any data it supports to use on your site/application having session initiated.I will show how to show invite friends popup dialog on your site/application. Call the below function on invite button/link click event.
function inviteFacebookFriends() {
FB.ensureInit(function() {
FB.Facebook.get_sessionState().waitUntilReady(
function() { //on Connect succes
var fbml = "";
fbml = '<fb:fbml>\n'
+ '<fb:request-form\n'
//Redirect back to this page
+ ' action="'+document.location+'"\n'
+ ' method="POST"\n'
+ ' invite="true"\n'
+ ' type="app test invite"\n'
+ ' content="app test inviting...\n'
+ '
+ ' label=\'Join me!\' />"\n'
+ '>\n'
+ ' <fb:multi-friend-selector\n'
+ ' rows="2"\n'
+ ' cols="4"\n'
+ ' bypass="Cancel"\n'
+ ' showborder="false"\n'
+ ' exclude_ids="excludeIds"\n'
+ ' actiontext="Use this form to invite your friends to connect to my site."/>\n'
+ ' </fb:request-form>' + ' </fb:fbml>';
var dialog = new FB.UI.FBMLPopupDialog("Invite Friends To This Site",fbml);
dialog.setContentWidth(650);
//dialog.setContentHeight(450);
dialog.show();
});
});
} Thats it! This will show the standard popup dialog for friends invitation. Basically this FBMl will be rendered by facebook js API.Now user can select any of his friends and send them invitation to join your site. Let me know if you have any queries OR problems, will try to help around.
Posted by Parth Barot at 1:43 PM 0 comments
Labels: API, Articles, Development, Facebook, javascript, Tutorials
Sunday, March 15, 2009
Telnet Client part 2 - using Apache net implementation...
Its a very simple class.You can download its source and can figure out what they have done. Though i will show simple usage for it.
TelnetClient tc = new TelnetClient();
tc.connect("localhost", 23); Then you can register a listener thread to get response from the telnet connection shown above. For full examples, check out java2sIts nothing new, but a good implementation what we understood so far.
If you want totally command prompt like session for telnet, then you must wait for response from execution of the given command.Then only the next command will be sent over, as we do in DOS/Terminal.So for that we must have a logic which check the input stream and receives response.
Posted by Parth Barot at 12:27 AM 0 comments
Labels: API, Articles, Development, Open Source, Programming, Tutorials
Saturday, December 20, 2008
Telnet client with java...
Through java, if we want to make remote connection over some port then we have two different ways.
1. Use windows/linux telnet command line utility (which is same on both win and linux... :).)
OR
2. Use socket programming using java.net package.
In first way, we need to get hands on the process.We can achieve that using
Process p = Runtime.getRuntime().exec(<system command or exe path>)But i don't think this should be used for telnet like communication,because telnet requires continuous session running on remote server and executing you commands.Sometimes it can be so that after executing several commands,you need to rollback so you can cancle all the commands.so its a continuous and sequential process most of the times.The Process class used can be out of our hands anytime if the executable crashes or if anything bad happen(Mostly..the exe crash...).So, we have another,'Socket' way here, which connects to perticular host on given port number and try to open TCP connection with it.If the host is listening on port and connection accepted,then we can send our commands to the host.(I know, i know, that we all know sockets since our starting graduation days :) ,but let me tell guys... ).
There are two ways to make a telnet client using Sockets.
1.Make it CLI based,means which accepts every input from Command Line Interface entered by user.
2.Make it automated,which takes command list from some file or database,generates a script or list of commands and run it whole on host.
First one is quite easy,i think you all might have done that :).Just let me tell you little what to do...
1.CLI based Telnet...
Socket soc = new Socket(host,port);
DataInputStream din=new DataInputStream(soc.getInputStream());
PrintWriter dout = new PrintWriter(soc.getOutputStream(),true);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));See,we have taken InputStream of socket and made a PrintWriter on the OutputStreamof it to send commands.Also we have taken BufferedReader for user inputs from CL....
....
do
{
char[] buffer = new char[8192];
int mark = bReader.read(buffer);
StringBuffer sb = null;
for(int i=0;i<buffer.length;i++){
char c = buffer[i];
if(c!='\0'){ //To avoid null characters printed...
if(sb == null){
sb = new StringBuffer(buffer.length);
}
sb.append(c);
}
}
System.out.print((sb!=null)?sb.toString():"-- No Response --");
Command=br.readLine(); //takes commands from CL by user...
if(!Command.equals("quit"))
{
dout.println(Command);
}
}while(!Command.equals("quit")); //exit the loop if user sends 'quit'...
...
This gives you same telnet as you got in your OS, so i think its simple but good to know :)
2.Automated Telnet...
It will be almost same,except we will have a ArrayList/Array of commands in hand before we create Socket.And then change the loop onto the list to execute all the commands one after another...
So this will executes all commands in commands Array of String.int j=-1;
String[] commands = new String[5];
...
....
do
{
j++;
char[] buffer = new char[8192];
int mark = bReader.read(buffer);
StringBuffer sb = null;
for(int i=0;i<buffer.length;i++){
char c = buffer[i];
if(c!='\0'){//To avoid null characters printed...
if(sb == null){
sb = new StringBuffer(buffer.length);
}
sb.append(c);
}
}
System.out.print((sb!=null)?sb.toString():"-- No Response --");
Command = commands[j];
if(Command==null || Command.length()<0)
break;
dout.println(Command+"\n");
}while(j<commands.length);
...
So folks,this ends our telnet socket :).Same like this we can make client or scripts for FTP automation.It helps in real time situation when you need to make some jobs for backup,export/import files on remote host etc...Waiting for you responses...
Posted by Parth Barot at 1:20 PM 3 comments
Labels: Articles, Development, Networking, Programming, Tips, Tutorials
Wednesday, December 17, 2008
Snmp4J - Java library for SNMP Communication...
We can query any device (Switch,PC etc...) if it has a SNMP agent running,which will handle our SNMP request and respond with the proper data.This library made it so easy for us without looking into much details of SNMP.
In basic,SNMP is used for getting information (GET requests),but sometimes it can be used to set values in the device (SET requests).Assume that every device has a list of pre-defined variables in it,which are called OID(Object IDs).These OIDs will have a specific structure (which is called MIB file,which seems like a tree structured as in registry).
OID looks like 1.3.6.1.4.1.318.1.1.1.12.3.2.1.3.1, which has a special meaning.It has a description(name) and an associated value in it.When you query particular OID (i.e 1.3.6.1....),it will give its associated value.You can set its value also (if its allowed ;)).OIDs also have communities(Public,Private etc...) which shows permissions.Mostly public community is allowed to be viewed by SNMP requests.
See the example below how to make a SNMP request,
import org.snmp4j.*;So the last line, snmp.send(pdu, target), will return the SNMP4j Response having the value for OID we set in the PDU.This is just the example of how to get any data from OID.We can set the values using SET PDU.
...
...
OctetString communityName = new OctetString("public");
String ipAddressUrl = strIpAddress+"/"+161; //161 is used for SNMP Agent...
Address targetAddress = new UdpAddress(ipAddressUrl);
TransportMapping transport = new DefaultUdpTransportMapping();
Snmp snmp = new Snmp(transport);
snmp.listen();
CommunityTarget target = new CommunityTarget();
target.setAddress(targetAddress);
target.setRetries(3);
target.setTimeout(500);
PDU pdu = new PDU();
pdu.setType(PDU.GET);
OID oid = new OID("1.3.6.1.2.1.1.");
VariableBinding vb = new VariableBinding(oid);
pdu.add(vb);
...
...
snmp.send(pdu, target);
Posted by Parth Barot at 10:53 PM 0 comments
Labels: API, Articles, Development, Freeware, Networking, Programming, Tips, Tutorials
Monday, July 14, 2008
Remote Method call - EJB/HTTPClient/Web Service?
This was a need in my project to call a method of another application which can be on same machine or another. First i thought i need to call a EJB and its all mess because of heavy loads for a simple method call. But when i saw the implementation, i got confused how i will cuse it! But my senior told me to check using HTTPClient from apache commons.
Its very simple to call a method on servlet using HTTPClient. Check the code below. We will just use PostMethod class for parameters to be passed and execute the request. So as per the parameters,the servlet will do its work.
PostMethod postMethod = new PostMethod("http://some.blah.com");Its so simple. But though its not a call which returns something. I mean you cna see i am just passign some information to some method to invoke some processing which is independent and i don't need its response.
postMethod.setParameter("some_id", "1");
postMethod.setParameter("param1", "any data");
postMethod.setParameter("param2", "any data");
...
int status = httpClient.executeMethod(postMethod); //status will be your response...
Posted by Parth Barot at 10:58 AM 0 comments
Labels: API, Articles, Development, Frameworks, Open Source, Programming, Tips, Tutorials, web
Tuesday, May 20, 2008
Controlling Module Dependencies in Eclipse
Let’s figure it out with Eclipse Web Tools Platform. I consider that you all have ability to create projects and modules in Eclipse; so skipping those steps. I have Eclipse 3.3 with WTP 2.0 M6.
I have created project with following details.
MyProject –
MyEJB_Module – Contains bean class
MyEJBClient_Module – Contains interfaces of EJB, VO, and BeanUtil.
MyWeb_Modules – Holds JSPs, servlets and all presentation tier stuffs.
MyJava_Module – Contains common classeslike constants, utilities.
Starting with MyProject, select properties from right click menu. In property dialog, select “J2EE Module Dependencies”. You will find all the modules. Select all as project is dependent on all modules.
Now you can configure dependency of individual module, let’s take an example of web module. In “J2EE Module Dependencies” window, you will find a radio button group which would has by default “Use EJB Client Jars” option selected. That radio button groups defines visibility of EJB jar.
As clients of any EJB should be isolated from bean classes, it is preferable not to select other options where you can define dependencies with EJB jar file. After all, EJB clients should not have any kind of dependencies with EJB jar.
Now here if I select MyEJB_ModuleClient.jar only, MyWeb_Module won’t able to access classes defined in MyJava_Module until you redefine module dependencies.
Similarity you can define dependencies with Utility project, specifically saying third party libraries. You want one module to access one jar and isolate others all you need to do is add library in main project (MyProject in my case) and then configure dependencies of other modules.
This feature takes care of dependencies on behalf of you and let you concentrate on other tasks.
Posted by Jay Rajani at 12:42 PM 0 comments
Labels: Articles, Configuration, Development, Eclipse, Open Source, Programming, Tips, Tools, Tutorials
Thursday, May 15, 2008
Servicemix PollingComponentSupport - stuck if lower period and higher threadPoolSize
We have two FilePoller components here and we kept the period to 10 minutes. Which means the instance of FilePoller will run at every 10 minutes. Now say if I have two instances, each run at 10 minutes, and 5 minutes gap between them. So it means after every five minutes, files will be picked by one of them. And the WorkManager, which is given to FilePoller as property, has threadPoolSize of 30.
All was working fine with this configuration.30 threads in pool, every five minutes any of two pullers will pick files. But now we have to change it. When we changed the period from 10 minutes to 1 minute, we got strange errors. Yes even you won't believe it. While testing concurrency we got, FileNotFound exception even though the file exists there, and many other concurrency issues. We looked into the logs and found that sometimes the load goes only on one server and the other is always idle doing nothing. Because when it comes, the first one is doing task.
Then we decided to decrease the thredPoolSize. Becasue if puller get 30 files for 30 threads from the pool, and when it comes to 31st file from the folder and if any of previous 30 threads is in the pool after it has completed its job, then it will take the file. It means, though we have pool size of 30, it may be possible that it can process more than 30 files per instance (say 32 to 38 files). So we decided to make pool size to 10.
Now after making 10 it seems to be working fine. Each one is picking almost equal numbers of files and sharing load as it should. Let’s see if more issues are coming or not.
So, key thing to be remembered is
"Keep you threadPoolSize and period on which instance will run in proportion to each other. If period is long then threads can be more but if you want to reduce the period, you must take care of pool size."
Posted by Parth Barot at 3:35 PM 0 comments
Labels: Articles, Development, Frameworks, Open Source, Programming, Spring, Tips, Tutorials
Tuesday, May 13, 2008
Java optimization and performance
Many of us do this when we want to throw an error. But if you are throwing exception from another catch, then don't make new exception object. Keep throwing the same exception which you caught if possible. This will be better for performance. And also in new exception usually we change the description only to reflect the perfect error cause, but other ways are there to track it.
Avoid excessive synchronization
Yah threading can be a bit complex situation sometimes in java. And we all use synchronization to avoid dead locks. But it needs a more attention then we give it. Try to make a block of code synchronized rather then making the whole method synched. The whole method will stop all other threads, waiting to go inside it. It will generate more overhead. So keep the design like we need less sync code.
Release DB and File IO
This is the most case in which we all do something wrong.
DB connections must be closed after completing your DB transactions because its a limited resource.
Also if you are using File IO, then must close file streams after completing the task.
Best way for this is, to write the releasing code in 'finally' block of the method.
Use StringBuffer/StringBuilder rather than String
We use string manipulations in our daily coding many times. And all we do is always making new String object. As most of us know, String is immutable object (which means once assigned you can't change its value), so when you assign existing String object another value, it will make new String object. And most string operation generates lot of small String objects.
If it’s possible to use StringBuffer or StringBuilder instead of String then its more more way better. Because it will be one object having all your data in it and you can get String form it when you want.
Now StringBuilder is nonSynchronized and StringBuffer is synchronized. So if you don't have threading issues and don't need Sync, then you must use StringBuilder which is included since jdk 1.5.
Later on we will talk about more points also when i remember them :)
Posted by Parth Barot at 11:47 AM 0 comments
Labels: Articles, Development, Programming, Tips, Tutorials
Friday, May 9, 2008
servicemix problems: NormalizedMessage getContent,copyPropertiesAndAttachments()
While creating and sending
NormalizedMessage object from any data, after doing that if you read data using NormalizedMessage.getContent() method and send the message object with exhchange to deliveryChannel, using DeliveryChannelImpl.send(MessageExchange) method, then you will get null exception in DeliveryChannelImpl class.Yes this is true.I don't know why, but it removes content from the message object.Only the content is removed and the properties are still there.
You can read properties from it in same component as many times as you want.If you are forwarding same message to next component, properties will automatically goes.But if you read content once, you must set it again :(.
Also remember that if you need to make new
MessageExchange, then you must copy all properties and attachments using TransformComponentSupport.copyPropertiesAndAttachments(outExchange,inMsg,outMsg) method.Then all your data from one message will be copied to another message.So keep checking this if you getting null Exceptions while sending message through
DeliveryChannel.Posted by Parth Barot at 5:07 PM 0 comments
Labels: Articles, Development, Frameworks, Freeware, Open Source, Programming, Spring, Tips, Tutorials
