Example usage for java.lang Integer equals

List of usage examples for java.lang Integer equals

Introduction

In this page you can find the example usage for java.lang Integer equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object to the specified object.

Usage

From source file:com.lp.server.personal.ejbfac.ZutrittscontrollerFacBean.java

public void updateZutrittsobjekt(ZutrittsobjektDto zutrittsobjektDto) throws EJBExceptionLP {
    if (zutrittsobjektDto == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DTO_IS_NULL, new Exception("zutrittsobjektDto == null"));
    }//from www .  j  av  a2 s .  c  o  m
    if (zutrittsobjektDto.getIId() == null || zutrittsobjektDto.getCNr() == null
            || zutrittsobjektDto.getZutrittscontrollerIId() == null || zutrittsobjektDto.getCRelais() == null
            || zutrittsobjektDto.getFOeffnungszeit() == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FELD_IN_DTO_IS_NULL, new Exception(
                "zutrittsobjektDto.getIId() == null || zutrittsobjektDto.getCNr() == null || zutrittsobjektDto.getZutrittscontrollerIId() == null || zutrittsobjektDto.getCAnschluss() == null || zutrittsobjektDto.getFOeffnungszeit() == null"));
    }

    Integer iId = zutrittsobjektDto.getIId();
    // try {
    Zutrittsobjekt zutrittsobjekt = em.find(Zutrittsobjekt.class, iId);
    if (zutrittsobjekt == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY, "");
    }

    try {
        Query query = em.createNamedQuery("ZutrittsobjektfindByCNr");
        query.setParameter(1, zutrittsobjektDto.getCNr());
        Integer iIdVorhanden = ((Zutrittsobjekt) query.getSingleResult()).getIId();
        if (iId.equals(iIdVorhanden) == false) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DUPLICATE_UNIQUE,
                    new Exception("PERS_ZUTRITTSOBJEKT.CNR"));
        }
    } catch (NoResultException ex) {
        // nothing here
    } catch (NonUniqueResultException ex1) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_NO_UNIQUE_RESULT, ex1);
    }

    setZutrittsobjektFromZutrittsobjektDto(zutrittsobjekt, zutrittsobjektDto);
    // }
    // catch (FinderException ex) {
    // throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY,
    // ex);
    // }

}

From source file:com.lp.server.personal.ejbfac.ZutrittscontrollerFacBean.java

public void updateZutrittsklasse(ZutrittsklasseDto zutrittsklasseDto) throws EJBExceptionLP {
    if (zutrittsklasseDto == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DTO_IS_NULL, new Exception("zutrittsklasseDto == null"));
    }/*from   ww  w.j a  v  a2 s. com*/
    if (zutrittsklasseDto.getIId() == null || zutrittsklasseDto.getCNr() == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FELD_IN_DTO_IS_NULL,
                new Exception("zutrittsklasseDto.getIId() == null || zutrittsklasseDto.getCNr() == null"));
    }
    if (zutrittsklasseDto.getCNr().equals(ZutrittscontrollerFac.ZUTRITTSKLASSE_ONLINECHECK)) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DUPLICATE_UNIQUE,
                new Exception("Zutrittsklasse 'ONL' darf nicht agelegt werden"));

    }

    Integer iId = zutrittsklasseDto.getIId();
    // try {
    Zutrittsklasse zutrittsklasse = em.find(Zutrittsklasse.class, iId);
    if (zutrittsklasse == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY, "");
    }

    try {
        Query query = em.createNamedQuery("ZutrittsklassefindByCNr");
        query.setParameter(1, zutrittsklasseDto.getCNr());
        Integer iIdVorhanden = ((Zutrittsklasse) query.getSingleResult()).getIId();
        if (iId.equals(iIdVorhanden) == false) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DUPLICATE_UNIQUE,
                    new Exception("PERS_ZUTRITTSKLASSE.C_NR"));
        }
    } catch (NoResultException ex) {
        // nothing here
    } catch (NonUniqueResultException ex1) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_NO_UNIQUE_RESULT, ex1);
    }

    setZutrittsklasseFromZutrittsklasseDto(zutrittsklasse, zutrittsklasseDto);
    // }
    // catch (FinderException ex) {
    // throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY,
    // ex);
    // }

}

From source file:com.aurel.track.exchange.excel.ExcelImportBL.java

/**
 * Return the lookup objectID based in the label
 * /* w  w w . j a v  a  2 s. c om*/
 * @param stringValue
 * @param fieldTypeRT
 * @param fieldID
 * @param systemLookups
 * @param projectSpecificLookups
 * @param serializableBeanAllowedContext
 * @param componentPartsMap
 * @param invalidValueHandlingMap
 * @param locale
 * @return
 * @throws ExcelImportNotExistingCellValueException
 * @throws ExcelImportNotAllowedCellValueException
 * @throws ExcelImportException
 */
private static Integer getWatcherValue(String stringValue, Integer fieldID,
        Map<Integer, Map<String, ILabelBean>> systemLookups, List<Integer> watcherListOriginal,
        SerializableBeanAllowedContext serializableBeanAllowedContext, Locale locale)
        throws ExcelImportNotExistingCellValueException, ExcelImportNotAllowedCellValueException {
    if (stringValue != null && !"".equals(stringValue)) {
        Integer projectID = serializableBeanAllowedContext.getProjectID();
        Integer itemTypeID = serializableBeanAllowedContext.getIssueTypeID();
        ILookup lookup = new SystemManagerRT();
        // Integer lookupKey = lookup.getDropDownMapFieldKey(fieldID);
        Map<String, ILabelBean> lookupBeansMap = null;
        // try to find the objectID from dropDownContainer, to avoid to go
        // to database for each entry in turn
        lookupBeansMap = systemLookups.get(SystemFields.INTEGER_PERSON);
        String trimmedString = stringValue.trim();
        // first try to match the trimmed string values
        Integer objectIDByLabel = lookup.getLookupIDByLabel(fieldID, projectID, itemTypeID, locale,
                trimmedString, lookupBeansMap, null);
        if (objectIDByLabel == null) {
            // now try the original (non trimmed) value also
            stringValue = stringValue.trim();
            objectIDByLabel = lookup.getLookupIDByLabel(fieldID, projectID, itemTypeID, locale, stringValue,
                    lookupBeansMap, null);
        }
        if (objectIDByLabel == null) {
            // lookup entity does not exist
            LOGGER.debug("The value " + stringValue + " does not exist for field " + fieldID);
            throw new ExcelImportNotExistingCellValueException(stringValue);
        } else {
            if (watcherListOriginal != null && watcherListOriginal.contains(objectIDByLabel)) {
                return objectIDByLabel;
            }
            int accessFlag;
            if (fieldID.equals(TReportLayoutBean.PSEUDO_COLUMNS.INFORMANT_LIST)) {
                accessFlag = AccessFlagIndexes.INFORMANT;
            } else {
                accessFlag = AccessFlagIndexes.CONSULTANT;
            }
            boolean allowed = AccessBeans.hasPersonRightInProjectForIssueType(objectIDByLabel, projectID,
                    itemTypeID, accessFlag, false, false);
            if (allowed) {
                return objectIDByLabel;
            } else {
                LOGGER.debug("The value " + stringValue + " is not allowed for field " + fieldID);
                // /throw an exception only if the not allowed value not
                // exist already
                throw new ExcelImportNotAllowedCellValueException(stringValue);
            }
        }
    }
    return null;
}

From source file:com.lp.server.personal.ejbfac.ZutrittscontrollerFacBean.java

public void updateZutrittscontroller(ZutrittscontrollerDto zutrittscontrollerDto) throws EJBExceptionLP {
    if (zutrittscontrollerDto == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DTO_IS_NULL,
                new Exception("zutrittscontrollerDto == null"));
    }//from   w  ww. j a  v  a 2 s .  c  o  m
    if (zutrittscontrollerDto.getIId() == null || zutrittscontrollerDto.getCBez() == null
            || zutrittscontrollerDto.getCAdresse() == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FELD_IN_DTO_IS_NULL, new Exception(
                "zutrittscontrollerDto.getIId() == null || zutrittscontrollerDto.getCBez() == null || zutrittscontrollerDto.getCAdresse() == null"));
    }

    Integer iId = zutrittscontrollerDto.getIId();
    // try {
    Zutrittscontroller zutrittscontroller = em.find(Zutrittscontroller.class, iId);
    if (zutrittscontroller == null) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY, "");
    }

    try {
        Query query = em.createNamedQuery("ZutrittscontrollerfindByCNr");
        query.setParameter(1, zutrittscontrollerDto.getCNr());
        Integer iIdVorhanden = ((Zutrittscontroller) query.getSingleResult()).getIId();
        if (iId.equals(iIdVorhanden) == false) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_DUPLICATE_UNIQUE,
                    new Exception("PERS_ZUTRITTSCONTROLLER.C_NR"));
        }
    } catch (NoResultException ex) {
        // nothing here
    } catch (NonUniqueResultException ex1) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_NO_UNIQUE_RESULT, ex1);
    }

    setZutrittscontrollerFromZutrittscontrollerDto(zutrittscontroller, zutrittscontrollerDto);
    // }
    // catch (FinderException ex) {
    // throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEI_FINDBYPRIMARYKEY,
    // ex);
    // }

}

From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java

/**
 * This Method imports the database components for the actual unitid given in the edition. <br>
 * Will be called from liveserver ONLY. (currently)
 * /*from  w  ww .  java  2 s  .  c  o m*/
 * @throws UserException
 * 
 * @see de.juwimm.cms.remote.EditionServiceSpring#importDatabaseComponents(org.w3c.dom.Element, de.juwimm.cms.model.UnitHbm, boolean)
 */
protected void importDatabaseComponents(org.w3c.dom.Element unitElm, de.juwimm.cms.model.UnitHbm unit,
        boolean useNewIds) throws Exception {
    if (log.isInfoEnabled())
        log.info("begin importDatabaseComponents for unit: " + unit.getName());
    // if (!context.getRollbackOnly()) {
    try {
        if (unitElm != null) {
            Integer unitIdFromEdition = new Integer(unitElm.getAttribute("id"));
            // old IDs and same unitId
            if (!useNewIds && unitIdFromEdition.equals(unit.getUnitId())) {
                /*
                 * If no new IDs, this will be a deploy. In other cases we already have deleted the complete site and setted the unitLogo
                 */
                try {
                    unit.setImageId(new Integer(unitElm.getAttribute("imageId")));
                } catch (Exception exe) {
                    if (log.isDebugEnabled())
                        log.debug("Unit " + unit.getName() + " has no Image: " + exe.getMessage());
                }
                try {
                    unit.setLogoId(new Integer(unitElm.getAttribute("logoId")));
                } catch (Exception exe) {
                    if (log.isDebugEnabled())
                        log.debug("Unit " + unit.getName() + " has no Logo: " + exe.getMessage());
                }

                if (log.isDebugEnabled())
                    log.debug("DELETING CURRENT ADDRESSES");
                Collection cAddresses = unit.getAddresses();
                getAddressHbmDao().remove(cAddresses);

                if (log.isDebugEnabled())
                    log.debug("DELETING CURRENT PERSONS");
                Collection<PersonHbm> persons = getPersonHbmDao().findByUnit(unit.getUnitId());
                getPersonHbmDao().remove(persons);

                if (log.isDebugEnabled())
                    log.debug("DELETING CURRENT DEPTS");
                Collection cDepartments = unit.getDepartments();
                getDepartmentHbmDao().remove(cDepartments);

                if (log.isDebugEnabled())
                    log.debug("DELETING CURRENT TTIMES");
                Collection<TalktimeHbm> talktimes = getTalktimeHbmDao().findByUnit(unit.getUnitId());
                getTalktimeHbmDao().remove(talktimes);
            }
            // old IDs and same unitID or new IDs and id == oldId from mapping
            if ((!useNewIds && unitIdFromEdition.equals(unit.getUnitId()))
                    || (useNewIds && unitIdFromEdition.equals(mappingUnitsReverse.get(unit.getUnitId())))) {
                if (log.isDebugEnabled())
                    log.debug("adding current ADDRESSES");
                Iterator itAdr = XercesHelper.findNodes(unitElm, "./address");
                while (itAdr.hasNext()) {
                    Element adrEl = (Element) itAdr.next();
                    AddressHbm address = createAddressHbm(adrEl, useNewIds, mappingAddresses);
                    unit.getAddresses().add(address);
                }
                if (log.isDebugEnabled())
                    log.debug("adding current PERSONS");
                Iterator<Element> itPers = XercesHelper.findNodes(unitElm, "./person");
                while (itPers.hasNext()) {
                    if (log.isDebugEnabled())
                        log.debug("found person to import");
                    Element elm = itPers.next();
                    createPersonHbm(unit, elm, useNewIds, mappingPersons, mappingAddresses, mappingTalktime);
                }
                if (log.isDebugEnabled())
                    log.debug("adding current DEPTS");
                Iterator itDepts = XercesHelper.findNodes(unitElm, "./department");
                while (itDepts.hasNext()) {
                    Element elm = (Element) itDepts.next();
                    DepartmentHbm department = createDepartmentHbm(elm, useNewIds, mappingDepartments,
                            mappingPersons, mappingAddresses, mappingTalktime);
                    department.setUnit(unit);
                    unit.getDepartments().add(department);
                }
                if (log.isDebugEnabled())
                    log.debug("adding current TTIMES");
                Iterator<Element> itTTimes = XercesHelper.findNodes(unitElm, "./talktime");
                while (itTTimes.hasNext()) {
                    Element elm = itTTimes.next();
                    TalktimeHbm talktime = createTalktimeHbm(elm, useNewIds, mappingTalktime);
                    talktime.setUnit(unit);
                }
            }
        } else {
            if (log.isDebugEnabled())
                log.debug(
                        "importDatabaseComponents reports: There are no /edition/units/unit nodes, so nothing to do");
        }
    } catch (Exception exe) {
        // context.setRollbackOnly();
        log.error("Error occured importDatabaseComponents", exe);
    }
    // }
    if (log.isInfoEnabled())
        log.info("end importDatabaseComponents for unit: " + unit.getName());

}

From source file:edu.ku.brc.specify.conversion.ConvertVerifier.java

/**
 * @param oldNewIdStr//from w  ww.  ja va2 s  .c o  m
 * @throws SQLException
 */
private void compareNumber(final String oldNewIdStr, final String colName, final int startInxNewArg,
        final int startInxOldArg) throws SQLException {
    Integer newInt = getIntFromObj(newDBRS.getObject(startInxNewArg));
    Integer oldInt = getIntFromObj(oldDBRS.getObject(startInxOldArg));

    if (oldInt == null && newInt == null)
        return;

    if (oldInt == null && newInt != null) {
        String msg = "Old " + colName + " [" + oldInt + "] is NULL New " + colName + "[" + newInt + "] is not";
        log.error(oldNewIdStr + " " + msg);
        tblWriter.logErrors(oldNewIdStr, msg);

    } else if (oldInt != null && newInt == null) {
        String msg = "Old " + colName + "[" + oldInt + "] is not null New " + colName + "[" + newInt
                + "] is NULL";
        log.error(oldNewIdStr + " " + msg);
        tblWriter.logErrors(oldNewIdStr, msg);

    } else if (oldInt != null && !oldInt.equals(newInt)) {
        String msg = "Old " + colName + "[" + oldInt + "] is not equal New " + colName + "[" + newInt + "]";
        log.error(oldNewIdStr + " " + msg);
        tblWriter.logErrors(oldNewIdStr, msg);
    }
}

From source file:cn.jsprun.struts.action.BasicSettingsAction.java

@SuppressWarnings("unchecked")
private Map getResultString(HttpServletRequest request, String checkBoxValue, String dsStringValue,
        int creditid, String textName) {
    String result = null;/*  ww w.  jav a 2  s  .  c  o m*/
    boolean bool = true;
    if (checkBoxValue != null) {
        String postcredits_ = request.getParameter(textName);
        postcredits_ = FormDataCheck.getNumberFromFormOfDisplayorder(postcredits_);
        Integer creditsI = null;
        if (Long.valueOf(postcredits_) > 99) {
            creditsI = 99;
        } else if (Long.valueOf(postcredits_) < -99) {
            creditsI = -99;
        } else {
            creditsI = Integer.valueOf(postcredits_);
        }
        Map postcreditsMap = null;
        if (!dsStringValue.equals("")) {
            postcreditsMap = dataParse.characterParse(dsStringValue, true);
            Object postcreditsOB = postcreditsMap.get(creditid);
            Integer postcredits = postcreditsOB == null ? null : Integer.valueOf(String.valueOf(postcreditsOB));
            if (postcredits == null || !creditsI.equals(postcredits)) {
                bool = false;
                postcreditsMap.put(creditid, creditsI);
            }
        } else {
            bool = false;
            postcreditsMap = new TreeMap();
            postcreditsMap.put(creditid, creditsI);
        }
        result = dataParse.combinationChar(postcreditsMap);
    } else {
        Map postcreditsMap = null;
        if (!dsStringValue.equals("")) {
            postcreditsMap = dataParse.characterParse(dsStringValue, true);
            String postcredits = String.valueOf(postcreditsMap.get(creditid));
            if (!postcredits.equals("null")) {
                bool = false;
                postcreditsMap.remove(creditid);
            }
            result = dataParse.combinationChar(postcreditsMap);
        } else {
            result = "";
        }
    }
    Map map = new HashMap();
    map.put("bool", bool);
    map.put("result", result);
    return map;
}

From source file:edu.ku.brc.specify.conversion.SpecifyDBConverter.java

/**
 * @param oldDBConn/* ww  w .ja  v a  2 s .co  m*/
 * @param newDBConn
 */
protected void fixLoanPreps(final Connection oldDBConn, final Connection newDBConn) {
    // Category == 0 -> Is a Loan, 1 is a Gift

    System.out.println("------------------------ Loans ----------------------------");

    int fixCnt = 0;
    int totalCnt = 0;
    int skippedCnt = 0;
    int notFndCnt = 0;
    int noMatch = 0;

    IdMapperMgr.getInstance().setDBs(oldDBConn, newDBConn);
    IdTableMapper loanPrepsMapper = IdMapperMgr.getInstance().addTableMapper("loanphysicalobject",
            "LoanPhysicalObjectID", false);
    IdTableMapper loansMapper = IdMapperMgr.getInstance().addTableMapper("loan", "LoanID", false);
    IdTableMapper prepMapper = IdMapperMgr.getInstance().addTableMapper("collectionobject",
            "CollectionObjectID", false);

    Statement stmt = null;
    PreparedStatement newStmt = null;
    PreparedStatement pStmt = null;
    try {
        pStmt = newDBConn.prepareStatement(
                "UPDATE loanpreparation SET Quantity=?, QuantityResolved=?, QuantityReturned=?, IsResolved=?, TimestampModified=?, TimestampCreated=?, "
                        + "LoanID=?, DescriptionOfMaterial=?, OutComments=?, InComments=?, PreparationID=?, Version=? "
                        + "WHERE LoanPreparationID = ?");

        newStmt = newDBConn.prepareStatement(
                "SELECT LoanPreparationID, TimestampModified, Version FROM loanpreparation WHERE LoanPreparationID = ?");

        String sql = "SELECT lp.LoanPhysicalObjectID, lp.PhysicalObjectID, lp.LoanID, lp.Quantity, lp.DescriptionOfMaterial, lp.OutComments, lp.InComments, "
                + "lp.QuantityResolved, lp.QuantityReturned, lp.TimestampCreated, lp.TimestampModified, lp.LastEditedBy, l.Closed "
                + "FROM loanphysicalobject lp INNER JOIN loan l ON l.LoanID = lp.LoanID WHERE l.Category = 0";

        stmt = oldDBConn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        while (rs.next()) {
            int id = rs.getInt(1);
            Timestamp oldCreatedTS = rs.getTimestamp(10);

            //System.out.println(id);
            Integer newID = loanPrepsMapper.get(id);
            if (newID != null) {
                newStmt.setInt(1, newID);

                ResultSet rs2 = newStmt.executeQuery();
                if (rs2.next()) {
                    Timestamp oldModifiedTS = rs.getTimestamp(11);
                    if (rs2.getInt(3) == 0) // version
                    {
                        Integer prepId = rs.getInt(2);
                        Integer loanId = rs.getInt(3);
                        Integer newLoanId = loansMapper.get(loanId);
                        Integer qty = rs.getInt(4);
                        String descOfMat = rs.getString(5);
                        String outComments = rs.getString(6);
                        String inComments = rs.getString(7);
                        Integer qtyRes = rs.getInt(8);
                        Integer qtyRet = rs.getInt(9);
                        String lasteditedBy = rs.getString(12);
                        Boolean isLoanClosed = rs.getBoolean(13);

                        isLoanClosed = isLoanClosed == null ? false : isLoanClosed;

                        pStmt.setInt(1, qty);
                        pStmt.setInt(2, qtyRes);
                        pStmt.setInt(3, qtyRet);

                        boolean isResolved = isLoanClosed;

                        if (!isLoanClosed) // if Loan is Closed then all are resolved by definition
                        {
                            if (qty != null) {
                                if (qtyRes != null && qty.equals(qtyRes)) {
                                    isResolved = true;

                                } else if (qtyRet != null && qty.equals(qtyRet)) {
                                    isResolved = true;
                                }
                            }
                        }
                        pStmt.setBoolean(4, isResolved);
                        pStmt.setTimestamp(5, oldModifiedTS);
                        pStmt.setTimestamp(6, oldCreatedTS);

                        pStmt.setInt(7, newLoanId);
                        pStmt.setString(8, descOfMat);
                        pStmt.setString(9, outComments);
                        pStmt.setString(10, inComments);
                        pStmt.setInt(11, prepId != null ? prepMapper.get(prepId) : null);
                        pStmt.setInt(12, 1); // Version

                        pStmt.setInt(13, newID);

                        if (pStmt.executeUpdate() != 1) {
                            log.error(String.format("*** Error updating OldID %d  newID %d", rs.getInt(1),
                                    newID));
                        } else {
                            fixCnt++;
                        }
                    } else {
                        noMatch++;
                    }
                } else {
                    notFndCnt++;
                }
                rs2.close();
            } else {
                //log.error(String.format("*** Error not new Id for OldID %d", rs.getInt(1)));
                skippedCnt++;
            }
            totalCnt++;
        }
        rs.close();

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (stmt != null)
                stmt.close();
            if (newStmt != null)
                newStmt.close();
            if (pStmt != null)
                pStmt.close();

        } catch (Exception ex) {
        }
    }

    System.out.println(String.format("Total: %d  Fixed: %d  Skipped: %d  NotFnd: %d  noMatch: %d", totalCnt,
            fixCnt, skippedCnt, notFndCnt, noMatch));
}

From source file:com.gst.portfolio.loanaccount.serialization.LoanApplicationCommandFromApiJsonHelper.java

public void validateForCreate(final String json, final boolean isMeetingMandatoryForJLGLoans,
        final LoanProduct loanProduct) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }/*w  w  w  .  j ava 2  s.  com*/

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("loan");

    final JsonElement element = this.fromApiJsonHelper.parse(json);

    final String loanTypeParameterName = "loanType";
    final String loanTypeStr = this.fromApiJsonHelper.extractStringNamed(loanTypeParameterName, element);
    baseDataValidator.reset().parameter(loanTypeParameterName).value(loanTypeStr).notNull();

    if (!StringUtils.isBlank(loanTypeStr)) {
        final AccountType loanType = AccountType.fromName(loanTypeStr);
        baseDataValidator.reset().parameter(loanTypeParameterName).value(loanType.getValue()).inMinMaxRange(1,
                3);

        final Long clientId = this.fromApiJsonHelper.extractLongNamed("clientId", element);
        final Long groupId = this.fromApiJsonHelper.extractLongNamed("groupId", element);
        if (loanType.isIndividualAccount()) {
            baseDataValidator.reset().parameter("clientId").value(clientId).notNull().longGreaterThanZero();
            baseDataValidator.reset().parameter("groupId").value(groupId)
                    .mustBeBlankWhenParameterProvided("clientId", clientId);
        }

        if (loanType.isGroupAccount()) {
            baseDataValidator.reset().parameter("groupId").value(groupId).notNull().longGreaterThanZero();
            baseDataValidator.reset().parameter("clientId").value(clientId)
                    .mustBeBlankWhenParameterProvided("groupId", groupId);
        }

        if (loanType.isJLGAccount()) {
            baseDataValidator.reset().parameter("clientId").value(clientId).notNull().integerGreaterThanZero();
            baseDataValidator.reset().parameter("groupId").value(groupId).notNull().longGreaterThanZero();

            // if it is JLG loan that must have meeting details
            if (isMeetingMandatoryForJLGLoans) {
                final String calendarIdParameterName = "calendarId";
                final Long calendarId = this.fromApiJsonHelper.extractLongNamed(calendarIdParameterName,
                        element);
                baseDataValidator.reset().parameter(calendarIdParameterName).value(calendarId).notNull()
                        .integerGreaterThanZero();

                // if it is JLG loan then must have a value for
                // syncDisbursement passed in
                String syncDisbursementParameterName = "syncDisbursementWithMeeting";
                final Boolean syncDisbursement = this.fromApiJsonHelper
                        .extractBooleanNamed(syncDisbursementParameterName, element);

                if (syncDisbursement == null) {
                    baseDataValidator.reset().parameter(syncDisbursementParameterName).value(syncDisbursement)
                            .trueOrFalseRequired(false);
                }
            }

        }

    }

    final Long productId = this.fromApiJsonHelper.extractLongNamed("productId", element);
    baseDataValidator.reset().parameter("productId").value(productId).notNull().integerGreaterThanZero();

    final String accountNoParameterName = "accountNo";
    if (this.fromApiJsonHelper.parameterExists(accountNoParameterName, element)) {
        final String accountNo = this.fromApiJsonHelper.extractStringNamed(accountNoParameterName, element);
        baseDataValidator.reset().parameter(accountNoParameterName).value(accountNo).ignoreIfNull()
                .notExceedingLengthOf(20);
    }

    final String externalIdParameterName = "externalId";
    if (this.fromApiJsonHelper.parameterExists(externalIdParameterName, element)) {
        final String externalId = this.fromApiJsonHelper.extractStringNamed(externalIdParameterName, element);
        baseDataValidator.reset().parameter(externalIdParameterName).value(externalId).ignoreIfNull()
                .notExceedingLengthOf(100);
    }

    final String fundIdParameterName = "fundId";
    if (this.fromApiJsonHelper.parameterExists(fundIdParameterName, element)) {
        final Long fundId = this.fromApiJsonHelper.extractLongNamed(fundIdParameterName, element);
        baseDataValidator.reset().parameter(fundIdParameterName).value(fundId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final String loanOfficerIdParameterName = "loanOfficerId";
    if (this.fromApiJsonHelper.parameterExists(loanOfficerIdParameterName, element)) {
        final Long loanOfficerId = this.fromApiJsonHelper.extractLongNamed(loanOfficerIdParameterName, element);
        baseDataValidator.reset().parameter(loanOfficerIdParameterName).value(loanOfficerId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final String loanPurposeIdParameterName = "loanPurposeId";
    if (this.fromApiJsonHelper.parameterExists(loanPurposeIdParameterName, element)) {
        final Long loanPurposeId = this.fromApiJsonHelper.extractLongNamed(loanPurposeIdParameterName, element);
        baseDataValidator.reset().parameter(loanPurposeIdParameterName).value(loanPurposeId).ignoreIfNull()
                .integerGreaterThanZero();
    }

    final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal", element);
    baseDataValidator.reset().parameter("principal").value(principal).notNull().positiveAmount();

    final String loanTermFrequencyParameterName = "loanTermFrequency";
    final Integer loanTermFrequency = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(loanTermFrequencyParameterName, element);
    baseDataValidator.reset().parameter(loanTermFrequencyParameterName).value(loanTermFrequency).notNull()
            .integerGreaterThanZero();

    final String loanTermFrequencyTypeParameterName = "loanTermFrequencyType";
    final Integer loanTermFrequencyType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(loanTermFrequencyTypeParameterName, element);
    baseDataValidator.reset().parameter(loanTermFrequencyTypeParameterName).value(loanTermFrequencyType)
            .notNull().inMinMaxRange(0, 3);

    final String numberOfRepaymentsParameterName = "numberOfRepayments";
    final Integer numberOfRepayments = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(numberOfRepaymentsParameterName, element);
    baseDataValidator.reset().parameter(numberOfRepaymentsParameterName).value(numberOfRepayments).notNull()
            .integerGreaterThanZero();

    final String repaymentEveryParameterName = "repaymentEvery";
    final Integer repaymentEvery = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(repaymentEveryParameterName, element);
    baseDataValidator.reset().parameter(repaymentEveryParameterName).value(repaymentEvery).notNull()
            .integerGreaterThanZero();

    final String repaymentEveryFrequencyTypeParameterName = "repaymentFrequencyType";
    final Integer repaymentEveryType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(repaymentEveryFrequencyTypeParameterName, element);
    baseDataValidator.reset().parameter(repaymentEveryFrequencyTypeParameterName).value(repaymentEveryType)
            .notNull().inMinMaxRange(0, 3);

    final String repaymentFrequencyNthDayTypeParameterName = "repaymentFrequencyNthDayType";
    final String repaymentFrequencyDayOfWeekTypeParameterName = "repaymentFrequencyDayOfWeekType";
    CalendarUtils.validateNthDayOfMonthFrequency(baseDataValidator, repaymentFrequencyNthDayTypeParameterName,
            repaymentFrequencyDayOfWeekTypeParameterName, element, this.fromApiJsonHelper);
    final String interestTypeParameterName = "interestType";
    final Integer interestType = this.fromApiJsonHelper.extractIntegerSansLocaleNamed(interestTypeParameterName,
            element);
    baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).notNull()
            .inMinMaxRange(0, 1);

    final String interestCalculationPeriodTypeParameterName = "interestCalculationPeriodType";
    final Integer interestCalculationPeriodType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(interestCalculationPeriodTypeParameterName, element);
    baseDataValidator.reset().parameter(interestCalculationPeriodTypeParameterName)
            .value(interestCalculationPeriodType).notNull().inMinMaxRange(0, 1);

    if (loanProduct.isLinkedToFloatingInterestRate()) {
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode(
                    "not.supported.loanproduct.linked.to.floating.rate",
                    "interestRatePerPeriod param is not supported, selected Loan Product is linked with floating interest rate.");
        }

        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) {
            final Boolean isFloatingInterestRate = this.fromApiJsonHelper
                    .extractBooleanNamed(LoanApiConstants.isFloatingInterestRate, element);
            if (isFloatingInterestRate != null && isFloatingInterestRate
                    && !loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed()) {
                baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode(
                        "true.not.supported.for.selected.loanproduct",
                        "isFloatingInterestRate value of true not supported for selected Loan Product.");
            }
        } else {
            baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate)
                    .trueOrFalseRequired(false);
        }

        if (interestType != null && interestType.equals(InterestMethod.FLAT.getValue())) {
            baseDataValidator.reset().parameter(interestTypeParameterName).failWithCode(
                    "should.be.0.for.selected.loan.product",
                    "interestType should be DECLINING_BALANCE for selected Loan Product as it is linked to floating rates.");
        }

        final String interestRateDifferentialParameterName = LoanApiConstants.interestRateDifferential;
        final BigDecimal interestRateDifferential = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(interestRateDifferentialParameterName, element);
        baseDataValidator.reset().parameter(interestRateDifferentialParameterName)
                .value(interestRateDifferential).notNull().zeroOrPositiveAmount()
                .inMinAndMaxAmountRange(loanProduct.getFloatingRates().getMinDifferentialLendingRate(),
                        loanProduct.getFloatingRates().getMaxDifferentialLendingRate());

    } else {

        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isFloatingInterestRate, element)) {
            baseDataValidator.reset().parameter(LoanApiConstants.isFloatingInterestRate).failWithCode(
                    "not.supported.loanproduct.not.linked.to.floating.rate",
                    "isFloatingInterestRate param is not supported, selected Loan Product is not linked with floating interest rate.");
        }
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.interestRateDifferential, element)) {
            baseDataValidator.reset().parameter(LoanApiConstants.interestRateDifferential).failWithCode(
                    "not.supported.loanproduct.not.linked.to.floating.rate",
                    "interestRateDifferential param is not supported, selected Loan Product is not linked with floating interest rate.");
        }

        final String interestRatePerPeriodParameterName = "interestRatePerPeriod";
        final BigDecimal interestRatePerPeriod = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(interestRatePerPeriodParameterName, element);
        baseDataValidator.reset().parameter(interestRatePerPeriodParameterName).value(interestRatePerPeriod)
                .notNull().zeroOrPositiveAmount();

    }

    final String amortizationTypeParameterName = "amortizationType";
    final Integer amortizationType = this.fromApiJsonHelper
            .extractIntegerSansLocaleNamed(amortizationTypeParameterName, element);
    baseDataValidator.reset().parameter(amortizationTypeParameterName).value(amortizationType).notNull()
            .inMinMaxRange(0, 1);

    final String expectedDisbursementDateParameterName = "expectedDisbursementDate";
    final LocalDate expectedDisbursementDate = this.fromApiJsonHelper
            .extractLocalDateNamed(expectedDisbursementDateParameterName, element);
    baseDataValidator.reset().parameter(expectedDisbursementDateParameterName).value(expectedDisbursementDate)
            .notNull();

    // grace validation
    final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
    baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment)
            .zeroOrPositiveAmount();

    final Integer graceOnInterestPayment = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
    baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment)
            .zeroOrPositiveAmount();

    final Integer graceOnInterestCharged = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
    baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged)
            .zeroOrPositiveAmount();

    final Integer graceOnArrearsAgeing = this.fromApiJsonHelper
            .extractIntegerWithLocaleNamed(LoanProductConstants.graceOnArrearsAgeingParameterName, element);
    baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName)
            .value(graceOnArrearsAgeing).zeroOrPositiveAmount();

    final String interestChargedFromDateParameterName = "interestChargedFromDate";
    if (this.fromApiJsonHelper.parameterExists(interestChargedFromDateParameterName, element)) {
        final LocalDate interestChargedFromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(interestChargedFromDateParameterName, element);
        baseDataValidator.reset().parameter(interestChargedFromDateParameterName).value(interestChargedFromDate)
                .ignoreIfNull().notNull();
    }

    final String repaymentsStartingFromDateParameterName = "repaymentsStartingFromDate";
    if (this.fromApiJsonHelper.parameterExists(repaymentsStartingFromDateParameterName, element)) {
        final LocalDate repaymentsStartingFromDate = this.fromApiJsonHelper
                .extractLocalDateNamed(repaymentsStartingFromDateParameterName, element);
        baseDataValidator.reset().parameter(repaymentsStartingFromDateParameterName)
                .value(repaymentsStartingFromDate).ignoreIfNull().notNull();
    }

    final String inArrearsToleranceParameterName = "inArrearsTolerance";
    if (this.fromApiJsonHelper.parameterExists(inArrearsToleranceParameterName, element)) {
        final BigDecimal inArrearsTolerance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(inArrearsToleranceParameterName, element);
        baseDataValidator.reset().parameter(inArrearsToleranceParameterName).value(inArrearsTolerance)
                .ignoreIfNull().zeroOrPositiveAmount();
    }

    final String submittedOnDateParameterName = "submittedOnDate";
    final LocalDate submittedOnDate = this.fromApiJsonHelper.extractLocalDateNamed(submittedOnDateParameterName,
            element);
    if (submittedOnDate == null) {
        baseDataValidator.reset().parameter(submittedOnDateParameterName).value(submittedOnDate).notNull();
    }

    final String submittedOnNoteParameterName = "submittedOnNote";
    if (this.fromApiJsonHelper.parameterExists(submittedOnNoteParameterName, element)) {
        final String submittedOnNote = this.fromApiJsonHelper.extractStringNamed(submittedOnNoteParameterName,
                element);
        baseDataValidator.reset().parameter(submittedOnNoteParameterName).value(submittedOnNote).ignoreIfNull()
                .notExceedingLengthOf(500);
    }

    final String transactionProcessingStrategyIdParameterName = "transactionProcessingStrategyId";
    final Long transactionProcessingStrategyId = this.fromApiJsonHelper
            .extractLongNamed(transactionProcessingStrategyIdParameterName, element);
    baseDataValidator.reset().parameter(transactionProcessingStrategyIdParameterName)
            .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero();

    final String linkAccountIdParameterName = "linkAccountId";
    if (this.fromApiJsonHelper.parameterExists(linkAccountIdParameterName, element)) {
        final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element);
        baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).ignoreIfNull()
                .longGreaterThanZero();
    }

    final String createSiAtDisbursementParameterName = "createStandingInstructionAtDisbursement";
    if (this.fromApiJsonHelper.parameterExists(createSiAtDisbursementParameterName, element)) {
        final Boolean createStandingInstructionAtDisbursement = this.fromApiJsonHelper
                .extractBooleanNamed(createSiAtDisbursementParameterName, element);
        final Long linkAccountId = this.fromApiJsonHelper.extractLongNamed(linkAccountIdParameterName, element);

        if (createStandingInstructionAtDisbursement) {
            baseDataValidator.reset().parameter(linkAccountIdParameterName).value(linkAccountId).notNull()
                    .longGreaterThanZero();
        }
    }

    // charges
    final String chargesParameterName = "charges";
    if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(chargesParameterName, element)) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement);
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);

        if (topLevelJsonElement.get(chargesParameterName).isJsonArray()) {
            final Type arrayObjectParameterTypeOfMap = new TypeToken<Map<String, Object>>() {
            }.getType();
            final Set<String> supportedParameters = new HashSet<>(Arrays.asList("id", "chargeId", "amount",
                    "chargeTimeType", "chargeCalculationType", "dueDate"));

            final JsonArray array = topLevelJsonElement.get("charges").getAsJsonArray();
            for (int i = 1; i <= array.size(); i++) {

                final JsonObject loanChargeElement = array.get(i - 1).getAsJsonObject();
                final String arrayObjectJson = this.fromApiJsonHelper.toJson(loanChargeElement);
                this.fromApiJsonHelper.checkForUnsupportedParameters(arrayObjectParameterTypeOfMap,
                        arrayObjectJson, supportedParameters);

                final Long chargeId = this.fromApiJsonHelper.extractLongNamed("chargeId", loanChargeElement);
                baseDataValidator.reset().parameter("charges").parameterAtIndexArray("chargeId", i)
                        .value(chargeId).notNull().integerGreaterThanZero();

                final BigDecimal amount = this.fromApiJsonHelper.extractBigDecimalNamed("amount",
                        loanChargeElement, locale);
                baseDataValidator.reset().parameter("charges").parameterAtIndexArray("amount", i).value(amount)
                        .notNull().positiveAmount();

                this.fromApiJsonHelper.extractLocalDateNamed("dueDate", loanChargeElement, dateFormat, locale);
            }
        }
    }

    // collateral
    final String collateralParameterName = "collateral";
    if (element.isJsonObject() && this.fromApiJsonHelper.parameterExists(collateralParameterName, element)) {
        final JsonObject topLevelJsonElement = element.getAsJsonObject();
        final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
        if (topLevelJsonElement.get("collateral").isJsonArray()) {

            final Type collateralParameterTypeOfMap = new TypeToken<Map<String, Object>>() {
            }.getType();
            final Set<String> supportedParameters = new HashSet<>(
                    Arrays.asList("id", "type", "value", "description"));
            final JsonArray array = topLevelJsonElement.get("collateral").getAsJsonArray();
            for (int i = 1; i <= array.size(); i++) {
                final JsonObject collateralItemElement = array.get(i - 1).getAsJsonObject();

                final String collateralJson = this.fromApiJsonHelper.toJson(collateralItemElement);
                this.fromApiJsonHelper.checkForUnsupportedParameters(collateralParameterTypeOfMap,
                        collateralJson, supportedParameters);

                final Long collateralTypeId = this.fromApiJsonHelper.extractLongNamed("type",
                        collateralItemElement);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("type", i)
                        .value(collateralTypeId).notNull().integerGreaterThanZero();

                final BigDecimal collateralValue = this.fromApiJsonHelper.extractBigDecimalNamed("value",
                        collateralItemElement, locale);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("value", i)
                        .value(collateralValue).ignoreIfNull().positiveAmount();

                final String description = this.fromApiJsonHelper.extractStringNamed("description",
                        collateralItemElement);
                baseDataValidator.reset().parameter("collateral").parameterAtIndexArray("description", i)
                        .value(description).notBlank().notExceedingLengthOf(500);

            }
        } else {
            baseDataValidator.reset().parameter(collateralParameterName).expectedArrayButIsNot();
        }
    }

    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.emiAmountParameterName, element)) {
        if (!(loanProduct.canDefineInstallmentAmount() || loanProduct.isMultiDisburseLoan())) {
            List<String> unsupportedParameterList = new ArrayList<>();
            unsupportedParameterList.add(LoanApiConstants.emiAmountParameterName);
            throw new UnsupportedParameterException(unsupportedParameterList);
        }
        final BigDecimal emiAnount = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanApiConstants.emiAmountParameterName, element);
        baseDataValidator.reset().parameter(LoanApiConstants.emiAmountParameterName).value(emiAnount)
                .ignoreIfNull().positiveAmount();
    }
    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.maxOutstandingBalanceParameterName, element)) {
        final BigDecimal maxOutstandingBalance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(LoanApiConstants.maxOutstandingBalanceParameterName, element);
        baseDataValidator.reset().parameter(LoanApiConstants.maxOutstandingBalanceParameterName)
                .value(maxOutstandingBalance).ignoreIfNull().positiveAmount();
    }

    if (loanProduct.canUseForTopup()) {
        if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.isTopup, element)) {
            final Boolean isTopup = this.fromApiJsonHelper.extractBooleanNamed(LoanApiConstants.isTopup,
                    element);
            baseDataValidator.reset().parameter(LoanApiConstants.isTopup).value(isTopup)
                    .validateForBooleanValue();

            if (isTopup != null && isTopup) {
                final Long loanId = this.fromApiJsonHelper.extractLongNamed(LoanApiConstants.loanIdToClose,
                        element);
                baseDataValidator.reset().parameter(LoanApiConstants.loanIdToClose).value(loanId).notNull()
                        .longGreaterThanZero();
            }
        }
    }
    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.datatables, element)) {
        final JsonArray datatables = this.fromApiJsonHelper.extractJsonArrayNamed(LoanApiConstants.datatables,
                element);
        baseDataValidator.reset().parameter(LoanApiConstants.datatables).value(datatables).notNull()
                .jsonArrayNotEmpty();
    }

    validateLoanMultiDisbursementdate(element, baseDataValidator, expectedDisbursementDate, principal);
    validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct);
    if (!dataValidationErrors.isEmpty()) {
        throw new PlatformApiDataValidationException(dataValidationErrors);
    }
}

From source file:de.juwimm.cms.remote.EditionServiceSpringImpl.java

/**
 * @param fulldeploy//from  www  .  j a  va 2 s  .  co  m
 *            means, if this is an import of an Full-Edition, Unit-Edition or Live-Deploy
 *            <ul>
 *            <li>0 - means LiveDeploy</li>
 *            <li>1 - means Fulldeploy of an FullEdition</li>
 *            <li>2 - means Fulldeploy of an UnitEdition</li>
 *            </ul>
 */
private ViewComponentHbm createViewComponent(Integer unitId, ViewDocumentHbm viewDocument,
        ArrayList<ViewComponentHbm> savedUnits, Element nde, ViewComponentHbm parent, ViewComponentHbm prev,
        boolean livedeploy, int fulldeploy, boolean useNewIds) throws Exception {
    boolean reusePrimaryKey = (fulldeploy == 0);
    ViewComponentHbm viewComponent = null;
    try {
        Integer myUnitId = new Integer(nde.getAttribute("unitId"));
        Integer vcId = new Integer(nde.getAttribute("id"));
        if (fulldeploy == 2 && !myUnitId.equals(unitId)) {
            return null;
        } else if (fulldeploy > 0 || myUnitId.equals(unitId)) {
            String reference = XercesHelper.getNodeValue(nde, "./reference");
            String linkName = XercesHelper.getNodeValue(nde, "./linkName");
            String approvedLinkName = XercesHelper.getNodeValue(nde, "./approvedLinkName");
            String statusInfo = XercesHelper.getNodeValue(nde, "./statusInfo");
            String urlLinkName = XercesHelper.getNodeValue(nde, "./urlLinkName");

            byte viewType = new Byte(XercesHelper.getNodeValue(nde, "./viewType")).byteValue();
            boolean visible = Boolean.valueOf(XercesHelper.getNodeValue(nde, "./visible")).booleanValue();
            if (livedeploy
                    && (viewType == Constants.VIEW_TYPE_CONTENT || viewType == Constants.VIEW_TYPE_UNIT)) {
                Node publsh = XercesHelper.findNode(nde, "./content/contentVersion/version[string()='PUBLS']");

                if (log.isDebugEnabled())
                    log.debug("viewType " + viewType);
                if (publsh == null) {
                    if (log.isDebugEnabled())
                        log.debug("Haven't found a Cool-Online-Version (PUBLS), does not create VC " + vcId);
                    return null;
                }
            }
            if (fulldeploy > 0) {
                if (useNewIds) {
                    viewComponent = getViewComponentHbmDao().create(viewDocument, reference, linkName,
                            statusInfo, urlLinkName, null);
                    viewComponent.setApprovedLinkName(approvedLinkName);
                    mappingVCs.put(vcId, viewComponent.getViewComponentId());
                } else {
                    // viewDocs can only be crated with viewComps 
                    if (viewDocument.getViewComponent().getViewComponentId().compareTo(vcId) == 0) {
                        viewComponent = viewDocument.getViewComponent();
                    } else {
                        viewComponent = getViewComponentHbmDao().load(vcId);
                    }
                    if (viewComponent == null) {
                        viewComponent = getViewComponentHbmDao().create(viewDocument, reference, linkName,
                                statusInfo, urlLinkName, vcId);
                    } else {
                        viewComponent.setDisplayLinkName(linkName);
                        viewComponent.setViewDocument(viewDocument);
                        viewComponent.setReference(reference);
                        viewComponent.setUrlLinkName(urlLinkName);
                        viewComponent.setLinkDescription(statusInfo);
                    }
                    viewComponent.setApprovedLinkName(approvedLinkName);
                    mappingVCs.put(vcId, vcId);
                }
                if (fulldeploy == 1) {
                    Integer newUnitId = mappingUnits.get(myUnitId);
                    if (newUnitId == null) {
                        newUnitId = myUnitId;
                    }
                    if (unitId == null || !newUnitId.equals(unitId)) {
                        if (log.isDebugEnabled())
                            log.debug("newUnitId " + newUnitId + " myUnitId " + myUnitId);
                        UnitHbm unit = getUnitHbmDao().load(newUnitId);
                        viewComponent.setAssignedUnit(unit);
                        unitId = unit.getUnitId();
                    }
                }
            } else {
                try {
                    if (log.isDebugEnabled())
                        log.debug("searching ViewComponent: " + vcId);
                    viewComponent = getViewComponentHbmDao().load(vcId);
                    viewComponent.setViewDocument(viewDocument);
                    viewComponent.setReference(reference);
                    viewComponent.setDisplayLinkName(linkName);
                    viewComponent.setLinkDescription(statusInfo);
                    viewComponent.setUrlLinkName(urlLinkName);
                    viewComponent.setApprovedLinkName(approvedLinkName);
                } catch (Exception e) {
                    if (log.isDebugEnabled())
                        log.debug("error, creating ViewComponent: " + vcId);
                    ViewComponentHbm tempVC = new ViewComponentHbmImpl();
                    tempVC.setViewDocument(viewDocument);
                    tempVC.setReference(reference);
                    tempVC.setLinkDescription(linkName);
                    tempVC.setStatus(Integer.parseInt(statusInfo));
                    tempVC.setUrlLinkName(urlLinkName);
                    tempVC.setViewComponentId(vcId);
                    viewComponent = getViewComponentHbmDao().create(tempVC);
                    viewComponent.setApprovedLinkName(approvedLinkName);
                }
                viewComponent.setOnline((byte) 1);
            }
            viewComponent.setPrevNode(prev);
            if (prev != null)
                prev.setNextNode(viewComponent);
            viewComponent.setParentViewComponent(parent);
            viewComponent.setMetaData(XercesHelper.getNodeValue(nde, "./metaKeywords"));
            viewComponent.setMetaDescription(XercesHelper.getNodeValue(nde, "./metaDescription"));
            String onlineStart = XercesHelper.getNodeValue(nde, "./onlineStart");
            if (!onlineStart.equals("")) {
                if (log.isDebugEnabled())
                    log.debug("OnlineStart: " + onlineStart);
                viewComponent.setOnlineStart(Long.parseLong(onlineStart));
            }
            String onlineStop = XercesHelper.getNodeValue(nde, "./onlineStop");
            if (!onlineStop.equals("")) {
                if (log.isDebugEnabled())
                    log.debug("OnlineStop: " + onlineStop);
                viewComponent.setOnlineStop(Long.parseLong(onlineStop));
            }
            viewComponent.setViewLevel(XercesHelper.getNodeValue(nde, "./viewLevel"));
            viewComponent.setViewIndex(XercesHelper.getNodeValue(nde, "./viewIndex"));
            viewComponent
                    .setDisplaySettings(Byte.parseByte(XercesHelper.getNodeValue(nde, "./displaySettings")));
            viewComponent.setShowType(Byte.parseByte(XercesHelper.getNodeValue(nde, "./showType")));
            viewComponent.setViewType(viewType);
            viewComponent.setVisible(visible);
            viewComponent.setSearchIndexed(
                    Boolean.valueOf(XercesHelper.getNodeValue(nde, "./searchIndexed")).booleanValue());
            viewComponent.setXmlSearchIndexed(
                    Boolean.valueOf(XercesHelper.getNodeValue(nde, "./xmlSearchIndexed")).booleanValue());
            byte status = -1;
            try {
                status = new Byte(XercesHelper.getNodeValue(nde, "./status")).byteValue();
            } catch (Exception e) {
                if (log.isDebugEnabled())
                    log.debug("Status was not set...");
            }
            // on import set deploy-state to "edited"
            if (!livedeploy)
                status = Constants.DEPLOY_STATUS_EDITED;
            viewComponent.setStatus(status);
            byte onlineState = -1;
            try {
                onlineState = new Byte(XercesHelper.getNodeValue(nde, "./online")).byteValue();
            } catch (Exception e) {
                if (log.isDebugEnabled())
                    log.debug("OnlineState was not set...");
            }
            // on import set online-state to offline
            if (!livedeploy)
                onlineState = Constants.ONLINE_STATUS_OFFLINE;
            viewComponent.setOnline(onlineState);
            if (fulldeploy == 0 && viewComponent.getStatus() == Constants.DEPLOY_STATUS_APPROVED) {
                // this only occures on new pages that are deployed for the first time
                // (they dont have the state online on workserver because of different transactions)
                if (log.isDebugEnabled())
                    log.debug("setting online: " + viewComponent.getDisplayLinkName());
                viewComponent.setOnline((byte) 1);
            }
            {
                // realm2viewComponent
                Node nodeRealm = XercesHelper.findNode(nde, "realm2viewComponent");
                if (nodeRealm != null) {
                    // this ViewComponent is protected by a realm
                    if (fulldeploy > 0) {
                        // use new ids
                        String neededrole = XercesHelper.getNodeValue(nodeRealm, "roleNeeded");
                        String loginPage = XercesHelper.getNodeValue(nodeRealm, "loginPageId");
                        if (loginPage != null && !"".equalsIgnoreCase(loginPage)) {
                            Integer loginPageId = null;
                            try {
                                loginPageId = Integer.valueOf(loginPage);
                            } catch (Exception e) {
                            }
                            if (loginPageId != null)
                                loginPagesRealm2vc.put(vcId, loginPageId);
                        }
                        Node relNode = XercesHelper.findNode(nodeRealm, "jdbcRealmId");
                        if (relNode != null) {
                            Integer id = new Integer(XercesHelper.getNodeValue(relNode));
                            RealmJdbcHbm sqlrealm = null;
                            if (useNewIds) {
                                sqlrealm = getRealmJdbcHbmDao().load(mappingRealmsJdbc.get(id));
                            } else {
                                sqlrealm = getRealmJdbcHbmDao().load(id);
                            }
                            Realm2viewComponentHbm tempRealm = createTempRealm(viewComponent, neededrole,
                                    sqlrealm, null, null, null);
                            Realm2viewComponentHbm r = getRealm2viewComponentHbmDao().create(tempRealm);
                            viewComponent.setRealm2vc(r);
                        } else {
                            relNode = XercesHelper.findNode(nodeRealm, "simplePwRealmId");
                            if (relNode != null) {
                                Integer id = new Integer(XercesHelper.getNodeValue(relNode));
                                RealmSimplePwHbm realm = null;
                                if (useNewIds) {
                                    realm = getRealmSimplePwHbmDao().load(mappingRealmsSimplePw.get(id));
                                } else {
                                    realm = getRealmSimplePwHbmDao().load(id);
                                }
                                Realm2viewComponentHbm tempRealm = createTempRealm(viewComponent, neededrole,
                                        null, realm, null, null);
                                Realm2viewComponentHbm r = getRealm2viewComponentHbmDao().create(tempRealm);
                                viewComponent.setRealm2vc(r);
                            } else {
                                relNode = XercesHelper.findNode(nodeRealm, "ldapRealmId");
                                if (relNode != null) {
                                    Integer id = new Integer(XercesHelper.getNodeValue(relNode));
                                    RealmLdapHbm realm = null;
                                    if (useNewIds) {
                                        realm = getRealmLdapHbmDao().load(mappingRealmsLdap.get(id));
                                    } else {
                                        realm = getRealmLdapHbmDao().load(id);
                                    }
                                    Realm2viewComponentHbm tempRealm = createTempRealm(viewComponent,
                                            neededrole, null, null, realm, null);
                                    Realm2viewComponentHbm r = getRealm2viewComponentHbmDao().create(tempRealm);
                                    viewComponent.setRealm2vc(r);
                                } else {
                                    relNode = XercesHelper.findNode(nodeRealm, "jaasRealmId");
                                    if (relNode != null) {
                                        Integer id = new Integer(XercesHelper.getNodeValue(relNode));
                                        RealmJaasHbm realm = null;
                                        if (useNewIds) {
                                            realm = getRealmJaasHbmDao().load(mappingRealmsJaas.get(id));
                                        } else {
                                            realm = getRealmJaasHbmDao().load(id);
                                        }
                                        Realm2viewComponentHbm tempRealm = createTempRealm(viewComponent,
                                                neededrole, null, null, null, realm);
                                        Realm2viewComponentHbm r = getRealm2viewComponentHbmDao()
                                                .create(tempRealm);
                                        viewComponent.setRealm2vc(r);
                                    }
                                }
                            }
                        }
                    } else {
                        Realm2viewComponentHbm tempRealm = new Realm2viewComponentHbmImpl();
                        tempRealm.setViewComponent(viewComponent);
                        Realm2viewComponentHbm r = getRealm2viewComponentHbmDao().create(tempRealm);
                        viewComponent.setRealm2vc(r);
                        String loginPage = XercesHelper.getNodeValue(nodeRealm, "loginPageId");
                        if (loginPage != null && !"".equalsIgnoreCase(loginPage)) {
                            Integer loginPageId = null;
                            try {
                                loginPageId = Integer.valueOf(loginPage);
                            } catch (Exception e) {
                            }
                            if (loginPageId != null)
                                loginPagesRealm2vc.put(vcId, loginPageId);
                        }
                    }
                }
            }
            // CONTENT
            Element cnde = (Element) XercesHelper.findNode(nde, "./content");
            if (cnde != null) {
                ContentHbm content = getContentHbmDao().createFromXml(cnde, reusePrimaryKey, livedeploy, null,
                        null, null, null);
                viewComponent.setReference(content.getContentId().toString());
            }
            // CHILDREN
            Iterator it = XercesHelper.findNodes(nde, "./viewcomponent");
            ViewComponentHbm childprev = null;
            ViewComponentHbm tmp = null;
            while (it.hasNext()) {
                Element childnode = (Element) it.next();
                tmp = createViewComponent(unitId, viewDocument, savedUnits, childnode, viewComponent, childprev,
                        livedeploy, fulldeploy, useNewIds);
                if (childprev != null) {
                    childprev.setNextNode(tmp);
                } else {
                    viewComponent.setFirstChild(tmp);
                }
                if (tmp != null)
                    childprev = tmp;
            }
        } else {
            // Im a ViewComponent from another Unit. This must be inside the Array... HEY ARRAY !!!
            boolean found = false;
            Iterator it = savedUnits.iterator();
            while (it.hasNext()) {
                ViewComponentHbm savedvc = (ViewComponentHbm) it.next();
                if (myUnitId.equals(savedvc.getAssignedUnit().getUnitId())) {
                    viewComponent = savedvc;
                    viewComponent.setPrevNode(prev);
                    byte showtype = viewComponent.getShowType();
                    viewComponent.setParentViewComponent(parent);
                    viewComponent.setShowType(showtype);
                    savedUnits.remove(savedvc);
                    found = true;
                    if (log.isDebugEnabled())
                        log.debug("MOVING BACK: " + viewComponent.getDisplayLinkName());
                    break;
                }
            }
            if (!found) {
                // This means: We are importing a Edition, where we suggest, that there is already this
                // Unit deployed, what we have as child-Unit.
                // It is possible, that we are deploying a unit, where this child-Unis haven't deployed yet -
                // f.e. initial-deploy or this child-unit has been new created and never deployed at this special
                // moment.
                // Therefor we will create a DUMMY entry with a "DUMMY"-Reference, so we can map the child-unit to
                // this place, if the child-Unit Editor wants to deploy his unit.
                try {
                    // FIRST we will take a look, if there is already this Unit - but wasn't found here.
                    // This could be possible, if this unit was been "outtaked" and this is an old Edition,
                    // we will find this Unit anywhere else.
                    viewComponent = getViewComponentHbmDao().find4Unit(myUnitId,
                            viewDocument.getViewDocumentId());
                } catch (Exception exe) {
                    try {
                        UnitHbm unit = getUnitHbmDao().load(myUnitId);
                        ViewComponentHbm tempVC = new ViewComponentHbmImpl();
                        tempVC.setViewDocument(viewDocument);
                        tempVC.setReference("DUMMY");
                        tempVC.setDisplayLinkName("SUB_ENTRY_NOT_DEPLOYED");
                        tempVC.setLinkDescription("SUB_ENTRY_NOT_DEPLOYED");
                        tempVC.setViewComponentId(vcId);
                        viewComponent = getViewComponentHbmDao().create(tempVC);
                        viewComponent.setViewType(Constants.VIEW_TYPE_UNIT);
                        viewComponent.setVisible(false);
                        viewComponent.setAssignedUnit(unit);
                    } catch (Exception ex) {
                        // Jens - ??
                        // context.setRollbackOnly();
                        throw new UserException("UnitWasNeverDeployed");
                    }
                }
                viewComponent.setPrevNode(prev);
                viewComponent.setParentViewComponent(parent);
            }
        }
    } catch (Exception exe) {
        // Jens - ??
        // context.setRollbackOnly();
        log.error("Error occured", exe);
        throw exe;
    }
    // IMPORT END
    return viewComponent;
}