/*
 * Copyright 2017 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.perspicuus.storage;

import org.apache.avro.Schema;
import org.hibernate.search.annotations.*;
import org.hibernate.search.annotations.Index;

import javax.persistence.*;

/**
 * Storage layer representation of a Schema.
 *
 * @since 2017-02
 * @author Jonathan Halliday (jonathan.halliday@redhat.com)
 */
@Entity
@NamedQueries({
        @NamedQuery(name = "SchemaEntity.byHash", query = "SELECT e FROM SchemaEntity e WHERE e.hash=:hash")
})
@Indexed
public class SchemaEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long id;

    @Column(nullable = false, unique = true)
    public String hash;

    @Column(nullable = false)
    @Field(name="content", store = Store.YES, bridge = @FieldBridge(impl = AvroSchemaStringBridge.class))
    public String content;

    public SchemaEntity() {}

    public SchemaEntity(String schema) {
        Schema avroSchema = new Schema.Parser().parse(schema);
        this.content = avroSchema.toString();
        this.hash = ""+content.hashCode();
    }
}

@@ -764,35 +764,177 @@
 ex;%0A
-%0Aimport javax.persistence.*
+import sun.security.provider.MD5;%0A%0Aimport javax.persistence.*;%0Aimport java.security.MessageDigest;%0Aimport java.security.NoSuchAlgorithmException;%0Aimport java.util.Arrays
 ;%0A%0A/
@@ -1731,24 +1731,25 @@
 toString();%0A
+%0A
         this
@@ -1749,41 +1749,527 @@
    t
-his.hash = %22%22+content.hashCode();
+ry %7B%0A            // https://avro.apache.org/docs/current/spec.html#Schema+Fingerprints%0A            // recommends MD5 or SHA-256, both of which are present as standard in java%0A            MessageDigest messageDigest = MessageDigest.getInstance(%22SHA-256%22);%0A            messageDigest.update(content.getBytes());%0A            byte%5B%5D digestBytes = messageDigest.digest();%0A            this.hash = Arrays.toString(digestBytes);%0A        %7D catch (NoSuchAlgorithmException e) %7B%0A            throw new RuntimeException(e);%0A        %7D
 %0A   

Use more robust checksum algorithm