All Downloads are FREE. Search and download functionalities are using the official Maven repository.

redora.configuration.rdo.service.base.RedoraTrashServiceBase Maven / Gradle / Ivy

There is a newer version: 1.9.2
Show newest version
/*
* DO NOT CHANGE THIS FILE. Changes will be overwritten.
* -----------------------------------------------------
* This file is generated by Redora (www.redora.net) a source code generator.
* Copyright to this file belongs to You: the person or organization who has
* used Redora to generate this file.
* Redora is released under the open source Apache License, but this generated code
* can be released under any license or stay unreleased, as wished by the copyright
* owner.
* 
* Unless required by applicable law or agreed to in writing, this software
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND
* , either express or implied.
*/
package redora.configuration.rdo.service.base;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import redora.api.Persistable;
import redora.api.fetch.*;
import redora.exceptions.*;
import redora.service.*;
import redora.configuration.rdo.model.*;
import redora.configuration.rdo.model.fields.*;
import redora.configuration.rdo.service.*;


import static redora.configuration.rdo.sql.RedoraTrashSQL.*;
import static redora.configuration.rdo.businessrules.RedoraTrashBusinessRules.check;
import static java.util.logging.Level.FINE;
import static java.util.logging.Level.SEVERE;
import static redora.db.SQLParameter.*;

/**
* You can work with the pojo's using this service. For example if you create command line J2SE functionality
* or server side logic.
* If you want to use your data in a web application, you also might want to look at {@link RedoraTrashServiceJSON} * and {@link redora.configuration.rdo.service.http.RedoraTrashServlet}.
* Whenever business rule logic needs to be checked, it will go through here. For example a web user wants to persist * some data. He will post this for example as JSON to {@link redora.configuration.rdo.service.http.RedoraTrashServlet} * which in turn invokes {@link RedoraTrashServiceJSON} which will serialize the JSON stream into a pojo * and then will invoke the persist method of this service. * @author Redora (www.redora.net) */ public class RedoraTrashServiceBase extends ServiceBase { static final transient Logger l = Logger.getLogger("redora.configuration.rdo.service.RedoraTrashService"); /** * Don't use this directly but use the ServiceFactory instead: * * RedoraTrashService() myService = ServiceFactory.redoraTrash(); * ... do stuff * ServiceFactory.close(myService); * * Initializes RedoraTrashService. * @see redora.configuration.rdo.service.ServiceFactory */ protected RedoraTrashServiceBase() throws ConnectException { super("default"); } /** * Chains this service object to another service object. The database connection * and transaction is managed by the other service. * @param chain (Mandatory) Service you want to make this service dependent on. */ protected RedoraTrashServiceBase(@NotNull ServiceBase chain) { super(chain, "default"); inTransaction = true; //Let the calling service handle the transaction } /** * Simple finder to get RedoraTrash by it's id. * @param id (Mandatory) The primary key. * @param scope (Mandatory) The allowed fetch scope: Scope.Table, Scope.Form, Scope.List. * @return The desired RedoraTrash * @throws ObjectNotFoundException When there is no object in the DB with this Id. */ @NotNull public RedoraTrash findById(@NotNull Long id, @NotNull Scope scope) throws QueryException, CopyException, ObjectNotFoundException { RedoraTrash retVal = null; String SQL; switch (scope) { case Table: SQL = FIND_BY_ID_TABLE; break; case Form: SQL = FIND_BY_ID_FORM; break; case List: SQL = FIND_BY_ID_LIST; break; default: throw new IllegalArgumentException("Illegal scope for this finder: " + scope); } SQL = prepare(SQL, id); ResultSet rs = null; try { rs = sqlQuery(SQL); if (rs.next()) { retVal = new RedoraTrash(rs, 0, scope); } else { throw new ObjectNotFoundException("Could not find RedoraTrash " + id); } } catch(SQLException e) { l.log(SEVERE, "Failed to run query " + SQL, e); throw new QueryException("Failed to run query: " + SQL, e); } finally { close(rs); } return retVal; } /** * Finds records by custom SQL. Custom queries should be defined in the queries section in the model. * @param sql (Mandatory) The SQL statement you wish to use. See also RedoraTrashSQL. * @param params (Optional) List of parameters. When omitted it is assumed there are no parameters. * @param page (Mandatory) The Page strategy. Allowed scopes are: Scope.Table, Scope.Form, Scope.List, Scope.Lazy. * @return Empty or filled list with RedoraTrash */ @NotNull public List find(@NotNull String sql, @Nullable List params, @NotNull Page page) throws QueryException, CopyException, PagingException { List retVal = new ArrayList(); String SQL = sql; if (params != null) { for (Object param : params) { SQL = prepare(SQL, param); } } SQL = preparePage(SQL, page); ResultSet rs = null; try { rs = sqlQuery(SQL); while (rs.next()) { retVal.add(new RedoraTrash(rs, 0, page.getScope())); } } catch(SQLException e) { l.log(SEVERE, "Failed to run query: " + SQL, e); throw new QueryException("Failed to run query: " + SQL, e); } finally { close(rs); } return retVal; } @NotNull public List finder(DefaultFinder finder, Object param, Page page) throws QueryException, CopyException, PagingException { if (!(page.getScope() == Scope.List || page.getScope() == Scope.Table)) { throw new PagingException("Illegal scope (" + page.getScope() + ") for this finder: " + finder); } String SQL = page.getScope() == Scope.Table ? finder.sqlTable : finder.sqlList; if (param instanceof List) { return find(page.getScope() == Scope.Table ? finder.sqlTable : finder.sqlList, (List)param, page); } else if (finder != DefaultFinder.FindAll) { SQL = prepare(SQL, param); } return find(SQL, null, page); } /** * Finds All records * @param page (Mandatory) The Page strategy. The allowed fetch scopes are: Scope.Table and Scope.List. * @return Empty or filled list with RedoraTrash */ @NotNull public List findAll(@NotNull Page page) throws QueryException, CopyException, PagingException { return finder(DefaultFinder.FindAll, null, page); } /** * @param page (Mandatory) Allowed: Scope.Table, Scope.List. * @return Empty or filled list */ @NotNull public List findByObjectId(@NotNull Long finder, @NotNull Page page) throws QueryException, CopyException, PagingException { if (!(page.getScope() == Scope.List || page.getScope() == Scope.Table)) { throw new PagingException("Illegal scope: " + page.getScope()); } List retVal = new ArrayList(); String SQL = page.getScope() == Scope.Table ? FIND_BY_OBJECT_ID_ID_TABLE : FIND_BY_OBJECT_ID_ID_LIST; SQL = prepare(SQL, finder); SQL = preparePage(SQL, page); ResultSet rs = null; try { rs = sqlQuery(SQL); while (rs.next()) { retVal.add(new RedoraTrash(rs, 0, page.getScope())); } } catch(SQLException e) { l.log(SEVERE, "Failed to run query " + SQL, e); throw new QueryException("Failed to run query: " + SQL, e); } finally { close(rs); } return retVal; } /** * @param page (Mandatory) Allowed: Scope.Table, Scope.List. * @return Empty or filled list */ @NotNull public List findByUndoHash(@NotNull String finder, @NotNull Page page) throws QueryException, CopyException, PagingException { if (!(page.getScope() == Scope.List || page.getScope() == Scope.Table)) { throw new PagingException("Illegal scope: " + page.getScope()); } List retVal = new ArrayList(); String SQL = page.getScope() == Scope.Table ? FIND_BY_UNDO_HASH_ID_TABLE : FIND_BY_UNDO_HASH_ID_LIST; SQL = prepareDirty(SQL, finder); SQL = preparePage(SQL, page); ResultSet rs = null; try { rs = sqlQuery(SQL); while (rs.next()) { retVal.add(new RedoraTrash(rs, 0, page.getScope())); } } catch(SQLException e) { l.log(SEVERE, "Failed to run query " + SQL, e); throw new QueryException("Failed to run query: " + SQL, e); } finally { close(rs); } return retVal; } /** * @param page (Mandatory) Allowed: Scope.Table, Scope.List. * @return Empty or filled list */ @NotNull public List findByUserId(@NotNull Long finder, @NotNull Page page) throws QueryException, CopyException, PagingException { if (!(page.getScope() == Scope.List || page.getScope() == Scope.Table)) { throw new PagingException("Illegal scope: " + page.getScope()); } List retVal = new ArrayList(); String SQL = page.getScope() == Scope.Table ? FIND_BY_USER_ID_ID_TABLE : FIND_BY_USER_ID_ID_LIST; SQL = prepare(SQL, finder); SQL = preparePage(SQL, page); ResultSet rs = null; try { rs = sqlQuery(SQL); while (rs.next()) { retVal.add(new RedoraTrash(rs, 0, page.getScope())); } } catch(SQLException e) { l.log(SEVERE, "Failed to run query " + SQL, e); throw new QueryException("Failed to run query: " + SQL, e); } finally { close(rs); } return retVal; } /** * Inserts or updates a collection of RedoraTrash. * Collections associated to RedoraTrash are persisted as well. * JDBC batch update is used to improve performance. * NOTE that this method assumes you already checked if given RedoraTrashes * have changed and if they did not violate any business rules. * @param pojos List of pojo objects you want to persist * @return Empty or filled list with violations. Note that (at least the unique * key) is only evaluated in the database. */ @NotNull public Set persist(@NotNull Collection pojos) throws RedoraException { Set retVal = new HashSet(); boolean transact = !inTransaction; if (transact) { beginTransaction(); } try { for (RedoraTrash pojo : pojos) retVal.addAll(persist(pojo)); } catch (RedoraException e) { if (transact) { transact = false; rollback(); } throw e; } finally { if (transact) if (retVal.isEmpty()) commit(); else rollback(); } return retVal; } /** * Inserts or updates RedoraTrash. Collections associated to RedoraTrash are persisted as well. * @param pojo (Mandatory) Object you want to persist * @return Empty list when OK, else a list of violations. */ @NotNull public Set persist(@NotNull RedoraTrash pojo) throws RedoraException { if (!pojo.isDirty()) { return new HashSet(); } Set br = check(pojo, pojo.isNew ? BusinessRuleViolation.Action.Insert : BusinessRuleViolation.Action.Update); if (!br.isEmpty()) { return br; } return persist(pojo, false); } /** * Persists the changes of RedoraTrash to the database and also any changed related children. * Business rules are not checked, that is why this method is protected. However, unique key * constrains are checked in the database, so this type of business rule is checked. * When a unique key constraint is violated, the transaction is rolled back and a BusinessRuleViolation * with the violating attribute is returned. If you have set up a transaction yourself (with service.beginTransaction()), * you are supposed to rollback (or commit) yourself.
* The persist function 'knows' the changes in RedoraTrash because of the dirty set in this * object. All the setters in RedoraTrash will set the object to dirty when they notice a change * in value.
* @see #soloPersist(RedoraTrash) * @param asBatch Set to true if you want to execute the statements outside this method. You need to invoke ps.executeBatch() yourself. * @return Empty when OK or filled with a unique key constraint violation * @throws PersistException When the action through JDBC / DB has an unexpected problem. */ @NotNull protected Set persist(@NotNull RedoraTrash pojo, boolean asBatch) throws RedoraException { l.log(FINE, "Updating {0}", pojo.getId()); if (pojo.fetchScope == Scope.List) { throw new PersistException("Modification is not allowed, this object is fetched as Scope.List and cannot be persisted. Fetch the object with Table or Form scope instead."); } final boolean isNew = pojo.isNew; Set retVal = null; retVal = soloPersist(pojo); return retVal; } /** * Persists RedoraTrash only. Ignores the children. Does not perform business rule * violation checking. So, know what you are doing when using this. * @param pojo Object you'd wish persisted * @return Empty when OK, or filled with unique key violation. */ @NotNull public Set soloPersist(@NotNull RedoraTrash pojo) throws RedoraException { Set retVal = new HashSet(); if (!pojo.dirty.isEmpty() || pojo.isNew) { String SQL; if (pojo.isNew) { pojo.dirty.put(RedoraTrashFields.creationDate, null); pojo.creationDate = new Date((new Date().getTime()/1000)*1000); //Strip nanoseconds, they are not persisted in MySQL StringBuilder sqlInsert = new StringBuilder("insert into `RedoraTrash` ("); char comma = ' '; for (RedoraTrashFields field : pojo.dirty.keySet()) { sqlInsert.append(comma); sqlInsert.append(field.name()); comma = ','; } sqlInsert.append(") values ("); comma = ' '; for (int i = 0; i < pojo.dirty.size(); i++) { sqlInsert.append(comma); sqlInsert.append('?'); comma = ','; } sqlInsert.append(')'); SQL = sqlInsert.toString(); } else { pojo.dirty.put(RedoraTrashFields.updateDate, pojo.updateDate); pojo.updateDate = new Date((new Date().getTime()/1000)*1000); //Strip nanoseconds, they are not persisted in MySQL StringBuilder sqlUpdate = new StringBuilder("update `RedoraTrash` set "); char comma = ' '; for (RedoraTrashFields field : pojo.dirty.keySet()) { sqlUpdate.append(comma); sqlUpdate.append(field.name()).append("=?"); comma = ','; } sqlUpdate.append(" where id=?"); SQL = sqlUpdate.toString(); } for (RedoraTrashFields field : pojo.dirty.keySet()) { switch (field) { case updateDate: SQL = prepareTime(SQL, pojo.updateDate); break; case creationDate: SQL = prepareTime(SQL, pojo.creationDate); break; case objectId: SQL = prepare(SQL, pojo.objectId); break; case undoHash: SQL = prepareDirty(SQL, pojo.undoHash); break; case objectName: SQL = prepareDirty(SQL, pojo.objectName); break; case userId: if (pojo.userId == null) { SQL = prepareNull(SQL); } else { SQL = prepare(SQL, pojo.userId); } break; } //switch } ResultSet rs = null; try { if (pojo.isNew) { st.st.execute(SQL, java.sql.Statement.RETURN_GENERATED_KEYS); if (st.st.getWarnings() != null) { throw new PersistException("RedoraTrash was not persisted " + st.st.getWarnings().getMessage()); } rs = st.st.getGeneratedKeys(); rs.next(); pojo.id = rs.getLong(1); } else { SQL = prepare(SQL, pojo.getId()); execute(SQL); } pojo.dirty.clear(); pojo.isNew = false; } catch (MySQLIntegrityConstraintViolationException e) { int start = e.toString().indexOf("for key '"); if (start > 0) { String indexName = e.toString().substring(start + 9); indexName = indexName.substring(0, indexName.indexOf("'")); retVal.add(new BusinessRuleViolation( pojo, RedoraTrashFields.valueOf(uniqueKeyAttribute("RedoraTrash", indexName)), BusinessRuleViolation.StandardRule.UniqueKey.ruleId, pojo.getId() == null?BusinessRuleViolation.Action.Insert:BusinessRuleViolation.Action.Update) ); } else { retVal.add(new BusinessRuleViolation( pojo, null, BusinessRuleViolation.StandardRule.UniqueKey.ruleId, pojo.getId() == null?BusinessRuleViolation.Action.Insert:BusinessRuleViolation.Action.Update) ); } } catch(SQLException e) { l.log(SEVERE, "Failed to perform persist: " + SQL, e); throw new PersistException("Failed to perform persist: " + SQL, e); } finally { close(rs); } } return retVal; } /** * Deletes RedoraTrash. * Collections associated to RedoraTrash are deleted as well when cascade delete is indicated. * @param pojo (Mandatory) RedoraTrash you want to delete. * @return Empty when OK, or filled set with violated business rules * @throws ObjectNotFoundException when RedoraTrash has no id (was never persisted). */ @NotNull public Set delete(@NotNull RedoraTrash pojo) throws RedoraException { if (pojo.getId() == null) { throw new ObjectNotFoundException("You are trying to delete a RedoraTrash that is not in the database"); } Set br = check(pojo, BusinessRuleViolation.Action.Delete); if (br.isEmpty()) { delete(pojo, false); } return br; } /** Deletes RedoraTrash without checking on business rule violations. */ protected void delete(RedoraTrash pojo, boolean asBatch) throws QueryException { l.log(FINE, "Deleting {0}", pojo.getId()); String SQL = prepare(DELETE, pojo.getId()); execute(SQL); } /** * Simple test method. It will dump the results of findAll to System.out * @param args Unused * @throws RedoraException Passing on */ public static void main(String[] args) throws RedoraException { RedoraTrashService _redoraTrashService = ServiceFactory.redoraTrashService(); for (RedoraTrash testRecord : _redoraTrashService.findAll(new Page(Scope.Table, Mode.Page, 100))) { if (testRecord.objectId != null) { System.out.print(testRecord.objectId); } else { System.out.print("NULL"); } System.out.print("-"); if (testRecord.undoHash != null) { System.out.print(testRecord.undoHash); } else { System.out.print("NULL"); } System.out.print("-"); if (testRecord.objectName != null) { System.out.print(testRecord.objectName); } else { System.out.print("NULL"); } System.out.print("-"); if (testRecord.userId != null) { System.out.print(testRecord.userId); } else { System.out.print("NULL"); } System.out.print("-"); System.out.println(); } ServiceFactory.close(_redoraTrashService); } }