View Javadoc
1   package uk.ac.ebi.intenz.webapp.controller.modification;
2   
3   import java.sql.Connection;
4   import java.sql.SQLException;
5   import java.util.GregorianCalendar;
6   
7   import javax.servlet.http.HttpServletRequest;
8   import javax.servlet.http.HttpServletResponse;
9   
10  import org.apache.log4j.Logger;
11  import org.apache.struts.action.ActionForm;
12  import org.apache.struts.action.ActionForward;
13  import org.apache.struts.action.ActionMapping;
14  import org.apache.struts.action.ActionMessage;
15  import org.apache.struts.action.ActionMessages;
16  
17  import uk.ac.ebi.intenz.domain.constants.Status;
18  import uk.ac.ebi.intenz.domain.enzyme.EnzymeEntry;
19  import uk.ac.ebi.intenz.domain.exceptions.DomainException;
20  import uk.ac.ebi.intenz.domain.exceptions.EcException;
21  import uk.ac.ebi.intenz.mapper.AuditPackageMapper;
22  import uk.ac.ebi.intenz.mapper.EnzymeEntryMapper;
23  import uk.ac.ebi.intenz.mapper.EventPackageMapper;
24  import uk.ac.ebi.intenz.mapper.HistoryEventMapper;
25  import uk.ac.ebi.intenz.webapp.dtos.EcSearchForm;
26  import uk.ac.ebi.intenz.webapp.dtos.EnzymeDTO;
27  import uk.ac.ebi.intenz.webapp.utilities.EntryLockSingleton;
28  import uk.ac.ebi.intenz.webapp.utilities.UnitOfWork;
29  import uk.ac.ebi.rhea.mapper.MapperException;
30  
31  /**
32   * This Action updates information of a transferred entry.
33   *
34   * This Action is invoked whenever a transferred entry is modified regardless of its status. It takes care of all
35   * changes of the enzyme's data (actually done by {@link uk.ac.ebi.intenz.webapp.utilities.UnitOfWork}) and updates
36   * the transfer events data, i.e. the history line and status of the deleted entry.
37   *
38   * @author Michael Darsow
39   * @version $Revision: 1.3 $ $Date: 2008/11/17 17:14:10 $
40   */
41  public class TransferEntryUpdateAction extends CurationAction {
42    private static final Logger LOGGER =
43  	  Logger.getLogger(TransferEntryUpdateAction.class.getName());
44    private static final String SEARCH_BY_EC_ACTION_FWD = "searchEc";
45  
46    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
47                                 HttpServletResponse response) throws Exception {
48      // Do standard checks in the parent's execute method.
49      ActionForward forward = super.execute(mapping, form, request, response);
50      if (forward != null) return forward;
51  
52      ActionMessages errors = new ActionMessages();
53      EnzymeDTO enzymeDTO = (EnzymeDTO) form;
54  
55      // Validate the entry's lists.
56  //    IntEnzValidations.validateEnzymeDTOLists(enzymeDTO, errors);
57  //    if (!errors.isEmpty()) {
58  //      saveErrors(request, errors);
59  //      return mapping.getInputForward();
60  //    }
61      
62      Connection con = (Connection) request.getSession().getAttribute("connection");
63      EntryLockSingleton els = (EntryLockSingleton) request.getSession().getServletContext().getAttribute("entryLock");
64      UnitOfWork unitOfWork = (UnitOfWork) request.getSession().getAttribute("uow");
65      try {
66      	/*
67          if (!enzymeDTO.isActive()){
68  		  EnzymeCommissionNumber targetEc = EnzymeCommissionNumber
69  				  .valueOf(enzymeDTO.getTransferredToEc());
70  		  EnzymeEntry targetEntry = new EnzymeEntryMapper().findByEc(
71  				  targetEc.getEc1(), targetEc.getEc2(),
72  				  targetEc.getEc3(), targetEc.getEc4(),
73  				  Status.APPROVED, con);
74  		  if (targetEntry == null){
75  		      errors.add("transferredToEc", new ActionMessage(
76  		    		  "errors.application.ec.nonexisting", targetEc));
77  		      saveErrors(request, errors);
78  		      keepToken(request);
79  		      return mapping.getInputForward();
80  		  } else if (!targetEntry.isActive()){
81  		      errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
82  		    		  "errors.application.ec.inactive", targetEc));
83  		      saveErrors(request, errors);
84  		      keepToken(request);
85  		      return mapping.getInputForward();
86  		  }
87          }
88  		*/
89          // Set the standard remark in the audit tables.
90        AuditPackageMapper auditPackageMapper = new AuditPackageMapper();
91        auditPackageMapper.setRemark(AuditPackageMapper.STANDARD_REMARK, con);
92        // Commit
93        LOGGER.info("Committing form data.");
94        unitOfWork.commit(enzymeDTO, con);
95        LOGGER.info("Data subimtted");
96  
97        if (enzymeDTO.isActive()){
98            // Store event.
99            LOGGER.info("Updating event.");
100           final String historyLine = updateHistoryLineOfDeletedEntry(
101         		  new Long(enzymeDTO.getLatestHistoryBeforeId()), con);
102           EventPackageMapper eventPackageMapper = new EventPackageMapper();
103           eventPackageMapper.updateFutureTransferEvent(
104         		  Integer.parseInt(enzymeDTO.getLatestHistoryEventGroupId()),
105         		  Integer.parseInt(enzymeDTO.getLatestHistoryEventId()),
106         		  enzymeDTO.getLatestHistoryEventNote(), enzymeDTO.getStatusCode(),
107         		  historyLine, con);
108       } else {
109     	  // Modifying notes of already deleted/transferred entry:
110     	  Integer afterId = null;
111     	  if (enzymeDTO.getTransferredToEc() != null){
112     		  EnzymeEntry targetEntry = new EnzymeEntryMapper().findByEc(
113     				  enzymeDTO.getTransferredToEc(), Status.APPROVED, con);
114     		  afterId = targetEntry.getId().intValue();
115     	  }
116     	  HistoryEventMapper hem = new HistoryEventMapper();
117 //    	  hem.updateEventNote(Integer.valueOf(enzymeDTO.getLatestHistoryEventId()),
118 //    			  Integer.valueOf(enzymeDTO.getLatestHistoryEventGroupId()),
119 //    			  enzymeDTO.getLatestHistoryEventNote(), con);
120     	  hem.updateEvent(Integer.valueOf(enzymeDTO.getLatestHistoryEventId()),
121     			  Integer.valueOf(enzymeDTO.getLatestHistoryEventGroupId()),
122 				  enzymeDTO.getLatestHistoryEventNote(),
123 				  Integer.valueOf(enzymeDTO.getId()), afterId, con);
124       }
125       con.commit();
126 
127       LOGGER.info("Transfer event updated.");
128     } catch (EcException e) {
129       errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.application.ec.invalid", enzymeDTO.getTransferredEc()));
130       saveErrors(request, errors);
131       keepToken(request);
132       return mapping.getInputForward();
133     } catch (Exception e){
134         con.rollback();
135         throw e;
136     } finally { // release lock
137       els.releaseLock(enzymeDTO.getId());
138       LOGGER.info("Lock of EC " + enzymeDTO.getEc() + " (ID: " + enzymeDTO.getEc() + " released.");
139     }
140 
141     // Forward to 'searchEc' Action to show both entries.
142     LOGGER.info("Searching for EC " + enzymeDTO.getEc());
143     EcSearchForm ecSearchForm = new EcSearchForm();
144     ecSearchForm.setEc(enzymeDTO.getEc());
145     request.setAttribute("ecSearchForm", ecSearchForm);
146     return mapping.findForward(SEARCH_BY_EC_ACTION_FWD);
147   }
148 
149   /**
150    * Updates the history line of the deleted entry by extending it with <b>', deleted <current year>'</b> (e.g.
151    * <b>', deleted 2005'</b>
152    *
153    * @param beforeId The ID of the deleted enzyme.
154    * @param con A databse connection to retreive the deleted enzyme's history line.
155    * @return the updated history line.
156    * @throws SQLException if a database error occurs.
157    * @throws DomainException if a domain related error occurs.
158    * @throws MapperException
159    */
160   private String updateHistoryLineOfDeletedEntry(Long beforeId, Connection con)
161   throws SQLException, DomainException, MapperException {
162     assert beforeId != null : "Parameter 'beforeId' must not be null.";
163     assert con != null : "Parameter 'con' must not be null.";
164     EnzymeEntryMapper enzymeEntryMapper = new EnzymeEntryMapper();
165     EnzymeEntry enzymeEntry = enzymeEntryMapper.findById(beforeId, con);
166     return getNewHistoryLine(enzymeEntry.getHistory().getRootNode().getHistoryLine());
167   }
168 
169   /**
170    * Gets the new history line by appending <b>', deleted <current year>'</b>.
171    *
172    * @param oldHistory The enzyme's old history line.
173    * @return the new history line.
174    */
175   private String getNewHistoryLine(String oldHistory) {
176     assert oldHistory != null : "Parameter 'oldHistory' must not be null.";
177     GregorianCalendar gc = new GregorianCalendar();
178     int year = gc.get(GregorianCalendar.YEAR);
179     StringBuffer historyLine = new StringBuffer();
180     historyLine.append(oldHistory);
181     historyLine.append(", deleted ");
182     historyLine.append(year);
183     return historyLine.toString();
184   }
185 
186 }