Java? Come on! :)

I’m working on a patch for Maven Release. Now Brett asked me to write an integration test, to prove I’m actually fixing something.

The project uses Maven Verifier, which runs a pom and then lets you test whether it did the right thing or not by checking the build log.

Check, if a file has a string in it

I copied this java-code (verify.bsh) from a similar integration test. It reads the build.log and checks if it contains some string.

import java.io.*;
import java.util.*;
import java.util.regex.*;

try
{   
    File buildLog = new File( basedir, "build.log" );
    
    System.out.println( "Checking logs.." );
    
    StringBuffer data = new StringBuffer( 1024 );
    BufferedReader reader = new BufferedReader( new FileReader( buildLog ) );
    char[] buf = new char[1024];
    int numRead = 0;
    while ( ( numRead = reader.read( buf ) ) != -1 )
    {
        String readData = String.valueOf( buf, 0, numRead );
        data.append( readData );
        buf = new char[1024];
    }
    reader.close();
    String contents = data.toString();

    String expected = "Executing goals 'clean verify' with arguments '-P profile-in-parent,it-repo'";
    
    if( contents.indexOf( expected ) != -1 )
    {
        return true;
    }            
}
catch( Throwable t )
{
    t.printStackTrace();
    return false;
}

System.out.println( "FAILED!" );
return false;

I now replaced this with following groovy code (verify.groovy):

expected = "[INFO] Executing goals 'clean verify' with arguments '-P it-repo,profile-in-parent'"

println "Expects \"$expected\" in build.log"
println "Checking logs..."

found = new File(basedir, "build.log" )
            .text
            .contains(expected)

println found ? "GOOD!" : "FAILED!"

return found

Happy coding!

Naming is important

Just stumbled over a “bug” in .NET 4.0 DataAnnotations/Validator that was quite easy to “work around”, but still took us a while to figure out.

We want to do simple structural server-side validations.

Data Annotations

/* haven’t installed my Live Writer beautifier-plugin yet */

public class SomeCommand : Command {

    [Required] public string Name { get; set; }

    [Required] public sting City { get; set; }

    [Range(0,99)] public string Age { get; set; }

}

The base class uses System.ComponentModel.DataAnnotations.Validator to run the validations in this simple Method:

private IEnumerable<ValidationResult> AutoValidation()
{
    var results = new List<ValidationResult>();
    Validator.TryValidateObject(this, new ValidationContext(this, null, null), results);
    return results;
}

Problem

It only validated the fields marked as required. The RangeAttribute was ignored.

After a while we had a look at the .NET-Framework-Sources using Reflector, and found this:

if (validateAllProperties)
{
    source.AddRange(GetValidationErrors(pair.Value, pair.Key, propertyValidationAttributes, breakOnFirstError));
}
else
{
    RequiredAttribute validationAttribute = propertyValidationAttributes.FirstOrDefault<ValidationAttribute>(delegate (ValidationAttribute a) {
        return (a is RequiredAttribute);
    }) as RequiredAttribute;
    if (validationAttribute != null)
   {
       // validate the RequiredAttribute

validateAllProperties in this case means: do not only run Required-Validations.

Solution

Actually a different override of Validator.TryValidateObject has a flag named validateAllProperties. But since it did already validate more than one property, I assumed true was the default.

Lesson I learned: do not assume anything!

Lesson for MS: Take time finding the right name! Do refactor!

I filed a bug here: https://connect.microsoft.com/VisualStudio/feedback/details/605635/missleading-parametername-validateallproperties-in-validator-try-validate-componentemodel-dataannotations

Size calculations for image resizing (C#)

I just reused some code I wrote a couple of years ago, and thought I’d share it here.

It’s not about the best ways to resize images. If that is what you search for, have a look at this 🙂

It’s rather some code for calculating the size of the target image from the originals size while applying one of four rules:

  • Fit: Often you want to fit the image into a box – but without stretching it. So if you have a image that is 50×100 and you want to fit it into 50×50, the result is 25×100. If the original is 100×50, the result would be 50×25. Getting it?
  • Stretch: Not to useful, but sometimes needed 🙂
  • FixedHeight: Maintain the ratio, adjust to height.
  • FixedWidth: Maintain the ration, adjust to width.

Usage

Pretty straight-forward, I think.

var _100_50 = new Size(100, 50);
ResizeType.Fit.CalcNewSize(_100_50, new Size(50, 50), true)
    .Satisfy(s => s.Width == 50 && s.Height == 25);

var _50_100 = new Size(50, 100);

ResizeType.Fit.CalcNewSize(_50_100, new Size(50, 50), true)
    .Satisfy(s => s.Width == 25 && s.Height == 50);

ResizeType.Stretched.CalcNewSize(_50_100, new Size(500, 500), false)
    .Satisfy(s => s.Width == 50 && s.Height == 100);

ResizeType.FixedHeight.CalcNewSize(_50_100, new Size(0, 50), false)
    .Satisfy(s => s.Width == 25 && s.Height == 50);

* The Satisfy-Method is from SharpTestEx.

Code

Have fun! 🙂

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;

namespace lcorneliussen
{
    public interface IResizeType
    {
        Size CalcNewSize(Size currentSize, Size newSize, bool resizeIfSmaller);
    }

    /// <summary>
    /// Offers some helpful methods for image resizing.
    /// </summary>
    public class ResizeType
    {
        /// <summary>
        /// Returns the new size by fixed height.
        /// </summary>
        public static IResizeType FixedHeight = new FixedHeightResizeType();

        /// <summary>
        /// Returns the new size by fixed width.
        /// </summary>
        public static IResizeType FixedWidth = new FixedWidthResizeType();

        /// <summary>
        /// Returns a size wich fits in a target size.
        /// </summary>
        public static IResizeType Fit = new FitResizeType();

        /// <summary>
        /// Stretches a image to the given size.
        /// </summary>
        public static IResizeType Stretched = new StretchedResizeType();

        private static int CalcNewHeight(int currentWidth, int currentHeight, int newWidth)
        {
            float ratio = (float)newWidth / (float)currentWidth;
            float newHeight = currentHeight * ratio;

            return (int)newHeight;
        }

        private static int CalcNewWidth(int currentWidth, int currentHeight, int newHeight)
        {
            float ratio = (float)newHeight / (float)currentHeight;
            float newWidth = currentWidth * ratio;

            return (int)newWidth;
        }

        private class FixedHeightResizeType : IResizeType
        {
            public Size CalcNewSize(Size currentSize, Size newSize, bool resizeIfSmaller)
            {
                int height = newSize.Height;

                if (!resizeIfSmaller)
                {
                    if (height > currentSize.Height) height = currentSize.Height;
                }

                int newWidth = CalcNewWidth(currentSize.Width, currentSize.Height, height);
                return new Size(newWidth, height);
            }
        }

        private class FixedWidthResizeType : IResizeType
        {
            public Size CalcNewSize(Size currentSize, Size newSize, bool resizeIfSmaller)
            {
                int width = newSize.Width;
                
                if (!resizeIfSmaller)
                {
                    if (width > currentSize.Width) width = currentSize.Width;
                }

                int newHeight = CalcNewHeight(currentSize.Width, currentSize.Height, width);
                return new Size(width, newHeight);
            }
        }

        private class FitResizeType : IResizeType
        {
            public Size CalcNewSize(Size currentSize, Size newSize, bool resizeIfSmaller)
            {
                int width = newSize.Width;
                int height = newSize.Height;

                int newWidth = currentSize.Width;
                int newHeight = currentSize.Height;

                if (!resizeIfSmaller) // break, if newSize allready fits in currentSize
                    if (currentSize.Height < height && currentSize.Width < width)
                        return new Size(currentSize.Width, currentSize.Height);

                if(width != newWidth) // shrink or expand to width
                {
                    newHeight = CalcNewHeight(currentSize.Width, currentSize.Height, width);
                    newWidth = width;
                }
                if (newHeight > height) //shrink to fit height, if neccesarry
                {
                    newWidth = CalcNewWidth(newWidth, newHeight, height);
                    newHeight = height;
                }

                return new Size(newWidth, newHeight);
            }
        }

        private class StretchedResizeType : IResizeType
        {
            public Size CalcNewSize(Size currentSize, Size newSize, bool resizeIfSmaller)
            {
                int w = newSize.Width;
                int h = newSize.Height;

                if (!resizeIfSmaller)
                {
                    if (w > currentSize.Width) w = currentSize.Width;
                    if (h > currentSize.Height) h = currentSize.Height;
                }

                return new Size(w, h);
            }
        }
    }
}

* this code on gist

antExec – Executing external processes in Groovy

Groovy is a nice language. I currently use it for writing maven plugins and for doing scripting tasks in the realm of build automation.

Poor mans integration with .NET or other systems is the command-line. Groovy has built-in support for that:

"myprog".execute()

And if you need parameters:

["cmd", "/C", "cd"].execute()

But there are some problems with how to wait for the process and retrieve the streams. Often you just want the output back – and you want to make sure that the command exited with no error.

There is also a ant-integration in groovy. So I wrote a little wrapper that makes using ant’s exec-task feasible:

mixinAntExec() // has to be called once
// prints the stdout
// if the error code is != 0, 
// it throws an exeption with 
// helpful information
println ("myprog".antExec())

def result = ["myprog", "/fail"].antExec(false)
println (result.exitValue) // error code
println (result.error) // err out
println (result.text) // std out

This script can either be pasted to the bottom, or included on the script path:

def mixinAntExec() {
    String.metaClass.antExec = {failOnError=true -> antExec([delegate], failOnError)}
    ArrayList.metaClass.antExec << {failOnError=true -> antExec(delegate, failOnError)}
}

def antExec(command, failOnError=true) {
    def commandLiteral = command.collect{it.contains(' ') ? '"' + it + '"' : it}.join(' ')
    
    println "ant exec with: ${commandLiteral}"
    
    def ant = new AntBuilder()
    ant.exec(outputproperty:"text",
             errorproperty: "error",
             resultproperty: "exitValue",
             failonerror: false,
             executable: command[0]) {
               if (command.size()>1)
                   arg(line:command[1..-1].collect{it.contains(' ') ? '"' + it + '"' : it}.join(' '))
             }
         
     def result = new Expando(
         text: ant.project.properties.text,
         error: ant.project.properties.error,
         exitValue: ant.project.properties.exitValue as Integer,
         toString: {text}
     )
     
     if (failOnError && result.exitValue != 0){
         throw new Exception("""command failed with ${result.exitValue}
executed: ${commandLiteral}
error: ${result.error}
text: ${result.text}""")

     }
     
     return result
}