Example usage for java.lang Integer longValue

List of usage examples for java.lang Integer longValue

Introduction

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

Prototype

public long longValue() 

Source Link

Document

Returns the value of this Integer as a long after a widening primitive conversion.

Usage

From source file:com.redhat.rhn.frontend.xmlrpc.system.SystemHandler.java

/**
 * Deletes the given note from the server.
 *
 * @param loggedInUser The current user/* w  w  w. j  a va 2  s .c o  m*/
 * @param sid        identifies the server on which the note resides
 * @param nid        identifies the note to delete
 * @return 1 if successful, exception otherwise
 * @throws NoSuchSystemException A NoSuchSystemException is thrown if the server
 * corresponding to sid cannot be found.
 *
 * @xmlrpc.doc Deletes the given note from the server.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param("int", "serverId")
 * @xmlrpc.param #param("int", "noteId")
 * @xmlrpc.returntype #return_int_success()
 */
public int deleteNote(User loggedInUser, Integer sid, Integer nid) {
    if (sid == null) {
        throw new IllegalArgumentException("sid cannot be null");
    }

    if (nid == null) {
        throw new IllegalArgumentException("nid cannot be null");
    }

    SystemManager.deleteNote(loggedInUser, sid.longValue(), nid.longValue());

    return 1;
}

From source file:com.redhat.rhn.frontend.xmlrpc.system.SystemHandler.java

/**
 * Get the latest available version of a package for each system
 * @param loggedInUser The current user/*  w  ww. j  ava2  s . c  o m*/
 * @param systemIds The IDs of the systems in question
 * @param name the package name
 * @return Returns an a map with the latest available package for each system
 * @throws FaultException A FaultException is thrown if the server corresponding to
 * sid cannot be found.
 *
 * @xmlrpc.doc Get the latest available version of a package for each system
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #array_single("int", "serverId")
 * @xmlrpc.param #param("string", "packageName")
 * @xmlrpc.returntype
 *     #array()
 *         #struct("system")
 *             #prop_desc("int", "id", "server ID")
 *             #prop_desc("string", "name", "server name")
 *             #prop_desc("struct", "package", "package structure")
 *                 #struct("package")
 *                     #prop("int", "id")
 *                     #prop("string", "name")
 *                     #prop("string", "version")
 *                     #prop("string", "release")
 *                     #prop("string", "epoch")
 *                     #prop("string", "arch")
 *                #struct_end()
 *        #struct_end()
 *    #array_end()
 */
public List<Map<String, Object>> listLatestAvailablePackage(User loggedInUser, List<Integer> systemIds,
        String name) throws FaultException {

    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

    for (Integer sid : systemIds) {
        Server server = lookupServer(loggedInUser, sid);

        Map<String, Object> systemMap = new HashMap<String, Object>();

        // get the package name ID
        Map pkgEvr = PackageManager.lookupEvrIdByPackageName(sid.longValue(), name);

        if (pkgEvr != null) {
            // find the latest package available to each system
            Package pkg = PackageManager.guestimatePackageBySystem(sid.longValue(),
                    (Long) pkgEvr.get("name_id"), (Long) pkgEvr.get("evr_id"), null, loggedInUser.getOrg());

            // build the hash to return
            if (pkg != null) {
                Map<String, Object> pkgMap = new HashMap<String, Object>();
                pkgMap.put("id", pkg.getId());
                pkgMap.put("name", pkg.getPackageName().getName());
                pkgMap.put("version", pkg.getPackageEvr().getVersion());
                pkgMap.put("release", pkg.getPackageEvr().getRelease());
                pkgMap.put("arch", pkg.getPackageArch().getLabel());

                if (pkg.getPackageEvr().getEpoch() != null) {
                    pkgMap.put("epoch", pkg.getPackageEvr().getEpoch());
                } else {
                    pkgMap.put("epoch", "");
                }

                systemMap.put("id", sid);
                systemMap.put("name", server.getName());
                systemMap.put("package", pkgMap);

                list.add(systemMap);
            }
        }
    }

    return list;
}

From source file:org.egov.services.payment.PaymentService.java

@Transactional
public List<InstrumentHeader> createInstrument(final List<ChequeAssignment> chequeAssignmentList,
        final String paymentMode, final Integer bankaccount, final Map<String, String[]> parameters,
        final Department dept) throws ApplicationRuntimeException, Exception {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Starting createInstrument...");
    List<InstrumentHeader> instHeaderList = new ArrayList<InstrumentHeader>();
    final List<Long> selectedPaymentVHList = new ArrayList<Long>();
    final Map<String, BigDecimal> payeeMap = new HashMap<String, BigDecimal>();
    BigDecimal totalPaidAmt = BigDecimal.ZERO;

    for (final ChequeAssignment assignment : chequeAssignmentList)
        if (assignment.getIsSelected()) {
            selectedPaymentVHList.add(assignment.getVoucherid());
            if (payeeMap.containsKey(assignment.getPaidTo() + DELIMETER + assignment.getDetailtypeid()
                    + DELIMETER + assignment.getDetailkeyid())) // concatenate the
                                                                                                                                                           // amount, if the
                                                                                                                                                           // party's are same
                payeeMap.put(//w w w .  j  a  va 2 s  .com
                        assignment.getPaidTo() + DELIMETER + assignment.getDetailtypeid() + DELIMETER
                                + assignment.getDetailkeyid(),
                        payeeMap.get(assignment.getPaidTo() + DELIMETER + assignment.getDetailtypeid()
                                + DELIMETER + assignment.getDetailkeyid()).add(assignment.getPaidAmount()));
            else
                payeeMap.put(assignment.getPaidTo() + DELIMETER + assignment.getDetailtypeid() + DELIMETER
                        + assignment.getDetailkeyid(), assignment.getPaidAmount());
            totalPaidAmt = totalPaidAmt.add(assignment.getPaidAmount());
        }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("selectedPaymentList===" + selectedPaymentVHList);
    final Bankaccount account = (Bankaccount) persistenceService.find(" from Bankaccount where  id=?",
            bankaccount.longValue());
    // get voucherList
    final List<CVoucherHeader> voucherList = persistenceService.findAllByNamedQuery("getVoucherList",
            selectedPaymentVHList);

    final List<Map<String, Object>> instrumentHeaderList = new ArrayList<Map<String, Object>>();
    final List<Map<String, Object>> instrumentVoucherList = new ArrayList<Map<String, Object>>();

    if (paymentMode.equals(FinancialConstants.MODEOFPAYMENT_CHEQUE)) {
        final Map<Long, CVoucherHeader> paymentVoucherMap = new HashMap<Long, CVoucherHeader>();
        for (final CVoucherHeader voucherHeader : voucherList)
            paymentVoucherMap.put(voucherHeader.getId(), voucherHeader);

        if (isChequeNoGenerationAuto()) // if cheque number generation is
                                        // auto
        {
            // get chequeNumber
            final String chequeNo = chequeService.nextChequeNumber(account.getId().toString(), payeeMap.size(),
                    dept.getId().intValue());
            final String[] chequeNoArray = StringUtils.split(chequeNo, ",");

            // create instrument header
            final Map<String, String> chequeNoMap = new HashMap<String, String>();
            final Iterator iterator = payeeMap.keySet().iterator();
            String key; // paidTo+delimeter+detailtypeid+delimeter+detailkeyid
            int i = 0;
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                instrumentHeaderList.add(prepareInstrumentHeader(account, chequeNoArray[i],
                        FinancialConstants.MODEOFPAYMENT_CHEQUE.toLowerCase(), key.split(DELIMETER)[0],
                        payeeMap.get(key), currentDate, key, null));
                chequeNoMap.put(key, chequeNoArray[i]);
                i++;
            }
            instHeaderList = instrumentService.addToInstrument(instrumentHeaderList);

            // create instrument voucher
            for (final ChequeAssignment assignment : chequeAssignmentList)
                if (assignment.getIsSelected())
                    instrumentVoucherList.add(preapreInstrumentVoucher(
                            paymentVoucherMap.get(assignment.getVoucherid()), account,
                            chequeNoMap.get(assignment.getPaidTo() + DELIMETER + assignment.getDetailtypeid()
                                    + DELIMETER + assignment.getDetailkeyid()),
                            assignment.getPaidTo()));
            instVoucherList = instrumentService.updateInstrumentVoucherReference(instrumentVoucherList);
        } else // for manual cheque number
        {
            String text = "";
            final Map<String, BigDecimal> partyChequeNoMap = new HashMap<String, BigDecimal>();
            for (final ChequeAssignment assignment : chequeAssignmentList)
                if (assignment.getIsSelected()) {
                    text = assignment.getPaidTo() + DELIMETER + assignment.getDetailtypeid() + DELIMETER
                            + assignment.getDetailkeyid() + DELIMETER + assignment.getChequeNumber() + DELIMETER
                            + formatter.format(assignment.getChequeDate()) + DELIMETER
                            + assignment.getSerialNo();
                    if (partyChequeNoMap.containsKey(text))
                        partyChequeNoMap.put(text, partyChequeNoMap.get(text).add(assignment.getPaidAmount()));
                    else
                        partyChequeNoMap.put(text, assignment.getPaidAmount());
                }
            final Iterator iterator = partyChequeNoMap.keySet().iterator();
            String key;
            while (iterator.hasNext()) // create instrument header
            {
                key = iterator.next().toString();

                instrumentHeaderList.add(prepareInstrumentHeader(account, key.split(DELIMETER)[3],
                        FinancialConstants.MODEOFPAYMENT_CHEQUE.toLowerCase(), key.split(DELIMETER)[0],
                        partyChequeNoMap.get(key), formatter.parse(key.split(DELIMETER)[4]), key,
                        key.split(DELIMETER)[5]));
            }
            instHeaderList = instrumentService.addToInstrument(instrumentHeaderList);
            // create instrument voucher
            for (final ChequeAssignment assignment : chequeAssignmentList)
                if (assignment.getIsSelected())
                    instrumentVoucherList.add(preapreInstrumentVoucher(
                            paymentVoucherMap.get(assignment.getVoucherid()), account,
                            assignment.getChequeNumber(), assignment.getPaidTo(), assignment.getSerialNo()));
            instVoucherList = instrumentService.updateInstrumentVoucherReference(instrumentVoucherList);
        } // end of manual cheque number
    }
    // if it's cash or RTGS
    else {
        final String chequeNo;
        if (paymentMode.equals(FinancialConstants.MODEOFPAYMENT_RTGS))
            instrumentHeaderList.add(prepareInstrumentHeaderForRtgs(account, parameters.get("rtgsRefNo")[0],
                    totalPaidAmt, formatter.parse(parameters.get("rtgsDate")[0]), ""));
        else if (isChequeNoGenerationAuto()) // if cheque number generation
                                             // is auto
        {
            chequeNo = chequeService.nextChequeNumber(account.getId().toString(), 1, dept.getId().intValue());
            instrumentHeaderList.add(prepareInstrumentHeader(account, chequeNo,
                    FinancialConstants.MODEOFPAYMENT_CHEQUE.toLowerCase(), parameters.get("inFavourOf")[0],
                    totalPaidAmt, currentDate, "", null));
        } else
            instrumentHeaderList.add(prepareInstrumentHeader(account, parameters.get("chequeNo")[0],
                    FinancialConstants.MODEOFPAYMENT_CHEQUE.toLowerCase(), parameters.get("inFavourOf")[0],
                    totalPaidAmt, formatter.parse(parameters.get("chequeDt")[0]), "",
                    parameters.get("serialNo")[0]));

        instHeaderList = instrumentService.addToInstrument(instrumentHeaderList);

        final List<Paymentheader> paymentList = persistenceService.findAllByNamedQuery("getPaymentList",
                selectedPaymentVHList);
        Map<String, Object> instrumentVoucherMap = null;
        for (final Paymentheader paymentheader : paymentList) {
            instrumentVoucherMap = new HashMap<String, Object>();
            instrumentVoucherMap.put(VoucherConstant.VOUCHER_HEADER, paymentheader.getVoucherheader());
            instrumentVoucherMap.put(VoucherConstant.INSTRUMENT_HEADER, instHeaderList.get(0));
            instrumentVoucherList.add(instrumentVoucherMap);
        }
        instVoucherList = instrumentService.updateInstrumentVoucherReference(instrumentVoucherList);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Completed createInstrument.");
    return instHeaderList;
}

From source file:com.redhat.rhn.frontend.xmlrpc.system.SystemHandler.java

/**
 * Set a servers membership in a given group
 * @param loggedInUser The current user// w w w  .  java  2s .c  o m
 * @param sid The id of the server in question
 * @param sgid The id of the server group
 * @param member Should this server be a member of this group?
 * @return Returns 1 if successful, exception otherwise
 * @throws FaultException A FaultException is thrown if the server corresponding to
 * sid cannot be found.
 *
 * @xmlrpc.doc Set a servers membership in a given group.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param("int", "serverId")
 * @xmlrpc.param #param("int", "serverGroupId")
 * @xmlrpc.param #param_desc("boolean", "member",  "'1' to assign the given server to
 * the given server group, '0' to remove the given server from the given server
 * group.")
 * @xmlrpc.returntype #return_int_success()
 */
public int setGroupMembership(User loggedInUser, Integer sid, Integer sgid, boolean member)
        throws FaultException {
    // Get the logged in user and server
    ensureSystemGroupAdmin(loggedInUser);
    Server server = lookupServer(loggedInUser, sid);
    ServerGroupManager manager = ServerGroupManager.getInstance();
    try {
        ManagedServerGroup group = manager.lookup(new Long(sgid.longValue()), loggedInUser);

        List<Server> servers = new ArrayList<Server>(1);
        servers.add(server);

        if (member) {
            //add to server group
            manager.addServers(group, servers, loggedInUser);
        } else {
            //remove from server group
            manager.removeServers(group, servers, loggedInUser);
        }
    } catch (LookupException le) {
        throw new PermissionCheckFailureException(le);
    }

    return 1;
}

From source file:org.egov.pims.service.EmployeeServiceImpl.java

@Deprecated
public List searchEmployee(Integer departmentId, Integer designationId, String code, String name,
        String searchAll) throws Exception {

    List<EmployeeView> employeeList = null;
    try {// w  w w  .  ja v a 2  s.  c o m

        String mainStr = "from EmployeeView ev where";
        if (code != null && !code.equals("")) {
            mainStr += " upper(trim(ev.employeeCode)) = :employeeCode and ";
        }
        if (departmentId.intValue() != 0) {
            mainStr += " ev.deptId.id= :deptId and ";
        }
        if (designationId.intValue() != 0) {
            mainStr += " ev.desigId.designationId = :designationId and ";
        }
        if (name != null && !name.equals("")) {
            mainStr += " trim(upper(ev.employeeName))  like '%" + name.trim().toUpperCase() + "%' and ";
        }
        /*
         * if(code!=null&&!code.equals("")) { mainStr
         * +=" where upper(trim(ev.employeeCode)) = :employeeCode "; } else
         * {
         */
        if ((searchAll.equals("false") && designationId.intValue() != 0)) {
            mainStr += " ((ev.toDate is null and ev.fromDate <= SYSDATE ) OR (ev.fromDate <= SYSDATE AND ev.toDate > SYSDATE)) and ev.isActive = '1' ";
        } else if ((searchAll.equals("true") && designationId.intValue() != 0)) {
            mainStr += " ((ev.toDate is null and ev.fromDate <= SYSDATE ) OR (ev.fromDate <= SYSDATE AND ev.toDate > SYSDATE)) ";
        }
        // Inspite of SearchAll is true or false, if employee code is
        // entered, search for all active and inactive employees
        else if (code != null && !code.equals("")) {
            mainStr += "  ((ev.toDate IS NULL AND ev.fromDate <= SYSDATE) OR (ev.fromDate <= SYSDATE AND ev.toDate > SYSDATE) "
                    + " OR (ev.fromDate IN (SELECT MAX (evn.fromDate)  FROM EmployeeView  evn   "
                    + " WHERE evn.id = ev.id AND NOT EXISTS  (SELECT evn2.id FROM EmployeeView evn2 WHERE evn2.id = ev.id AND "
                    + " ((evn2.toDate  IS NULL AND evn2.fromDate <= SYSDATE) OR (evn2.fromDate <= SYSDATE AND evn2.toDate > SYSDATE)) )))) ";
        } else if (searchAll.equals("true") && designationId.intValue() == 0) {
            mainStr += "  ((ev.toDate IS NULL AND ev.fromDate <= SYSDATE) OR (ev.fromDate <= SYSDATE AND ev.toDate > SYSDATE) "
                    + " OR (ev.fromDate IN (SELECT MAX (evn.fromDate)  FROM EmployeeView  evn   "
                    + " WHERE evn.id = ev.id AND NOT EXISTS  (SELECT evn2.id FROM EmployeeView evn2 WHERE evn2.id = ev.id AND "
                    + " ((evn2.toDate  IS NULL AND evn2.fromDate <= SYSDATE) OR (evn2.fromDate <= SYSDATE AND evn2.toDate > SYSDATE)) )))) ";
        } else {
            mainStr += " ((ev.toDate is null and ev.fromDate <= SYSDATE ) OR (ev.fromDate <= SYSDATE AND ev.toDate > SYSDATE)) ";
        }
        // }

        Query qry = null;
        qry = getCurrentSession().createQuery(mainStr);
        LOGGER.info("qryqryqryqry" + qry.toString());
        if (code != null && !code.equals("")) {
            qry.setString("employeeCode", code.trim().toUpperCase());
        }
        if (departmentId.intValue() != 0) {
            qry.setLong("deptId", departmentId.longValue());
        }
        if (designationId.intValue() != 0) {
            qry.setInteger("designationId", designationId);
        }
        employeeList = (List) qry.list();

    } catch (HibernateException he) {
        LOGGER.error(he);
        throw new ApplicationRuntimeException("Exception:" + he.getMessage(), he);
    } catch (Exception he) {
        LOGGER.error(he);

        throw new ApplicationRuntimeException("Exception:" + he.getMessage(), he);

    }
    return employeeList;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.UploadTable.java

/**
 * @param fld/*from   w w  w.j  ava 2 s. c o  m*/
 * @param rec
 * @param newVal
 * @return true if fields value has changed.
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 */
@SuppressWarnings("unchecked")
protected boolean valueChange(DataModelObjBase rec, Method getter, Object[] newVal)
        throws InvocationTargetException, IllegalAccessException {
    boolean result = false;
    if (getter != null && rec != null) {
        Object currentVal = getter.invoke(rec);
        Object newValObj = newVal[0];
        if (currentVal == null ^ newValObj == null) {
            result = true;
        } else if (currentVal != null && newValObj != null) {
            if (currentVal instanceof DataModelObjBase) {
                Integer currentValId = ((DataModelObjBase) currentVal).getId();
                Integer newValObjId = ((DataModelObjBase) newValObj).getId();
                if (currentValId == null ^ newValObjId == null) {
                    result = true;
                } else {
                    result = currentValId.longValue() != newValObjId.longValue();
                }
            } else if (currentVal instanceof Comparable<?>) {
                result = ((Comparable<Object>) currentVal).compareTo((Comparable<?>) newValObj) != 0;
            } else {
                result = !currentVal.equals(newValObj); //how well will this work?
            }
        }
    }
    return result;
}

From source file:com.redhat.rhn.frontend.xmlrpc.system.SystemHandler.java

/**
 * Provision a guest on the server specified.
 *
 * @param loggedInUser The current user/* ww  w .  jav a 2s .  c  om*/
 * @param sid of server to provision guest on
 * @param guestName to assign to guest
 * @param profileName of Kickstart Profile to use.
 * @param memoryMb to allocate to the guest (maxMemory)
 * @param vcpus to assign
 * @param storageGb to assign to disk
 * @param macAddress to assign
 * @return Returns 1 if successful, exception otherwise
 *
 * @xmlrpc.doc Provision a guest on the host specified.  This schedules the guest
 * for creation and will begin the provisioning process when the host checks in
 * or if OSAD is enabled will begin immediately.
 *
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param_desc("int", "serverId", "ID of host to provision guest on.")
 * @xmlrpc.param #param("string", "guestName")
 * @xmlrpc.param #param_desc("string", "profileName", "Kickstart Profile to use.")
 * @xmlrpc.param #param_desc("int", "memoryMb", "Memory to allocate to the guest")
 * @xmlrpc.param #param_desc("int", "vcpus", "Number of virtual CPUs to allocate to
 *                                          the guest.")
 * @xmlrpc.param #param_desc("int", "storageGb", "Size of the guests disk image.")
 * @xmlrpc.param #param_desc("string", "macAddress", "macAddress to give the guest's
 *                                          virtual networking hardware.")
 * @xmlrpc.returntype #return_int_success()
 */
public int provisionVirtualGuest(User loggedInUser, Integer sid, String guestName, String profileName,
        Integer memoryMb, Integer vcpus, Integer storageGb, String macAddress) {
    log.debug("provisionVirtualGuest called.");
    // Lookup the server so we can validate it exists and throw error if not.
    lookupServer(loggedInUser, sid);
    KickstartData ksdata = KickstartFactory.lookupKickstartDataByLabelAndOrgId(profileName,
            loggedInUser.getOrg().getId());

    if (ksdata == null) {
        throw new FaultException(-3, "kickstartProfileNotFound",
                "No Kickstart Profile found with label: " + profileName);
    }

    ProvisionVirtualInstanceCommand cmd = new ProvisionVirtualInstanceCommand(new Long(sid.longValue()),
            ksdata.getId(), loggedInUser, new Date(), ConfigDefaults.get().getCobblerHost());

    cmd.setGuestName(guestName);
    cmd.setMemoryAllocation(new Long(memoryMb));
    cmd.setVirtualCpus(new Long(vcpus.toString()));
    cmd.setLocalStorageSize(new Long(storageGb));
    // setting an empty string generates a random mac address
    cmd.setMacAddress(macAddress);
    // setting an empty string generates a default virt path
    cmd.setFilePath("");
    // Store the new KickstartSession to the DB.
    ValidatorError ve = cmd.store();
    if (ve != null) {
        throw new FaultException(-2, "provisionError",
                LocalizationService.getInstance().getMessage(ve.getKey(), ve.getValues()));
    }

    return 1;
}

From source file:com.redhat.rhn.frontend.xmlrpc.system.SystemHandler.java

/**
 * Set server details./* w  w w  . j  a  v a2s.  c o  m*/
 *
 * @param loggedInUser The current user
 * @param serverId ID of server to lookup details for.
 * @param details Map of (optional) system details to be set.
 * @return 1 on success, exception thrown otherwise.
 *
 * @xmlrpc.doc Set server details. All arguments are optional and will only be modified
 * if included in the struct.
 * @xmlrpc.param #param("string", "sessionKey")
 * @xmlrpc.param #param_desc("int", "serverId", "ID of server to lookup details for.")
 * @xmlrpc.param
 *      #struct("server details")
 *          #prop_desc("string", "profile_name", "System's profile name")
 *          #prop_desc("string", "base_entitlement", "System's base entitlement label.
 *                      (enterprise_entitled or sw_mgr_entitled)")
 *           #prop_desc("boolean", "auto_errata_update", "True if system has
 *                          auto errata updates enabled")
 *           #prop_desc("string", "description", "System description")
 *           #prop_desc("string", "address1", "System's address line 1.")
 *           #prop_desc("string", "address2", "System's address line 2.")
 *           #prop("string", "city")
 *           #prop("string", "state")
 *           #prop("string", "country")
 *           #prop("string", "building")
 *           #prop("string", "room")
 *           #prop("string", "rack")
 *     #struct_end()
 *
 *  @xmlrpc.returntype #return_int_success()
 */
public Integer setDetails(User loggedInUser, Integer serverId, Map<String, Object> details) {

    // confirm that the user only provided valid keys in the map
    Set<String> validKeys = new HashSet<String>();
    validKeys.add("profile_name");
    validKeys.add("base_entitlement");
    validKeys.add("auto_errata_update");
    validKeys.add("address1");
    validKeys.add("address2");
    validKeys.add("city");
    validKeys.add("state");
    validKeys.add("country");
    validKeys.add("building");
    validKeys.add("room");
    validKeys.add("rack");
    validKeys.add("description");
    validateMap(validKeys, details);

    Server server = null;
    try {
        server = SystemManager.lookupByIdAndUser(new Long(serverId.longValue()), loggedInUser);
    } catch (LookupException e) {
        throw new NoSuchSystemException();
    }

    if (details.containsKey("profile_name")) {
        String name = (String) details.get("profile_name");
        name = StringUtils.trim(name);
        validateProfileName(name);
        server.setName(name);
    }

    if (details.containsKey("description")) {
        server.setDescription((String) details.get("description"));
    }

    if (details.containsKey("base_entitlement")) {
        // Raise exception if user attempts to set base entitlement but isn't an org
        // admin:
        if (!loggedInUser.hasRole(RoleFactory.ORG_ADMIN)) {
            throw new PermissionCheckFailureException();
        }

        String selectedEnt = (String) details.get("base_entitlement");
        Entitlement base = EntitlementManager.getByName(selectedEnt);
        if (base != null) {
            server.setBaseEntitlement(base);
        } else if (selectedEnt.equals("unentitle")) {
            SystemManager.removeAllServerEntitlements(server.getId());
        }
    }

    if (details.containsKey("auto_errata_update")) {
        Boolean autoUpdate = (Boolean) details.get("auto_errata_update");

        if (autoUpdate.booleanValue()) {
            if (server.getAutoUpdate().equals("N")) {
                // schedule errata update only it if the value has changed
                ActionManager.scheduleAllErrataUpdate(loggedInUser, server, new Date());
            }
            server.setAutoUpdate("Y");
        } else {
            server.setAutoUpdate("N");
        }
    }

    if (server.getLocation() == null) {
        Location l = new Location();
        server.setLocation(l);
        l.setServer(server);
    }

    if (details.containsKey("address1")) {
        server.getLocation().setAddress1((String) details.get("address1"));
    }
    if (details.containsKey("address2")) {
        server.getLocation().setAddress2((String) details.get("address2"));
    }
    if (details.containsKey("city")) {
        server.getLocation().setCity((String) details.get("city"));
    }
    if (details.containsKey("state")) {
        server.getLocation().setState((String) details.get("state"));
    }
    if (details.containsKey("country")) {
        String country = (String) details.get("country");
        Map<String, String> map = LocalizationService.getInstance().availableCountries();
        if (country.length() > 2 || !map.containsValue(country)) {
            throw new UnrecognizedCountryException(country);
        }
        server.getLocation().setCountry(country);
    }
    if (details.containsKey("building")) {
        server.getLocation().setBuilding((String) details.get("building"));
    }
    if (details.containsKey("room")) {
        server.getLocation().setRoom((String) details.get("room"));
    }
    if (details.containsKey("rack")) {
        server.getLocation().setRack((String) details.get("rack"));
    }

    return 1;
}

From source file:com.cloud.configuration.ConfigurationManagerImpl.java

@Override
@ActionEvent(eventType = EventTypes.EVENT_SERVICE_OFFERING_CREATE, eventDescription = "creating service offering")
public ServiceOffering createServiceOffering(final CreateServiceOfferingCmd cmd) {
    final Long userId = CallContext.current().getCallingUserId();

    final String name = cmd.getServiceOfferingName();
    if (name == null || name.length() == 0) {
        throw new InvalidParameterValueException(
                "Failed to create service offering: specify the name that has non-zero length");
    }//from   w w w . java 2 s  .com

    final String displayText = cmd.getDisplayText();
    if (displayText == null || displayText.length() == 0) {
        throw new InvalidParameterValueException("Failed to create service offering " + name
                + ": specify the display text that has non-zero length");
    }

    final Integer cpuNumber = cmd.getCpuNumber();
    final Integer cpuSpeed = cmd.getCpuSpeed();
    final Integer memory = cmd.getMemory();

    //restricting the createserviceoffering to allow setting all or none of the dynamic parameters to null
    if (cpuNumber == null || cpuSpeed == null || memory == null) {
        if (cpuNumber != null || cpuSpeed != null || memory != null) {
            throw new InvalidParameterValueException(
                    "For creating a custom compute offering cpu, cpu speed and memory all should be null");
        }
    }

    if (cpuNumber != null && (cpuNumber.intValue() <= 0 || cpuNumber.longValue() > Integer.MAX_VALUE)) {
        throw new InvalidParameterValueException("Failed to create service offering " + name
                + ": specify the cpu number value between 1 and " + Integer.MAX_VALUE);
    }
    if (cpuSpeed != null && (cpuSpeed.intValue() < 0 || cpuSpeed.longValue() > Integer.MAX_VALUE)) {
        throw new InvalidParameterValueException("Failed to create service offering " + name
                + ": specify the cpu speed value between 0 and " + Integer.MAX_VALUE);
    }
    if (memory != null && (memory.intValue() < 32 || memory.longValue() > Integer.MAX_VALUE)) {
        throw new InvalidParameterValueException("Failed to create service offering " + name
                + ": specify the memory value between 32 and " + Integer.MAX_VALUE + " MB");
    }

    // check if valid domain
    if (cmd.getDomainId() != null && _domainDao.findById(cmd.getDomainId()) == null) {
        throw new InvalidParameterValueException("Please specify a valid domain id");
    }

    final Boolean offerHA = cmd.getOfferHa();

    boolean localStorageRequired = false;
    final String storageType = cmd.getStorageType();
    if (storageType != null) {
        if (storageType.equalsIgnoreCase(ServiceOffering.StorageType.local.toString())) {
            if (offerHA) {
                throw new InvalidParameterValueException("HA offering with local storage is not supported. ");
            }
            localStorageRequired = true;
        } else if (!storageType.equalsIgnoreCase(ServiceOffering.StorageType.shared.toString())) {
            throw new InvalidParameterValueException("Invalid storage type " + storageType
                    + " specified, valid types are: 'local' and 'shared'");
        }
    }

    final Boolean limitCpuUse = cmd.GetLimitCpuUse();
    final Boolean volatileVm = cmd.getVolatileVm();

    final String vmTypeString = cmd.getSystemVmType();
    VirtualMachine.Type vmType = null;
    boolean allowNetworkRate = false;

    Boolean isCustomizedIops;

    if (cmd.getIsSystem()) {
        if (vmTypeString == null
                || VirtualMachine.Type.DomainRouter.toString().toLowerCase().equals(vmTypeString)) {
            vmType = VirtualMachine.Type.DomainRouter;
            allowNetworkRate = true;
        } else if (VirtualMachine.Type.ConsoleProxy.toString().toLowerCase().equals(vmTypeString)) {
            vmType = VirtualMachine.Type.ConsoleProxy;
        } else if (VirtualMachine.Type.SecondaryStorageVm.toString().toLowerCase().equals(vmTypeString)) {
            vmType = VirtualMachine.Type.SecondaryStorageVm;
        } else if (VirtualMachine.Type.InternalLoadBalancerVm.toString().toLowerCase().equals(vmTypeString)) {
            vmType = VirtualMachine.Type.InternalLoadBalancerVm;
        } else {
            throw new InvalidParameterValueException(
                    "Invalid systemVmType. Supported types are: " + VirtualMachine.Type.DomainRouter + ", "
                            + VirtualMachine.Type.ConsoleProxy + ", " + VirtualMachine.Type.SecondaryStorageVm);
        }

        if (cmd.isCustomizedIops() != null) {
            throw new InvalidParameterValueException(
                    "Customized IOPS is not a valid parameter for a system VM.");
        }

        isCustomizedIops = false;

        if (cmd.getHypervisorSnapshotReserve() != null) {
            throw new InvalidParameterValueException(
                    "Hypervisor snapshot reserve is not a valid parameter for a system VM.");
        }
    } else {
        allowNetworkRate = true;
        isCustomizedIops = cmd.isCustomizedIops();
    }

    if (cmd.getNetworkRate() != null) {
        if (!allowNetworkRate) {
            throw new InvalidParameterValueException(
                    "Network rate can be specified only for non-System offering and system offerings having \"domainrouter\" systemvmtype");
        }
        if (cmd.getNetworkRate().intValue() < 1) {
            throw new InvalidParameterValueException("Failed to create service offering " + name
                    + ": specify the network rate value more than 0");
        }
    }

    if (cmd.getDeploymentPlanner() != null) {
        final List<String> planners = _mgr.listDeploymentPlanners();
        if (planners != null && !planners.isEmpty()) {
            if (!planners.contains(cmd.getDeploymentPlanner())) {
                throw new InvalidParameterValueException(
                        "Invalid name for Deployment Planner specified, please use listDeploymentPlanners to get the valid set");
            }
        } else {
            throw new InvalidParameterValueException("No deployment planners found");
        }
    }

    return createServiceOffering(userId, cmd.getIsSystem(), vmType, cmd.getServiceOfferingName(), cpuNumber,
            memory, cpuSpeed, cmd.getDisplayText(), cmd.getProvisioningType(), localStorageRequired, offerHA,
            limitCpuUse, volatileVm, cmd.getTags(), cmd.getDomainId(), cmd.getHostTag(), cmd.getNetworkRate(),
            cmd.getDeploymentPlanner(), cmd.getDetails(), isCustomizedIops, cmd.getMinIops(), cmd.getMaxIops(),
            cmd.getBytesReadRate(), cmd.getBytesWriteRate(), cmd.getIopsReadRate(), cmd.getIopsWriteRate(),
            cmd.getHypervisorSnapshotReserve());
}

From source file:ca.oson.json.Oson.java

private <E, R> R json2IntegerDefault(FieldData objectDTO) {
    E value = (E) objectDTO.valueToProcess;
    Class<R> returnType = objectDTO.returnType;
    boolean required = objectDTO.required();

    if (returnType == int.class || getDefaultType() == JSON_INCLUDE.DEFAULT || required) {
        Integer defaultValue = (Integer) objectDTO.getDefaultValue();
        Long min = objectDTO.getMin();
        Long max = objectDTO.getMax();
        if (defaultValue != null) {
            if (min != null && min > defaultValue.longValue()) {
                return (R) (Integer) min.intValue();
            }//from www .  ja v  a  2 s .c o m

            return (R) defaultValue;
        }

        if (min != null && min > DefaultValue.integer) {
            return (R) (Integer) min.intValue();
        }

        return (R) DefaultValue.integer;
    }

    return null;
}