Prime Datatype

package com.elharo.xml.relaxng;

import org.relaxng.datatype.*;
import org.relaxng.datatype.helpers.StreamingValidatorImpl;

public class PrimeDatatype implements Datatype {

  private boolean isPrime(String literal) {
      
    try {
      int candidate = Integer.parseInt(literal); 
      if (candidate < 2) return false;
      double max = Math.sqrt(candidate);
      for (int i = 2; i <= max; i++) {
        if (candidate % i == 0) return false;
      }
      return true;
    }
    catch (NumberFormatException ex) {
      return false;      
    }
    
  }

  public boolean isValid(String literal, ValidationContext context) {
    return isPrime(literal);
  }

  public void checkValid(String literal, ValidationContext context) 
    throws DatatypeException {

    if (!isValid(literal, context)) {
      throw new DatatypeException(literal + " is not a prime number");
    }
    
  }

  
  public DatatypeStreamingValidator createStreamingValidator(ValidationContext context) {

    // Inefficient but simple. StreamingValidatorImpl stores 
    // everything in a string and then validates the string. More 
    // efficient implementations can validate piece by piece.
    return new StreamingValidatorImpl(this, context);

  }

  
  // These next three methods are closely tied together. The object
  // returned by this method si only used for sameValue and hashCode.
  public Object createValue(String literal, ValidationContext context) {

    if (isPrime(literal)) {
        return Integer.valueOf(literal);
    }
    return null;
    
  }
  
  public boolean sameValue(Object value1, Object value2) {

    if (value1 == null) return value2 == null;
    else return value1.equals(value2);
    
  }

  public int valueHashCode(Object value) {
    return value.hashCode();
  }

  public int getIdType() {
    return ID_TYPE_NULL;
  }

  public boolean isContextDependent() {
    return false;
  }
  
}

Previous | Next | Top | Cafe con Leche

Copyright 2005, 2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 26, 2004