Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  Copyright 2010 Pavel Ponec.
   *
   *  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.
  *  under the License.
  */
 package org.ujorm.orm.utility;
 
 import java.io.Reader;
 import java.sql.Blob;
 import java.sql.Clob;
 import java.util.List;
 import org.ujorm.Key;
 import org.ujorm.Ujo;
Many useful methods for
  • BLOB/CLOB
  • lazy loading
  • reloading
    • Author(s):
      Pavel Ponec
 
 final public class OrmTools {

    
Create a new Blob

Parameters:
bytes The null value is supported.
 
     public static final SerialBlob createBlob(byte[] bytes) {
         try {
             return bytes!=null ? new SerialBlob(bytes) : null;
         } catch (Exception e) {
             throw new IllegalStateException(e);
         }
     }

    
Create a new Blob

Parameters:
inputStream
 
     public static SerialBlob createBlob(InputStream inputStream) {
         try {
             byte[] buffer = new byte[1024];
             ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length);
             int len;
 
             while ((len = inputStream.read(buffer)) >= 0) {
                 baos.write(buffer, 0, len);
             }
             return new SerialBlob(baos.toByteArray());
         } catch (Exception e) {
             throw new IllegalStateException("Reding error"e);
         } finally {
             try {
                 inputStream.close();
             } catch (IOException e) {
                 throw new IllegalStateException("Reding error"e);
             }
         }
     }

    
Returns byte array to the maximal length Integer.MAX_VALUE.

Parameters:
blob The null value is supported.
Throws:
java.lang.IllegalStateException A container for the SQLExeption
java.lang.IndexOutOfBoundsException Length of the bytes is great than Integer.MAX_VALUE
    public static byte[] getBlobBytes(Blob blobthrows IllegalStateExceptionIndexOutOfBoundsException {
        try {
            if (blob==null) {
                return null;
            }
            if (blob.length() <= .) {
                return blob.getBytes(1, (intblob.length());
            }
        } catch (Exception e) {
            throw new IllegalStateException("Reding error"e);
        }
        throw new IndexOutOfBoundsException("Length of the result is great than Integer.MAX_VALUE");
    }

    
Returns a Blob byte array to the maximal length Integer.MAX_VALUE.

Throws:
java.lang.IllegalStateException A container for the SQLExeption
    public static InputStream getBlobStream(Blob blobthrows IllegalStateException {
        try {
            return blob.getBinaryStream();
        } catch (Exception e) {
            throw new IllegalStateException("Reding error"e);
        }
    }
    // --------------
    
Create a new Clob.

Parameters:
text The null value is supported.
    public static final SerialClob createClob(char[] text) {
        try {
            return text!=null ? new SerialClob(text) : null;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    
Create a new Clob.

Parameters:
text The null value is supported.
    public static SerialClob createClob(String text) {
        return text!=null ? createClob(text.toCharArray()) : null;
    }

    
Create a new Clob.
    public static SerialClob createClob(Reader reader) {
        try {
            char[] buffer = new char[1024];
            CharArrayWriter baos = new CharArrayWriter(buffer.length);
            int len;
            while ((len = reader.read(buffer)) >= 0) {
                baos.write(buffer, 0, len);
            }
            return new SerialClob(baos.toCharArray());
        } catch (Exception e) {
            throw new IllegalStateException("Reader error"e);
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                throw new IllegalStateException("Reader error"e);
            }
        }
    }

    
Returns a result to the maximal length Integer.MAX_VALUE.

Parameters:
clob The null value is supported.
Throws:
java.lang.IllegalStateException A container for the SQLExeption
java.lang.IndexOutOfBoundsException Length of the bytes is great than Integer.MAX_VALUE
    public static String getClobString(Clob clobthrows IllegalStateExceptionIndexOutOfBoundsException {
        try {
            if (clob==null) {
                return null;
            }
            if (clob.length() <= .) {
                return clob.getSubString(1, (intclob.length());
            }
        } catch (Exception e) {
            throw new IllegalStateException("Reding error"e);
        }
        throw new IndexOutOfBoundsException("Length of the result is great than Integer.MAX_VALUE");
    }

    
Returns a result to the maximal length Integer.MAX_VALUE.

Parameters:
clob The null value is supported
Throws:
java.lang.IllegalStateException A container for the SQLExeption
java.lang.IndexOutOfBoundsException Length of the bytes is great than Integer.MAX_VALUE
    public static char[] getClob(Clob clobthrows IllegalStateExceptionIndexOutOfBoundsException {
        return clob!=null ? getClobString(clob).toCharArray() : null;
    }

    
Load all lazy values for the current parameter.
    public static void loadLazyValues(OrmUjo ujo) {
        loadLazyValues(ujo, 1);
    }

    
Load all lazy values for the current parameter recursively until optional depth.

Parameters:
ujo The object must not be null.
depth The object depth.
    @SuppressWarnings("unchecked")
    public static void loadLazyValues(final OrmUjo ujoint depth) {
        if (--depth<0) {
            return;
        }
        for (Key p : ujo.readKeys()) {
            if (p.isTypeOf(OrmUjo.class)) {
                Object value = p.of(ujo);
                if (value!=null && depth>0) {
                    loadLazyValues((OrmUjovaluedepth);
                }
            }
        }
    }

    
Load all lazy values for the current parameter recursively until optional depth.

Parameters:
ujos The parameter can be the Query, UjoIterator and some List for example.
depth The object resursion depth.
Returns:
Returns a list of items or the parameter ujos. If the 'ujos' parameter is type of List, than method returns the parameter directly.
    public static <UJO extends OrmUjoList<UJO> loadLazyValues(final Iterable<UJO> ujosint depth) {
        List<UJO> result = ujos instanceof List
                ? null
                : new ArrayList<UJO>(64);
        for (UJO ujo : ujos) {
            loadLazyValues(ujodepth);
            if (result!=null) {
                result.add(ujo);
            }
        }
        if (result==null) {
            result = (List<UJO>) ujos;
        }
        return result;
    }

    
Reload values of the persistent object.
Note: If the object has implemented the interface ExtendedOrmUjo than foreign keys are reloaded, else a lazy initialization for first depth is done.

Parameters:
ujo The persistent object to relading values.
Returns:
The FALSE value means that the object is missing in the database.
See also:
org.ujorm.orm.Session.reload(org.ujorm.orm.OrmUjo)
    public boolean reload(final OrmUjo ujofinal Session session) {
        return session.reload(ujo);
    }

        
Load lazy value for all items and required keys by the one SQL statement.

Parameters:
ujos The parameter can be the Query, UjoIterator and some List for example.
Returns:
Returns a list of items or the parameter ujos. If the 'ujos' parameter is type of List, than method returns the parameter directly.
    @SuppressWarnings("unchecked")
    public static <UJO extends ExtendedOrmUjoList<UJO> loadLazyValuesAsBatch(final Iterable<UJO> ujosKey<UJO, ? extends OrmUjokey) {
        final List<UJO> result = new ArrayList<UJO>(ujos instanceof List ? ((Listujos).size() : 128);
        final HashMap<ObjectOrmUjomap = new HashMap<ObjectOrmUjo>(64);
        while (key.isComposite()) {
            key = ((CompositeKey)key).getFirstKey();
        }
        for (UJO u : ujos) {
            result.add(u);
            ForeignKey fk = u.readFK(key);
            if (fk!=null) {
                map.put(fk.getValue(), null);
            }
        }
        if (result.isEmpty()) {
            return result;
        }
        final Session session = result.get(0).readSession();
        final MetaColumn column = (MetaColumnsession.getHandler().findColumnModel(keytrue);
        final MetaColumn pkColumn = column.getForeignColumns().get(0);
        final Query<OrmUjoquery = session.createQuery(pkColumn.getTable().getType());
        final int limit = session.getParameters().get(.);
        final int count = map.size();
        final List<ObjectidList = new ArrayList(Math.min(limitcount));
        final Iterator<Objectkeys = map.keySet().iterator();
        for (int i = 1; i <= counti++) {
            idList.add(keys.next());
            if (i % limit == 0 || i == count) {
                query.setCriterion(Criterion.whereIn(pkColumn.getKey(), idList));
                for (OrmUjo u : query) {
                    map.put(pkColumn.getValue(u), u);
                }
                idList.clear();
            }
        }
        for (UJO u : result) {
            ForeignKey fk = u.readFK(key);
            if (fk!=null) {
                u.writeSession(null); // switch off the change management
                u.writeValue(keymap.get(fk.getValue()));
                u.writeSession(session);
            }
        }
        return result;
    }

    
Load lazy value for all items and all relation keys by the rule: a one SQL statement per relation key.

Parameters:
query An Ujorm query
Returns:
Returns a list of items or the parameter ujos. If the 'ujos' parameter is type of List, than method returns the parameter directly.
    @SuppressWarnings("unchecked")
    public static <UJO extends ExtendedOrmUjoList<UJO> loadLazyValuesAsBatch(final Query<UJO> query) {
        List<UJO> result = query.iterator().toList();
        List<MetaColumncolumns = ..getList(query.getTableModel());
        for (MetaColumn col : columns) {
            if (col.isForeignKey()) {
                loadLazyValuesAsBatch(resultcol.getKey());
            }
        }
        return result;
    }

    
Create new a Criterion. Both parameters are joined by the OR operator however if a one from data parameters is null, than the operator is ignored.

Parameters:
table NotNull
crn Nullable
foreighKeys Nullable
Returns:
NotNull
    public static Criterion createCriterion
            ( final MetaTable table
            , final Criterion crn
            , final List<ObjectprimaryKeys
            ) {
        Criterion result = crn;
        if (isFilled(primaryKeys)) {
            final MetaPKey pKey = ..of(table);
            if (pKey.getCount()!=1) {
                throw new IllegalStateException("There supported only objects with a one primary keys");
            }
            final Criterion c = pKey.getFirstColumn().getKey().whereIn(primaryKeys);
            result = result!=null ? result.or(c) : c;
        }
        return result!=null ? result : table.getFirstPK().getKey().forNone();
    }


    
Is the Text not null and not empty ?
    public static boolean isFilled(final CharSequence text) {
        return text!=null && text.length()>0;
    }

    
Is the Collection not null and not empty ?
    public static boolean isFilled(final Collection collection) {
        return collection!=null && !collection.isEmpty();
    }

    
Returns true, if the argument text is not null and not empty.
    public static boolean isFilled(final Object value) {
        final boolean result = value instanceof CharSequence
            ? isFilled((CharSequence)value)
            : value!=null
            ;
        return result;
    }

    
Clone the argument entity using all direct keys including the original ORM session, if any. All lazy relations will be loaded.
    public static <U extends Ujo> U clone(U entitythrows IllegalStateException {
        final KeyList<U> keys = entity.readKeys();
        final U result = keys.newBaseUjo();
        for (Key k : keys) {
            k.copy(entityresult);
        }
        if (entity instanceof OrmUjo) {
           ((OrmUjo)result).writeSession(((OrmUjo)entity).readSession());
        }
        return result;
    }
New to GrepCode? Check out our FAQ X