Thursday, July 28, 2011

Scala by-name parameter

I was reading the section "Call-by-Name" in the book "Begining Scala" by David Pollak,
trying to get my head around by-name parameters. He gave an example,

def nano() = {
    println("Getting nano")
    System.nanoTime
}

def delayed(t: => Long) = { // => indicates a by-name parameter
    println("In delayed method")
    println("Param: "+t)
    t
}

println(delayed(nano()))

Coming from Java and used to call-by-reference, I was expecting the output to be

Getting nano
In delayed method
Param: 4513758999378
4513758999378     // same value as Param

but the output was

In delayed method
Getting nano
Param: 4475258994017
Getting nano
4475259694720     // different value from Param

Re-reading that section a couple of times still doesn't ring a bell (the book is really good though).
Googling "scala by-name parameters" returns long examples and explanations
on the subject, and more confusion for an absolute Scala beginner like me.

Referring to the Scala Language Specification, section 4.6.1 By-Name Parameters finally defreezes my brain.

... argument is not evaluated at the point of function application, but instead is evaluated at each use within the function.

Ok. Got it. Back to the example,

def delayed(t: => Long) = {
    println("In delayed method")
    println("Param: "+t) // t or nano() used, so "Getting nano" printed,
                         // then print "Param: " and the return of nano(), e.g. System.nanoTime
    t                    // t or nano() used again, thus print "Getting nano" and the System.nanoTime
                         // would have now elapsed
}

Wednesday, July 27, 2011

Google +1 callback and Wicket

Google plusone tag's callback parameter let's you call a JavaScript function when the plusone button is clicked. As an example,

<g:plusone size="tall" callback="callWicket"></g:plusone>
 
<script type="text/javascript">
        function callWicket(data) {
            // Do something here
        }
    </script>
 

What if you want to pass Wicket data (for this example, we'll get the JSON object) when the plusone button is clicked? There's an explanation of calling Wicket from JavaScript. We can either use the wicketAjaxGet or wicketAjaxPost functions provided by the contributed wicket-ajax.js when you add an Ajax behaviour to Wicket components, e.g. adding an AbstractDefaultAjaxBehavior.

We have to build the JavaScript as shown,

function callWicket() {
        var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });
    }
 

to be generated by the wicket component :-

<script type="text/javascript" wicket:id="pluscallback"></script>
 
'$url$' is obtained from behave.getCallbackUrl() and $args will be constructed from plusone JSON object. Thus,
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {

        protected void respond(final AjaxRequestTarget target) {
            // Do what you want with the data
        }
    };
    add(behave);

    CharSequence url = behave.getCallbackUrl();
    CharSequence args = "&href='+data.href+'&state='+data.state";
    StringBuffer sb = new StringBuffer();
    sb.append("function callWicket(data, id) { \n");
    sb.append("     var wcall = wicketAjaxGet('");
    sb.append(url); // the $url$
    sb.append(args); // the $args$
    sb.append(", function() { }, function() { });");
    sb.append("    }");
    Label pluscallback = new Label("pluscallback", sb.toString());   // the script tag
    add(pluscallback);
 
Getting the parameters from the JavaScript
RequestCycle.get().getRequest().getParameter("href");
    RequestCycle.get().getRequest().getParameter("state");
 

You can download the Wicket quickstart here.

Wednesday, July 20, 2011

Google +1 and Wicket Ajax Components

I wanted to incorporate the google +1 buttons for submitted links on a social bookmarking website I was building, which uses Wicket. Adding +1 buttons was easy.

The html tag:

<g:plusone wicket:id="plusone"></g:plusone>

Adding a dynamic href attribute to the tag was made simple using the AttributeModifier class:

Label plusone = new Label("plusone");
plusone.add(new AttributeModifier("href", true, new Model(submittedLink.getUrl())));
.

The rendered html tag, as sent to the browser will be:

<g:plusone wicket:id="plusone" href="http://www.exampleurl.com"></g:plusone>

with it's final form as a <div> tag with lot's of content.

However, the +1 buttons does not show after Wicket's Ajax calls, for example when clicking on a AjaxFallbackLink to refresh the section containing the button. I am guessing that the <g:plusone> tag is rendered to the final button form only initially when the page is first requested/loaded.

You can however fire up the JavaScript to manually render the tag using gapi.plusone.go(). Thus, overriding the Wicket Ajax component's onAjaxEvent will do the trick.

@Override
protected void onAjaxEvent(AjaxRequestTarget target) {
   target.appendJavascript("gapi.plusone.go()");
   super.onAjaxEvent(target);
}

Monday, June 20, 2011

Basic Linux Security - SSH

It's been some time since my Linode VPS has been up. Haven't been paying any attention to it since I've been busy coding a web application. Thought I'd do some housekeeping, starting with the logs files and guess what? There's quite a number of individuals who are keen on getting into the server. Keep trying as I need lots practice to keep you out. I get a couple of these unique visitors daily. Here's one. From the /var/log/auth.log,

Jun 19 10:13:03 debian sshd[327]: Invalid user mirain from 210.83.226.181
Jun 19 10:13:03 debian sshd[327]: pam_unix(sshd:auth): check pass; user unknown
Jun 19 10:13:03 debian sshd[327]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=210.83.226.181
Jun 19 10:13:05 debian sshd[327]: Failed password for invalid user mirain from 210.83.226.181 port 58621 ssh2
Jun 19 10:13:06 debian sshd[329]: reverse mapping checking getaddrinfo for reverse.gdsz.cncnet.net [210.83.226.181] failed - POSSIBLE BREAK-IN ATTEMPT!
Jun 19 10:13:06 debian sshd[329]: Invalid user opt2 from 210.83.226.181
Jun 19 10:13:06 debian sshd[329]: pam_unix(sshd:auth): check pass; user unknown
Jun 19 10:13:06 debian sshd[329]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=210.83.226.181
Jun 19 10:13:08 debian sshd[329]: Failed password for invalid user opt2 from 210.83.226.181 port 58909 ssh2
Jun 19 10:13:10 debian sshd[331]: reverse mapping checking getaddrinfo for reverse.gdsz.cncnet.net [210.83.226.181] failed - POSSIBLE BREAK-IN ATTEMPT!
Jun 19 10:13:10 debian sshd[331]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=210.83.226.181  user=root
Jun 19 10:13:12 debian sshd[331]: Failed password for root from 210.83.226.181 port 59144 ssh2
Jun 19 10:13:13 debian sshd[333]: reverse mapping checking getaddrinfo for reverse.gdsz.cncnet.net [210.83.226.181] failed - POSSIBLE BREAK-IN ATTEMPT!
Jun 19 10:13:13 debian sshd[333]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=210.83.226.181  user=root
Jun 19 10:13:16 debian sshd[333]: Failed password for root from 210.83.226.181 port 59447 ssh2
Jun 19 10:13:17 debian sshd[335]: reverse mapping checking getaddrinfo for reverse.gdsz.cncnet.net [210.83.226.181] failed - POSSIBLE BREAK-IN ATTEMPT!
Jun 19 10:13:17 debian sshd[335]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=210.83.226.181  user=root
Jun 19 10:13:19 debian sshd[335]: Failed password for root from 210.83.226.181 port 59763 ssh2
Jun 19 10:13:21 debian sshd[337]: reverse mapping checking getaddrinfo for reverse.gdsz.cncnet.net [210.83.226.181] failed

A quick google gives some simple tips for my ssh setup. I'll just list it here for future reference.

  • Disable root login. In /etc/ssh/sshd_config PermitRootLogin no
  • Change the port sshd is running on, e.g. Port 2229
  • Install fail2ban. Package description: bans IPs that cause multiple authentication errors
  • Change the shell for nobody to /bin/false or /bin/nologin

There's still others but these will do for now. Have to get back to coding.

Saturday, March 27, 2010

Integration Testing JPA and EJB 3 with Arquillian and GlassFish Embedded

By default, the Arquillian container for GlassFish embedded creates a temporary instance every time you run the Arquillian test. So how do we go about setting up JNDI datasources for GlassFish embedded? Well, for now you could make a tiny change to GlassfishEmbeddedContainer.java (in arquillian-glassfish-embedded-30 maven artifact) so it'll setup your embedded instance at a permanent location. Then, you can setup all the datasources you want in the instance's domain.xml file.

Make the changes to GlassfishEmbeddedContainer.java and rebuild the jars to your local maven repository

public GlassFishEmbeddedContainer() {
                final Server.Builder builder = new Server.Builder(GlassFishEmbeddedContainer.class.getName());

                final EmbeddedFileSystem.Builder embeddedFsBuilder = new EmbeddedFileSystem.Builder();

                // final EmbeddedFileSystem embeddedFs = embeddedFsBuilder.build();
                final EmbeddedFileSystem embeddedFs = embeddedFsBuilder.
                    instanceRoot(new File("src/test/glassfish")). // set the instance root
                build();
                builder.embeddedFileSystem(embeddedFs);
                server = builder.build();

                server.addContainer(ContainerBuilder.Type.all);
            }

        

@Override
    public void start() throws LifecycleException {
        try {
            for (EmbeddedContainer contianer : server.getContainers()) {
                // do not bind the embedded glassfish to any port
                // instead, the instance will use the port specified in the domain.xml file
                //contianer.bind(server.createPort(port), "http");
                contianer.start();
            }
        } catch (Exception e) {
            throw new LifecycleException("Could not start container", e);
        }
    }

Here's a screenshot of directory and files generated by the Glassfish embedded when you run the test. However, you have to create your own domain.xml and place it under the config folder. You can copy this file from your GlassFish v3 installation and modify it accordingly.


Sample datasource setup in domain.xml


    
    
        
        
        
        
        
    


The test

@RunWith(Arquillian.class)
public class TicketFacadeTest {

    @EJB
    private TicketFacade ticketFacade;

    @Deployment
    public static JavaArchive createDeployment() {
        return Archives.create("test.jar", JavaArchive.class).
                addClasses(
                Ticket.class, // be sure to include your JPA entities, else Glassfish embedded will not pick it up
                TicketFacade.class,
                TicketFacadeBean.class).
                addManifestResource(new File("src/main/resources/META-INF/persistence.xml"));
    }

    @Test
    public void shouldBeAbleToInjectEJB() throws Exception {
        Ticket ticket = new Ticket();
        ticket.setDescription("This is a new ticket.");
        ticket.setPriority(Priority.SEVERE);
        ticket.setStatus(Status.NEW);
        ticketFacade.create(ticket);

        List tickets = ticketFacade.findAll();
        Assert.assertEquals(1, tickets.size());

    }
}


Download the project.

Friday, September 08, 2006

Calculating page request times for your web application

It has been 3 weeks since I started developing jobBoard, a web application for online recruitment/jobs database. Time now for some performance numbers!

How do you accurately measure the processing time it takes for each request on your web application? An example,

  • User clicks on a link on a page
  • Request goes through a couple of servlet filters, e.g acegi, sitemesh filters
  • The corresponding controllers/actions process the request, calls DAOs
  • DAOs/ORMs queries the native database system and returns results to controller
  • Controller gets results from DAOs and puts request attributes to JSP/Velocity etc. page template
  • Page served up by the web server.

There's a good article on servlet filters with an example just to do the above. However, I needed to present the process time on the requested web page but once the filter chain is executed, I can't put the execution time as a request attribute to be used by the page template. But here's a neat trick.

Put the 'before' time into the request attribute,

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

  long before = System.currentTimeMillis();
  request.setAttribute("before", before); // add here
  chain.doFilter(request, response); 
  long after = System.currentTimeMillis();

Then in my JSP page,

Request processed in <%= System.currentTimeMillis() - Long.valueOf(pageContext.getRequest().getAttribute("before").toString()) %> ms

The values are the same as when using the example TimeFilter as it is

Process Time.

Friday, September 01, 2006

Testing your Java Persistence API queries interactively

One of aspects of developing with ORMs is to test your JPA, EJB, Hibernate QL queries and get the results you wanted before hard coding it into your web application. For Hibernate, there's Hibernate tools but what about JPA? And within the Spring framework. Fortunately, the Spring framework provides a class (org.springframework.test.jpa.AbstractJpaTests;) to test your DAOs, which you can just adapt to make a sort of 'Query Tester'.

Here's what I did

public class JpaJobboardTests extends AbstractJpaTests {

  private JobDao jobDao;
  
  protected String[] getConfigLocations() {
    return new String[] {
      "applicationContext-jpa.xml"
    };
  }
        
    public void testQuery() {
        Query q = sharedEntityManager.createQuery(

                "SELECT DISTINCT j FROM Job j " +
                "JOIN j.industries i " +
                "JOIN j.employmentTypes e " +
                "JOIN j.qualification q " +
                "WHERE " +
                "q.id BETWEEN 2 AND 4" +
                " AND " +
                "i.id IN (4) " +
                " AND e.id IN (3)"

                );
        List jobs = q.getResultList();
        Iterator iterator = jobs.iterator();
        while (iterator.hasNext()) {
            Job job = (Job)iterator.next();
            System.out.println(job.getId() + " : " + job.getPosition());
            System.out.println(job.getIndustries());
            System.out.println(job.getEmploymentTypes());
            System.out.println(job.getQualification().getId());
        }
    }

    public void testGetAllJobs() {
        List jobs = this.jobDao.findAll();        
    }
    
    public JobDao getJobDao() {
        return jobDao;
    }
    
    public void setJobDao(JobDao jobDao) {
        this.jobDao = jobDao;
    }
    
}

Plug it into my favorite IDE, and run it. You can edit your queries and see the results interactively.

Sure, you could code a seperate application just to do this, with named queries stored in a seperate XML file, and changing the queries in the external file, and not the source codes and recompiling every time.

Thursday, August 31, 2006

Using the Display Tag with external sorting and paging

I was comparing between using using Value List Handler and the Display Tag Library to do sorting and paging of my web appliaction's result sets and decided on using the Display Tag Library for it's much simpler configuration and because of the latest release's external sorting and paging features. Created a helper class to get the parameters provided by the display tag to pass to the DAOs, otherwise the code in the controller/action gets a litlle messy. Here's pieces of what i did.

In the JSP

In the controller (I'm using Spring MVC)

In the DAO

Currently the banner does not show correct values. e.g if u have 10 as the page size, it should show 1-10 for first page, 11-20 for second page. But it always shows 1-10 for all the pages. However, this will probably be fixed in next release.

Friday, August 18, 2006

Spring 2.0 form tags

I like the Spring's form tags. It just does what it what I wanted. Registered a custom date editor in the controller and used Spring's select tag for the date selection instead of input to a text box.

<form:select path="birthDate.date">
  <c:foreach var="date" begin="1" end="31" step="1">
    <form:option value="${date}"></form:option>
  </c:foreach>
</form:select>

<form:select path="birthDate.month">
  <c:foreach var="month" begin="0" end="11" step="1">
    <form:option value="${month}" label="${1+ month}"></form:option>
  </c:foreach>
</form:select>

<form:select path="birthDate.year">
  <c:foreach var="year" begin="45" end="106" step="1">
    <form:option value="${year}" label="${1900 + year}"></form:option>
  </c:foreach>
</form:select>

  <spring:bind path="account.birthDate">
  <span class="error">${status.errorMessage}</span>
  </spring:bind>
Doing forms for date inputs used to be a pain with Struts.

Hibernate Tools and Java Persistence API?

I missed using Hibernate's table generation tools. Currently am working on a web application and wanted to try learning to use the Java Persistence API . I am using netbeans 5.5 beta as my IDE and as of now, the table generation from entity classes can only be used when using the Sun Application server and using JSF as the web framework. As a temporary solution, I used the JSF/JPA/DDL generation and switched to running Spring MVC+JPA on the same project.