Ariel's Blog Stuff that I like

5Aug/120

“Curiosity” Rover, almost on Mars


The most sophisticated rover ever sent to Mars is slated to land in less than 15 hours.  The car-sized 900 kg robotic machinery will attempt a dangerous but, nevertheless, trial blazing landing sequence.

This project follows the successful twin rovers Spirit and Opportunity, launched in 2003, that were first designed for a 3 months mission. Surprisingly, Spirit lasted more than 5 years, ending up stuck in soft soil, while its twin, Opportunity, is still roaming the planes of Meridiani Planum, an equatorial region of Mars.

The success of the MER (Mars Exploration Rovers), meant that exploration of the Red Planet using robotic rovers is not Sci-Fi anymore. This is way, to answer more specific questions related to Mars' past habitability, the MSL (Mars Science Laboratory) is a complex mix of hardware and software that should be able to achieve the following goals:

  • determine if the Red Planet could ever have supported life
  • study the climate
  • study the geology
  • plan for future human missions.

Because more instruments are needed, the size of the vehicle is much grater than the previous ones. The previous missions used airbags to perform the touchdown on the surface. To be able to land a more massive and heavy load, mission designers will employ a sky-crane. This time, Curiosity will land on its wheels, being lowered by a 7.6 meter tether, a system that has never been used before.

The rover is expected to last at least 2 years.

Although very far away and with a one-way ticket to a hostile place, "Curiosity" makes you think, at least for a moment, that there are countless secrets to be discovered outside of this world.

Below there's a short movie detailing the landing procedure.

Later Edit:
The rover successfully touched down on Mars, sending its first pictures:

Filed under: Uncategorized No Comments
30Jan/1113

Database-backed authentication in Spring Security

This is a short and (hopefully) comprehensive guide to building a way to authenticate and authorize users into a website. This is done using Spring Security. It builds up on the examples provided in the Spring Security latest release which can be downloaded from here .

Starting from the XML files:

Web.xml

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
        	/WEB-INF/dispatcher-servlet.xml
        	/WEB-INF/applicationContext-security.xml
        </param-value>
  </context-param>

applicationContext-security.xml

<?xml version="1.0" encoding="UTF-8"?>

<!--
  - Sample namespace-based configuration
  -
  -->

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <global-method-security pre-post-annotations="enabled">
        <!-- AspectJ pointcut expression that locates our "post" method and applies security that way
        <protect-pointcut expression="execution(* bigbank.*Service.post*(..))" access="ROLE_TELLER"/>
        -->
    </global-method-security>

    <http use-expressions="true">
        <intercept-url pattern="/secure/extreme/**" access="hasRole('ROLE_SUPERVISOR')"/>
        <intercept-url pattern="/secure/**" access="isAuthenticated()" />
        <!-- Disable web URI authorization, as we're using <global-method-security> and have @Secured the services layer instead
        <intercept-url pattern="/listAccounts.html" access="isRememberMe()" />
        <intercept-url pattern="/post.html" access="hasRole('ROLE_TELLER')" />
        -->
        <intercept-url pattern="/**" access="permitAll" />
        <form-login />
        <logout />
        <remember-me />
<!--
    Uncomment to enable X509 client authentication support
        <x509 />
-->
        <!-- Uncomment to limit the number of sessions a user can have -->
        <session-management invalid-session-url="/timeout.jsp">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
        </session-management>

    </http>

    <!-- hibernate DAO for authentication with sessionFactory dependency from dispatcher-servlet.xml defined in the web.xml -->
	<beans:bean id="userDAO" class="com.arielsweb.security.UserLoginDAOImpl">
		<beans:property name="sessionFactory" ref="sesFactory"></beans:property>
	</beans:bean>

	<beans:bean id="userService" class="com.arielsweb.security.UserLoginService">
		<beans:property name="userDAO" ref="userDAO"></beans:property>
    </beans:bean> 
    
    <authentication-manager>
         <authentication-provider user-service-ref="userService">
         	<password-encoder hash="sha" />
         </authentication-provider>    	 
    </authentication-manager>

</beans:beans>

UserLoginDAO.java

package com.arielsweb.security;

import java.util.List;

/**
 * The Interface UserLoginDAO.
 */
public interface UserLoginDAO {

	/**
	 * Load user by name.
	 *
	 * @param name the name
	 * @return the user
	 */
	User loadUserByName(String name);
}

UserLoginDAOImpl.java

package com.arielsweb.security;

import java.util.List;
import java.util.Set;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

/**
 * The Class UserLoginDAOImpl
 */
public class UserLoginDAOImpl implements UserLoginDAO {

	/** The hibernate template. */
	private HibernateTemplate hibernateTemplate;

	/**
	 * Sets the session factory.
	 * 
	 * @param sessionFactory
	 *            the new session factory
	 */
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Override
	public User loadUserByName(String name) {
		if (name != null && !name.equals("")) {
			List<User> usr = hibernateTemplate
					.find("from User where username ='" + name + "'");

			if (usr.size() == 1) {
				return usr.get(0);
			} else {
				return null;
			}
		} else {
			return null;
		}
	}
}

UserLoginService.java

package com.arielsweb.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * The Class UserLoginService
 */
public class UserLoginService implements UserDetailsService {

	/** The user dao. */
	private UserLoginDAO userDao;

	/**
	 * Sets the user dao.
	 *
	 * @param u the new user dao
	 */
	public void setUserDAO(UserLoginDAO u) {
		userDao = u;
	}

	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	public UserDetails loadUserByUsername(String username) {
		if (username != null && !username.equals("")) {
			User user = userDao.loadUserByName(username);
			if (user == null) {
				return null;
			}
	
			GrantedAuthority grantedAuth = new UserGrantedAuthority(user.getRole());
			CustomUser cu = new CustomUser(user.getId(), user.getUsername(), user.getPassword(),
										   new GrantedAuthority[]{ grantedAuth });
			return cu;
		} else {
			return null;
		}
	}

}

And the classes referenced inside the service:
User.java

package com.arielsweb.security;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {

	private Integer id;
	private String username;
	private String password;
	private Boolean enabled;
	private String role;
	private String email;

	public User() {
	}

	public User(String username, String password, Boolean isEnabled, String role, String email) {
		super();
		this.username = username;
		this.password = password;
		this.enabled = isEnabled;
		this.role = role;
		this.email = email;
	}

	@Id
	@GeneratedValue
	/**
	 * @return the id
	 */
	public Integer getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(Integer id) {
		this.id = id;
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return username;
	}

	/**
	 * @param username the username to set
	 */
	public void setUsername(String username) {
		this.username = username;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		this.password = password;
	}

	/**
	 * @return the isEnabled
	 */
	public Boolean getEnabled() {
		return enabled;
	}

	/**
	 * @param isEnabled the isEnabled to set
	 */
	public void setEnabled(Boolean isEnabled) {
		this.enabled = isEnabled;
	}

	/**
	 * @return the roles
	 */
	public String getRole() {
		return role;
	}

	/**
	 * @param roles the roles to set
	 */
	public void setRole(String roles) {
		this.role = roles;
	}
	
	/**
	 * @return the emailAddress
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * @param emailAddress the emailAddress to set
	 */
	public void setEmail(String emailAddress) {
		this.email = emailAddress;
	}
}

UserGrantedAuthority.java

package com.arielsweb.security;

import org.springframework.security.core.GrantedAuthority;

/**
 * The Class UserGrantedAuthority
 */
public class UserGrantedAuthority implements GrantedAuthority {

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = -3786297951121082647L;
	
	/** The authority. */
	private String authority = null;

	/**
	 * Instantiates a new user granted authority.
	 *
	 * @param auth the auth
	 */
	public UserGrantedAuthority(String auth) {
		authority = auth;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.core.GrantedAuthority#getAuthority()
	 */
	@Override
	public String getAuthority() {
		return authority;
	}

}

CustomUser.java

package com.arielsweb.security;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

public class CustomUser implements Serializable, UserDetails {

	private static final long serialVersionUID = 1201392234549297485L;
	private long id;
	private String password;
	private String username;
	private GrantedAuthority[] authorities = null;

	/**
	 * Instantiates a new custom user.
	 *
	 * @param id the id
	 * @param username the username
	 * @param password the password
	 * @param authorities the authorities
	 */
	public CustomUser(int id, String username, String password, GrantedAuthority[] authorities) {
		this.id = id;
		this.password = password;
		this.username = username;
		this.authorities = authorities;
	}

	public Collection<GrantedAuthority> getAuthorities() {
		Collection<GrantedAuthority> auth = new ArrayList<GrantedAuthority>();
		for (int i = 0; i < authorities.length; i++) {
			auth.add(authorities[i]);
		}
		return auth;
	}
	
	/**
	 * @return the id
	 */
	public long getId() {
		return id;
	}
	
	/**
	 * @param id the id to set
	 */
	public void setId(long id) {
		this.id = id;
	}
	
	@Override
	public String getPassword() {
		return this.password;
	}

	@Override
	public String getUsername() {
		return this.username;
	}
/**
* For convenience the below methods return all true; In a real application it is not desired, however.
*/
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}

Putting it all together, as well as setting up a database containing a table similar in structure to the User.java entity, should result in a working database-backed login system.

28Nov/100

P2P Communication using JXTA

In this post I'll share some information related to the P2P world and JXTA. I had the chance to delve into this topic thanks to my bachelor thesis which implied using this paradigm.

JXTA came around 2001 as an open-source project being developed by Sun Microsystems. Unfortunately the framework had times of on and off development. The current GA(General availability) version is 2.6. The code below targets the 2.5 version but that shouldn't be a problem since JXTA is merely a specification(implemented in C and Java, so far). I'll stop at those points that gave me a hard time understanding them because, quite naturally, you'll be tempted to think: "Why does P2P have to be so complicated?".

The architecture of JXTA is quite complex and, in case you are interesed, you can take a look at http://jxse.kenai.com/Tutorials/Tutorials.html.
The programmer's guide for 2.5 version presents the basic framework constructs and 2.6 goes on into deeper details related to the respective version.
Because you want to deploy your application in whatever network possible you must be agnostic of the underlying physical layer. JXTA achieves this by creating a virtual network. At this level, a host is not represented by their IP address and port number anymore. Instead, each peer is described by its peer ID, a unique JXTA identifier.

A very important aspect in a P2P system is being able to easily publish and find services. By using an advertisement, one can leverage the ability to locate services offered by peers. For example, in a hypothetical network of 2 peers, peer A has file-sharing services while B wants to download some files. For B to get the files and A to fulfill its purpose the following actions have to take place:

1. A publishes an advertisement in which it states its file-sharing services. This is published locally or remotely, depending on the method chosen.

2. B issues a query to check for file-sharing servces. This will be propagated into the network by the framework and the results will be returned asynchronously (this is because the call to get a remote advertisement could stall for a while until it returns).

3. B catches a discovery event asynchronously and reads the data. If it matches its criteria, it will act acordingly. The found advertisement is cached and will live in the local cache, just in case B wants to find the service in the future.  If that's the case, it'll skip searching the network.

The above steps translate into this lines of code:

1.

discovery.publish(pipeAdv, lifetime, expiration); // publishes in the local cache

// or

discovery.remotePublish(pipeAdv, expiration); // publishes adv remotely

2.

discovery.getRemoteAdvertisements(null, // no specific peer (propagate)
                				 DiscoveryService.ADV, // Adv type
                			         "Name", // the attribute we are searching by
					         "File Sharing", // the value of the attribute
				                 1, // one advertisement response is expected
						 null); // no query specific listener. we are using a                 global listener

The 5th parameter can be quite a problem if you want to receive many advertisements. It can be easily forgotten there unchanged. It happened to me.

3.

public void discoveryEvent(DiscoveryEvent ev) {
        DiscoveryResponseMsg res = ev.getResponse();

        Advertisement adv;
        Enumeration en = res.getAdvertisements();

        if (en != null) {
            while (en.hasMoreElements()) {
                adv = (Advertisement) en.nextElement();
                System.out.println(adv);
            }
        }
    }

The advertisements are quite a powerful way of dynamically resolving services. They are nothing more than plain-old XML files that are stored either locally or remotely.
Sticking to the file-sharing example here is how the advertisement might look like:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jxta:PipeAdvertisement>
<jxta:PipeAdvertisement xml:space="default" xmlns:jxta="http://jxta.org">
	<Id>
		urn:jxta:uuid-59616261646162614E504720503250339F4D098AB75C405BA64FC0A9A1F70AF404
	</Id>
	<Type>
		JxtaUnicast
	</Type>
	<Name>
		File Sharing
	</Name>
</jxta:PipeAdvertisement>

Adverisements can pe published or retrieved by using the build-in discovery service from JXTA. They can be broadcasted into the network if the service provided is unique or for a loose coupling between peers and services. On the other hand, in the case of static services such as offering the ability to connect to a multicast server, they can easily be hardcoded in the application and used as needed. To expand a little bit this use case, imagine a network in which every peer sends status information at regular intervals to others. Basically everyone is both a multicast client and server. It might come in handy to just connect to the multicast servers that others provide using an advertisement hardcoded in a static class. Since this kind of service is the same for every peer and hardly going to change, it is easier than setting up a discovery service to find something predictable.

Advertisements are good for many things but, as I found out from the forums, they are not a good way for notifying presence. So, if you want to create a P2P chat application, you should avoid checking the online peers by looking for their PeerAdvertisement or some custom type. This is because they are cached locally and that makes it difficult to reflect real-time changes. Furthermore, the cache can behave unpredictably(at least  I experienced some odd behaviour in the 2.5 version). As I read from the 2.6 guide, the cache implementation changed and it's expected to be more reliable.

Another important note is about advertisement expiration and lifetime. Although they might sound the same thing, as you'll see in the API docs, they're not. Lifetime represents the duration that the advertisement will exist where it is published and expiration is the time the peers that find it will store it in their local cache. From my personal experience, in the 2.5 version, PeerAdvertisements presented some peculiar bug, in the sense that they appeared not to expire for some reason. Then again, this might be changed in the 2.6 and subsequent versions.

As a side-note, Oracle cut the support for JXTA, so at the time of this writing the project is in the process of being moved to Apache Software Foundation and the name they chose is Chaupal. It is expected that future versions of JXTA will be named Apache Chaupal. Nevertheless, this short introduction deals with principles behind the specification so the name / version change shouldn't be an issue.

Tagged as: , , No Comments
13Oct/102

What’s the buzz about Gliese 581g?

Gliese star system

Gliese 581g

There has been quite a lot of talk since 29th of September when the planet Gliese 581g was discovered and that is for a reason.

First of all, I think it's quite a bad name for a rising star on the web(or planet, if you wish). But given that some exoplanets' names are more like cyphers, such as OGLE-TR-56b, we can live with that. It's all about that trailing "g" from the name. "G" stands for goldilocks and that makes the buzz.

A goldilocks zone is  a place around a star, not too far and not too close so that liquid water can form on the surface of the planets orbiting inside that zone. You can think of it as a river in a desert. Imagine the space as a huge desert and here and there some villages near streams of water. In that sense, we are lucky to be placed just near that kind of river. But it seems like we're not the only village in the county, that is...cosmic county.

Gliese 581g may be the neibourghing village in the desert, but is it really?

Calculations show that its mass is three to four times that of Earth, which makes it the most Earth-like thing yet discovered. This means that it could be a rocky planet, and that implies it could hold on to an atmosphere and, of course, the list of implications could go on meaning that intelligent beings could live on the surface. But there's a twist.

We already know of planets in the goldilocks zone that are rocky and have an atmosphere, those being Venus, Earth and Mars. Of course, one could argue that Venus and Mars are outside, since they don't have liquid water on the surface, but my point here is other. From the three, only one happens to have the magic formula to sustain life. So based only on the things we know at this moment about Gliese 581g, it's impossible to tell if we should consider it galactic real estate. In other words, it could be a Venus-like planet where the only good thing to do is to melt lead or the barron desert of Mars where it's doubtful that microbes could live.

But given that this planet is a hostile environment, the news still remains cool. It's impossible to peer deeper into space to see it directly. The planetary system from which it is part of is tilted at an unfortunate angle, so the planet doesn't pass in between us and its host star for us to study it. Since it is a mere (in cosmic terms) 20 light-years away, it's a good bet to say that very soon a planetary system tilted edge on will be found.

Or maybe there's another twist. Maybe sentient ETs are already roaming the galaxy and are among us. Maybe they started off from Gliese's planetary system. This sounds SciFi and I tend to disregard it, but for the sake of diversity it would be cool to meet ET in the far off future. For the moment, it's better to feel like the only village in the cosmic county. At least there's no  need for a county sheriff.

If you want to find more try here and here

Tagged as: 2 Comments