Example usage for java.util HashMap clear

List of usage examples for java.util HashMap clear

Introduction

In this page you can find the example usage for java.util HashMap clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the mappings from this map.

Usage

From source file:com.krawler.crm.reportBuilder.bizservice.ReportBuilderServiceImpl.java

public JSONObject getDataCustomReport(String companyid, String searchJson, String groupByColumns, String ss,
        String filterCol, String filterSS, boolean detailFlag, String fromDate, String toDate,
        String filterCombo, boolean heirarchyPerm, String field, String direction, String start, String limit,
        int moduleid, String query, String countquery, String masterIds, String[] quicksearchcol,
        ArrayList filter_names, ArrayList filter_params, HashMap<String, String> dataIndexReftableMap,
        String extraFilter) throws ServiceException {
    JSONObject jobj = new JSONObject();
    KwlReturnObject kmsg = null;//w w w . jav  a  2  s  .co m
    try {
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        if (!StringUtil.isNullOrEmpty(fromDate) && !StringUtil.isNullOrEmpty(toDate)
                && !StringUtil.isNullOrEmpty(filterCombo)) {
            requestParams.put("fromDate", fromDate);
            requestParams.put("toDate", toDate);
            requestParams.put("filterCombo", filterCombo);
        }
        requestParams.put("ss", ss);
        if (!StringUtil.isNullOrEmpty(filterCol) && !StringUtil.isNullOrEmpty(filterSS)) {
            requestParams.put("filterCol", filterCol);
            requestParams.put("filterSS", filterSS);
            requestParams.put("detailFlag", detailFlag);
        }
        requestParams.put("searchJson", searchJson);
        if (!StringUtil.isNullOrEmpty(start)) {
            requestParams.put("start", StringUtil.checkForNull(start));
            requestParams.put("limit", StringUtil.checkForNull(limit));
            requestParams.put("pagingFlag", true);
        } else {
            requestParams.put("pagingFlag", false);
        }
        requestParams.put("companyid", companyid);
        if (!StringUtil.isNullOrEmpty(field)) {
            requestParams.put("field", field);
            requestParams.put("direction", direction);
        }
        requestParams.put("heirarchyPerm", heirarchyPerm);
        requestParams.put("query", query);
        requestParams.put("countquery", countquery);
        if (!StringUtil.isNullOrEmpty(groupByColumns)) {
            requestParams.put("groupByColumns", groupByColumns);
        }
        if (!StringUtil.isNullOrEmpty(extraFilter)) {
            requestParams.put("extrafilter", extraFilter);
        }
        requestParams.put(Constants.moduleid, moduleid);
        requestParams.put("quicksearchcol", quicksearchcol);
        kmsg = reportBuilderDaoObj.getDataCustomReport(requestParams, filter_names, filter_params);
        SqlRowSet rs = (SqlRowSet) kmsg.getEntityList().get(0);

        //ToDo- Get ids of crmCombomaster table - Only fetch those combo which are present in report.
        filter_names.clear();
        filter_params.clear();
        filter_names.add("INc.crmCombomaster");
        filter_params.add(masterIds);
        filter_names.add("c.company.companyID");
        filter_params.add(companyid);
        requestParams.put(Constants.filter_names, filter_names);
        requestParams.put(Constants.filter_params, filter_params);
        HashMap<String, DefaultMasterItem> defaultMasterMap = getCrmCommonDAO()
                .getDefaultMasterItemsMap(requestParams);
        //ToDo - fetch map only custom drop-down columns present in the report. Add companyid filter while fetching customComboMap.
        requestParams.clear();
        HashMap<String, FieldComboData> customComboMap = getCrmCommonDAO()
                .getCustomComboItemsMap(requestParams);

        List<Object> ll = getIdsList(rs);
        List<String> idsList = (List<String>) ll.get(0);
        Boolean productColFlag = (Boolean) ll.get(1);

        //             Map<String, List<LeadOwnerInfo>> ownersMap = crmLeadDAOObj.getLeadOwners(idsList);
        Map ownersMap = new HashMap();
        Map<String, List<CrmProduct>> productsMap = new HashMap<String, List<CrmProduct>>();
        if (productColFlag) {
            switch (moduleid) {
            case 1: //Account
                productsMap = crmAccountDAOObj.getAccountProducts(idsList);
                break;
            case 2: //Lead
                //                            ownersMap = crmLeadDAOObj.getLeadOwners(idsList);
                productsMap = crmLeadDAOObj.getLeadProducts(idsList);
                break;
            case 3: //Case
                productsMap = crmCaseDAOObj.getCaseProducts(idsList);
                break;
            case 5: //Opportunity
                productsMap = crmOpportunityDAOObj.getOpportunityProducts(idsList);
                break;
            }
        }

        jobj = getReportJSON(moduleid, rs, defaultMasterMap, customComboMap, productsMap, ownersMap,
                dataIndexReftableMap, detailFlag, productColFlag);
        jobj.put("totalCount", kmsg.getRecordTotalCount());
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
    }
    return jobj;
}

From source file:com.ardhi.businessgame.services.BusinessGameService.java

/**
 * Calculate the installment's details. More likely, a ratio of equipment, employee, input and
 * output provided in one installment./* w ww  .j  a  va  2 s.  c om*/
 * 
 * @param idInstallment The id of an installment being called.
 * @return List of information regarding the details of an installment. The output will come as
 * follow : (0) type installment, (1) calculated efficiency, (2) calculated effectivity,
 * (3) list of input, (4) list of input ratio, (5) list of output, (6) list of output ratio, 
 * (7) whether the installment is active/inactive state.
 * 
 */
private ArrayList<String> calculateInstallmentAndIOByIdInstallment(String idInstallment) {
    String hiElement = "";
    double hiVal = 0, efficiency = 0, effectivity = 0;
    int eff;
    SqlRowSet srs1 = db.getJdbc()
            .queryForRowSet("select type,active from installment where id='" + idInstallment + "'"), srs2, srs3;
    HashMap<String, Double> elementsRatio = new HashMap<String, Double>(),
            elements = new HashMap<String, Double>(), elementsCalc = new HashMap<String, Double>();
    ArrayList<String> data = new ArrayList<String>(), input = new ArrayList<String>(),
            output = new ArrayList<String>();
    ArrayList<Double> inputVal = new ArrayList<Double>(), outputVal = new ArrayList<Double>();
    boolean pass = false;

    if (srs1.next()) {
        hiElement = "";
        hiVal = 0;
        elementsRatio.clear();
        elements.clear();
        elementsCalc.clear();
        pass = true;

        srs2 = db.getJdbc()
                .queryForRowSet("select equipment_type,items from info_sector_equipment where sector='"
                        + srs1.getString("type") + "'");
        while (srs2.next()) {
            elementsRatio.put(srs2.getString("equipment_type"), srs2.getDouble("items"));
            if (hiVal < srs2.getDouble("items")) {
                hiElement = srs2.getString("equipment_type");
                hiVal = srs2.getDouble("items");
            }
            srs3 = db.getJdbc().queryForRowSet(
                    "select count(installment_equipment.id) from installment_equipment,list_equipment,desc_equipment where installment='"
                            + idInstallment + "' and desc_equipment.equipment='"
                            + srs2.getString("equipment_type")
                            + "' and installment_equipment.id=list_equipment.id and list_equipment.[desc]=desc_equipment.id");
            srs3.next();
            elements.put(srs2.getString("equipment_type"), srs3.getDouble(1));
        }

        srs2 = db.getJdbc().queryForRowSet("select employee_type,items from info_sector_employee where sector='"
                + srs1.getString("type") + "'");
        while (srs2.next()) {
            elementsRatio.put(srs2.getString("employee_type"), srs2.getDouble("items"));
            if (hiVal < srs2.getDouble("items")) {
                hiElement = srs2.getString("employee_type");
                hiVal = srs2.getDouble("items");
            }
            srs3 = db.getJdbc().queryForRowSet(
                    "select count(installment_employee.id) from installment_employee,list_employee,desc_employee where installment='"
                            + idInstallment + "' and desc_employee.employee='" + srs2.getString("employee_type")
                            + "' and installment_employee.id=list_employee.id and list_employee.[desc]=desc_employee.id");
            srs3.next();
            elements.put(srs2.getString("employee_type"), srs3.getDouble(1));
        }

        //calculating:
        while (true) {
            for (String element : elementsRatio.keySet()) {
                if (element.equals(hiElement)) {
                    elementsCalc.put(element, elements.get(element));
                } else {
                    elementsCalc.put(element, (elementsRatio.get(element) * elements.get(hiElement))
                            / elementsRatio.get(hiElement));
                }
            }

            for (String element : elements.keySet()) {
                if (elements.get(element) < elementsCalc.get(element)) {
                    pass = false;
                    hiElement = element;
                    hiVal = elements.get(element);
                    break;
                } else {
                    pass = true;
                }
            }
            if (pass) {
                eff = elements.get(hiElement).intValue() / elementsRatio.get(hiElement).intValue();
                if (elements.get(hiElement) % elementsRatio.get(hiElement) > 0) {
                    hiVal = (elementsRatio.get(hiElement) * (eff + 1));
                    if (hiVal > 0)
                        efficiency = new BigDecimal(Double.valueOf(
                                elementsCalc.get(hiElement) / (elementsRatio.get(hiElement) * (eff + 1))))
                                        .setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
                    else
                        efficiency = 0;
                    effectivity = eff + 1;
                } else {
                    hiVal = (elementsRatio.get(hiElement) * eff);
                    if (hiVal > 0)
                        efficiency = new BigDecimal(Double
                                .valueOf(elementsCalc.get(hiElement) / (elementsRatio.get(hiElement) * eff)))
                                        .setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue();
                    else
                        efficiency = 0;
                    effectivity = eff;
                }
                srs2 = db.getJdbc()
                        .queryForRowSet("select input_type,size from info_sector_input where sector='"
                                + srs1.getString("type") + "'");
                while (srs2.next()) {
                    input.add(srs2.getString("input_type"));
                    inputVal.add(
                            new BigDecimal(Double.valueOf(srs2.getDouble("size") * effectivity * efficiency))
                                    .setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                }
                srs2 = db.getJdbc()
                        .queryForRowSet("select output_type,size from info_sector_output where sector='"
                                + srs1.getString("type") + "'");
                while (srs2.next()) {
                    output.add(srs2.getString("output_type"));
                    outputVal.add(
                            new BigDecimal(Double.valueOf(srs2.getDouble("size") * effectivity * efficiency))
                                    .setScale(2, BigDecimal.ROUND_HALF_EVEN).doubleValue());
                }
                break;
            }
        }
    }
    data.add(srs1.getString("type"));
    data.add(gson.toJson(efficiency));
    data.add(gson.toJson(effectivity));
    data.add(gson.toJson(input));
    data.add(gson.toJson(inputVal));
    data.add(gson.toJson(output));
    data.add(gson.toJson(outputVal));
    data.add(gson.toJson(srs1.getBoolean("active")));

    input = null;
    inputVal = null;
    output = null;
    outputVal = null;
    srs1 = null;
    srs2 = null;
    srs3 = null;

    gc();

    return data;
}

From source file:com.netcrest.pado.tools.pado.command.put.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Map getEntryMap(String fullPath, BufferInfo bufferInfo, List<String> list, boolean keyEnumerated,
        boolean valueEnumerated, int startIndex) throws Exception {
    String pairs = "";
    for (int i = startIndex; i < list.size(); i++) {
        pairs += list.get(i) + " ";
    }/*  w w  w .  ja  v a  2 s.  c om*/

    Map<String, Method> keySetterMap = ReflectionUtil.getAllSettersMap(padoShell.getKeyClass());
    Map<String, Method> valueSetterMap = ReflectionUtil.getAllSettersMap(padoShell.getValueClass());

    String gridPath = GridUtil.getChildPath(fullPath);
    String gridId = SharedCache.getSharedCache().getGridId(fullPath);
    IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IGridMapBiz.class,
            gridPath);
    gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);

    // (x='1,2,3' and y='2',a='hello, world' and b='test')
    HashMap map = new HashMap();
    StringBuffer buffer = new StringBuffer(pairs);
    boolean keySearch = false;
    boolean fieldSearch = false;
    boolean openQuote = false;
    boolean delimiter = false;
    boolean quoted = false;
    String fieldString = "";
    String valueString = "";
    String and = "";

    Object key = null;
    Object value = null;
    for (int i = 0; i < buffer.length(); i++) {
        char c = buffer.charAt(i);
        if (c == '(') {
            if (openQuote == false) {

                String function = null;
                String functionCall = null;
                String functionString = null;
                if (valueString.length() > 0) {
                    functionString = valueString;
                } else if (fieldString.length() > 0) {
                    functionString = fieldString;
                }
                if (functionString != null) {

                    // it's a function

                    // get enclosed parenthesis
                    int enclosedIndex = getEnclosingParenthesis(buffer, i);

                    function = functionString.toLowerCase();
                    if (enclosedIndex == -1) {
                        throw new ParseException("Malformed function call: " + function, i);
                    }

                    functionCall = function + buffer.substring(i, enclosedIndex + 1);
                    Logger.fine("functionCall = |" + functionCall + "|");
                    i = enclosedIndex;
                }
                if (functionCall != null) {
                    if (valueString.length() > 0) {
                        valueString = functionCall;
                    } else if (fieldString.length() > 0) {
                        fieldString = functionCall;
                    }

                } else {
                    key = null;
                    value = null;
                    keySearch = true;
                    fieldSearch = true;
                    fieldString = "";
                    valueString = "";
                }

                quoted = false;

                continue;
            }

        } else if (c == '=') {
            if (keySearch && key == null && keyEnumerated == false) {
                key = padoShell.getKeyClass().newInstance();
            }
            if (keySearch == false && value == null && valueEnumerated == false) {
                if (padoShell.getValueClass() == null) {
                    throw new ClassNotFoundException(
                            "Undefined value class. Use the 'value' command to set the class name");
                }
                value = padoShell.getValueClass().newInstance();
            }
            fieldSearch = false;
            continue;
        } else if (c == ')') {
            if (openQuote == false) {
                Logger.fine("v: field = " + fieldString);
                Logger.fine("v: value = " + valueString);
                Logger.fine("");

                if (valueEnumerated) {
                    Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                    if (k == null) {
                        PadoShell.printlnError(
                                "Error: value not found in the cache for the key number " + fieldString);
                        PadoShell.println("       run 'key -l' to view the enumerated keys.");
                        map.clear();
                        break;
                    }
                    value = gridMapBiz.get(k);
                    if (key == null) {
                        PadoShell.printlnError("Error: value not in the cache - " + fieldString);
                        map.clear();
                        break;
                    }
                    Logger.fine("k = " + k);
                    Logger.fine("key = " + key);
                    Logger.fine("value = " + value);
                } else {
                    if (valueString.length() == 0) {
                        // primitive
                        value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                    } else {
                        updateObject(valueSetterMap, value, fieldString, valueString);
                    }
                }

                map.put(key, value);

                fieldSearch = true;
                quoted = false;
                fieldString = "";
                valueString = "";
                key = null;
                and = "";
                continue;
            }
        } else if (c == '\\') {
            // ignore and treat the next character as a character
            delimiter = true;
            continue;
        } else if (c == '\'') {
            if (delimiter) {
                delimiter = false;
            } else {
                if (openQuote) {
                    quoted = true;
                }
                openQuote = !openQuote;
                continue;
            }
        } else if (c == ' ') {
            if (openQuote == false) {
                boolean andExpected = false;
                if (keySearch) {
                    Logger.fine("k: field = " + fieldString);
                    Logger.fine("k: value = " + valueString);
                    Logger.fine("");

                    if (fieldString.length() > 0) {
                        updateObject(keySetterMap, key, fieldString, valueString);
                        andExpected = true;
                    }
                } else {
                    Logger.fine("v: field = " + fieldString);
                    Logger.fine("v: value = " + valueString);
                    Logger.fine("");

                    if (fieldString.length() > 0) {
                        updateObject(valueSetterMap, value, fieldString, valueString);
                        andExpected = true;
                    }
                }

                if (andExpected) {
                    and = "";
                    int index = -1;
                    for (int j = i; j < buffer.length(); j++) {
                        and += buffer.charAt(j);
                        and = and.trim().toLowerCase();
                        if (and.equals("and")) {
                            index = j;
                            break;
                        } else if (and.length() > 3) {
                            break;
                        }
                    }
                    if (index != -1) {
                        i = index;
                    }
                }

                fieldSearch = true;
                fieldString = "";
                valueString = "";
                and = "";
                quoted = false;
                continue;
            }
        }

        if (c == ',') {

            // if ',' is not enclosed in quotes...
            if (openQuote == false) {

                fieldString = fieldString.trim();
                valueString = valueString.trim();

                // end of key
                Logger.fine("k: field = " + fieldString);
                Logger.fine("k: value = " + valueString);
                Logger.fine("");

                if (keySearch) {
                    if (keyEnumerated) {
                        key = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                        if (key == null) {
                            PadoShell.printlnError(
                                    "Error: value not found in the cache for the key number " + fieldString);
                            PadoShell.println("       run 'key -l' to view the enumerated keys.");
                            map.clear();
                            break;
                        }
                    } else {
                        if (valueString.length() == 0) {
                            key = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                        } else {
                            updateObject(keySetterMap, key, fieldString, valueString);
                        }
                    }
                } else {

                    if (valueEnumerated) {
                        Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                        value = gridMapBiz.get(k);
                        if (value == null) {
                            PadoShell.printlnError("Error: undefined value num " + fieldString);
                            map.clear();
                            break;
                        }
                    } else {
                        if (valueString.length() == 0) {
                            value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                        } else {

                            updateObject(valueSetterMap, value, fieldString, valueString);
                        }
                    }

                }

                fieldSearch = true;
                keySearch = false;
                quoted = false;
                fieldString = "";
                valueString = "";
                and = "";
                continue;
            }
        }

        if (fieldSearch) {
            fieldString += c;
        } else if (quoted == false) {
            valueString += c;
        }
    }

    return map;
}

From source file:org.waarp.openr66.database.data.DbHostConfiguration.java

/**
 * update Roles with possible purge and new or added content, and updating in memory information
 * /* w  w w .  j  av  a 2 s . co m*/
 * @param config
 * @param newroles
 * @param purged
 * @return True if ok
 */
public boolean updateRoles(Configuration config, String newroles, boolean purged) {
    HashMap<String, HashSet<String>> map = new HashMap<String, HashSet<String>>();
    if (!updateMap(newroles, XML_ROLES + "/" + XML_ROLE, XML_ROLEID, XML_ROLESET, " |\\|", map)) {
        return false;
    }
    if (purged) {
        config.roles.clear();
    } else {
        String roles = getRoles();
        if (!updateMap(roles, XML_ROLES + "/" + XML_ROLE, XML_ROLEID, XML_ROLESET, " |\\|", map)) {
            return false;
        }
    }
    if ((newroles != null && !newroles.isEmpty()) || purged) {
        Document document = DocumentHelper.createDocument(DocumentHelper.createElement(XML_ROLES));
        Element root = document.getRootElement();
        for (Entry<String, HashSet<String>> entry : map.entrySet()) {
            RoleDefault newrole = new RoleDefault();
            Element elt = root.addElement(XML_ROLE);
            elt.addElement(XML_ROLEID).setText(entry.getKey());
            String cumul = null;
            if (entry.getValue().contains(ROLE.NOACCESS.name())) {
                newrole.setRole(ROLE.NOACCESS);
                cumul = ROLE.NOACCESS.name();
            }
            for (String namerole : entry.getValue()) {
                try {
                    RoleDefault.ROLE roletype = RoleDefault.ROLE.valueOf(namerole.toUpperCase());
                    if (roletype != ROLE.NOACCESS) {
                        newrole.addRole(roletype);
                        if (cumul == null) {
                            cumul = namerole.toUpperCase();
                        } else {
                            cumul += " " + namerole.toUpperCase();
                        }
                    }
                } catch (IllegalArgumentException e) {
                    // ignore
                }
            }
            logger.info("New Role: " + entry.getKey() + ":" + newrole);
            config.roles.put(entry.getKey(), newrole);
            elt.addElement(XML_ROLESET).setText(cumul);
        }
        setRoles(root.asXML());
        try {
            update();
        } catch (WaarpDatabaseException e) {
            document.clearContent();
            document = null;
            return false;
        }
        document.clearContent();
        document = null;
    } else {
        for (Entry<String, HashSet<String>> entry : map.entrySet()) {
            RoleDefault newrole = new RoleDefault();
            if (entry.getValue().contains(ROLE.NOACCESS.name())) {
                newrole.setRole(ROLE.NOACCESS);
            }
            for (String namerole : entry.getValue()) {
                try {
                    RoleDefault.ROLE roletype = RoleDefault.ROLE.valueOf(namerole.toUpperCase());
                    if (roletype != ROLE.NOACCESS) {
                        newrole.addRole(roletype);
                    }
                } catch (IllegalArgumentException e) {
                    // ignore
                }
            }
            logger.info("New Role: " + entry.getKey() + ":" + newrole);
            config.roles.put(entry.getKey(), newrole);
        }
    }
    map.clear();
    map = null;
    return true;
}

From source file:mondrian.olap.Util.java

public static <T> Set<T> newIdentityHashSetFake() {
    final HashMap<T, Boolean> map = new HashMap<T, Boolean>();
    return new Set<T>() {
        public int size() {
            return map.size();
        }/*from w  ww .  j av  a2s.  c o m*/

        public boolean isEmpty() {
            return map.isEmpty();
        }

        public boolean contains(Object o) {
            return map.containsKey(o);
        }

        public Iterator<T> iterator() {
            return map.keySet().iterator();
        }

        public Object[] toArray() {
            return map.keySet().toArray();
        }

        public <T> T[] toArray(T[] a) {
            return map.keySet().toArray(a);
        }

        public boolean add(T t) {
            return map.put(t, Boolean.TRUE) == null;
        }

        public boolean remove(Object o) {
            return map.remove(o) == Boolean.TRUE;
        }

        public boolean containsAll(Collection<?> c) {
            return map.keySet().containsAll(c);
        }

        public boolean addAll(Collection<? extends T> c) {
            throw new UnsupportedOperationException();
        }

        public boolean retainAll(Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        public boolean removeAll(Collection<?> c) {
            throw new UnsupportedOperationException();
        }

        public void clear() {
            map.clear();
        }
    };
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.TestRM.java

@Test(timeout = 40000)
public void testNMToken() throws Exception {
    MockRM rm = new MockRM(conf);
    try {/*from   w w w.  j a  va  2 s. c  om*/
        Assume.assumeFalse(rm.getResourceScheduler() instanceof FairScheduler);
        rm.start();
        MockNM nm1 = rm.registerNode("h1:1234", 10000);

        NMTokenSecretManagerInRM nmTokenSecretManager = rm.getRMContext().getNMTokenSecretManager();

        // submitting new application
        RMApp app = rm.submitApp(1000);

        // start scheduling.
        nm1.nodeHeartbeat(true);

        // Starting application attempt and launching
        // It should get registered with NMTokenSecretManager.
        RMAppAttempt attempt = app.getCurrentAppAttempt();

        MockAM am = rm.sendAMLaunched(attempt.getAppAttemptId());

        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId()));

        // This will register application master.
        am.registerAppAttempt();

        ArrayList<Container> containersReceivedForNM1 = new ArrayList<Container>();
        List<ContainerId> releaseContainerList = new ArrayList<ContainerId>();
        HashMap<String, Token> nmTokens = new HashMap<String, Token>();

        // initially requesting 2 containers.
        AllocateResponse response = am.allocate("h1", 1000, 2, releaseContainerList);
        Assert.assertEquals(0, response.getAllocatedContainers().size());
        allocateContainersAndValidateNMTokens(am, containersReceivedForNM1, 2, nmTokens, nm1);
        Assert.assertEquals(1, nmTokens.size());

        // requesting 2 more containers.
        response = am.allocate("h1", 1000, 2, releaseContainerList);
        Assert.assertEquals(0, response.getAllocatedContainers().size());
        allocateContainersAndValidateNMTokens(am, containersReceivedForNM1, 4, nmTokens, nm1);
        Assert.assertEquals(1, nmTokens.size());

        // We will be simulating NM restart so restarting newly added h2:1234
        // NM 2 now registers.
        MockNM nm2 = rm.registerNode("h2:1234", 10000);
        nm2.nodeHeartbeat(true);
        ArrayList<Container> containersReceivedForNM2 = new ArrayList<Container>();

        response = am.allocate("h2", 1000, 2, releaseContainerList);
        Assert.assertEquals(0, response.getAllocatedContainers().size());
        allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 2, nmTokens, nm2);
        Assert.assertEquals(2, nmTokens.size());

        // Simulating NM-2 restart.
        nm2 = rm.registerNode("h2:1234", 10000);
        // Wait for reconnect to make it through the RM and create a new RMNode
        Map<NodeId, RMNode> nodes = rm.getRMContext().getRMNodes();
        while (nodes.get(nm2.getNodeId()).getLastNodeHeartBeatResponse().getResponseId() > 0) {
            Thread.sleep(WAIT_SLEEP_MS);
        }

        int interval = 40;
        // Wait for nm Token to be cleared.
        while (nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(),
                nm2.getNodeId()) && interval-- > 0) {
            LOG.info("waiting for nmToken to be cleared for : " + nm2.getNodeId());
            Thread.sleep(WAIT_SLEEP_MS);
        }
        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId()));

        // removing NMToken for h2:1234
        nmTokens.remove(nm2.getNodeId().toString());
        Assert.assertEquals(1, nmTokens.size());

        // We should again receive the NMToken.
        response = am.allocate("h2", 1000, 2, releaseContainerList);
        Assert.assertEquals(0, response.getAllocatedContainers().size());
        allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 4, nmTokens, nm2);
        Assert.assertEquals(2, nmTokens.size());

        // Now rolling over NMToken masterKey. it should resend the NMToken in
        // next allocate call.
        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(),
                nm1.getNodeId()));
        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(),
                nm2.getNodeId()));

        nmTokenSecretManager.rollMasterKey();
        nmTokenSecretManager.activateNextMasterKey();

        Assert.assertFalse(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(),
                nm1.getNodeId()));
        Assert.assertFalse(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(),
                nm2.getNodeId()));
        // It should not remove application attempt entry.
        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId()));

        nmTokens.clear();
        Assert.assertEquals(0, nmTokens.size());
        // We should again receive the NMToken.
        response = am.allocate("h2", 1000, 1, releaseContainerList);
        Assert.assertEquals(0, response.getAllocatedContainers().size());
        allocateContainersAndValidateNMTokens(am, containersReceivedForNM2, 5, nmTokens, nm2);
        Assert.assertEquals(1, nmTokens.size());
        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptNMTokenPresent(attempt.getAppAttemptId(),
                nm2.getNodeId()));

        // After AM is finished making sure that nmtoken entry for app
        Assert.assertTrue(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId()));
        am.unregisterAppAttempt();
        // marking all the containers as finished.
        for (Container container : containersReceivedForNM1) {
            nm1.nodeHeartbeat(attempt.getAppAttemptId(), container.getId().getContainerId(),
                    ContainerState.COMPLETE);
        }
        for (Container container : containersReceivedForNM2) {
            nm2.nodeHeartbeat(attempt.getAppAttemptId(), container.getId().getContainerId(),
                    ContainerState.COMPLETE);
        }
        nm1.nodeHeartbeat(am.getApplicationAttemptId(), 1, ContainerState.COMPLETE);
        am.waitForState(RMAppAttemptState.FINISHED);
        Assert.assertFalse(nmTokenSecretManager.isApplicationAttemptRegistered(attempt.getAppAttemptId()));
    } finally {
        rm.stop();
    }
}

From source file:com.krawler.spring.hrms.common.hrmsCommonController.java

public ModelAndView getPromotedEmp(HttpServletRequest request, HttpServletResponse response) {
    JSONObject jobj = new JSONObject();
    JSONObject jobj1 = new JSONObject();
    KwlReturnObject result = null;//from w  ww.  j  ava 2s. co  m
    int count = 0;
    List list = null;
    Iterator itr;
    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    try {
        String cmpid = sessionHandlerImplObj.getCompanyid(request);

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        requestParams.put("ss", StringUtil.checkForNull(request.getParameter("ss")));
        requestParams.put("searchcol", new String[] { "userid.firstName", "userid.lastName" });
        requestParams.put("filter_names",
                Arrays.asList("userid.company.companyID", ">=updatedon", "<=updatedon"));
        requestParams.put("filter_values",
                Arrays.asList(cmpid, new Date(df.format(new Date(request.getParameter("stdate")))),
                        new Date(df.format(new Date(request.getParameter("enddate"))))));
        requestParams.put("allflag", false);
        StringUtil.checkpaging(requestParams, request);
        result = hrmsCommonDAOObj.getEmpHistory(requestParams);
        count = result.getRecordTotalCount();
        list = result.getEntityList();
        itr = list.iterator();
        JSONArray jArr = new JSONArray();
        while (itr.hasNext()) {
            JSONObject obj = new JSONObject();
            Emphistory ehst = (Emphistory) itr.next();
            User user = ehst.getUserid();
            Useraccount ua = (Useraccount) kwlCommonTablesDAOObj
                    .getObject("com.krawler.common.admin.Useraccount", user.getUserID());
            obj.put("olddesignation", (ehst.getDesignation() != null ? ehst.getDesignation().getValue() : ""));
            obj.put("olddepartmentname", (ehst.getDepartment() != null ? ehst.getDepartment().getValue() : ""));
            obj.put("updatedate",
                    ehst.getUpdatedon() != null
                            ? sessionHandlerImplObj.getDateFormatter(request).format(ehst.getUpdatedon())
                            : "");
            requestParams.clear();
            requestParams.put("companyid", cmpid);
            requestParams.put("empid", ua.getEmployeeid());
            if (ua.getEmployeeIdFormat() == null) {
                obj.put("employeeid", ua.getEmployeeid() == null ? ""
                        : profileHandlerDAOObj.getEmpidFormatEdit(requestParams).getEntityList().get(0));
            } else {
                requestParams.put("standardEmpId", profileHandlerDAOObj.getEmpidFormatEdit(requestParams)
                        .getEntityList().get(0).toString());
                requestParams.put("employeeIdFormat", ua.getEmployeeIdFormat());
                obj.put("employeeid", profileHandlerDAOObj.getNewEmployeeIdFormat(requestParams));
            }
            obj.put("username", (user.getUserLogin() == null) ? "" : user.getUserLogin().getUserName());
            obj.put("fullname",
                    user.getFirstName() + " " + (user.getLastName() == null ? "" : user.getLastName()));
            obj.put("newdesignation", (ua.getDesignationid() == null) ? "" : ua.getDesignationid().getValue());
            obj.put("newdepartmentname", (ua.getDepartment() == null) ? "" : ua.getDepartment().getValue());
            jArr.put(obj);
        }

        jobj.put("count", count);
        jobj.put("data", jArr);
        jobj1.put("data", jobj);
        jobj1.put("valid", true);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return new ModelAndView(successView, "model", jobj1.toString());
}

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java

public ModelAndView deleteJobapplicant(HttpServletRequest request, HttpServletResponse response)
        throws ServiceException, HibernateException, SessionExpiredException {
    JSONObject jobj = new JSONObject();
    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);

    try {/*from w  w w .java  2 s.c  om*/
        String[] ids = request.getParameterValues("ids");
        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        for (int i = 0; i < ids.length; i++) {
            requestParams.clear();
            requestParams.put("id", ids[i]);
            hrmsRecJobDAOObj.deleteConfigJobapplicant(requestParams);
        }
        jobj.put("data", "");
        jobj.put("valid", true);
        txnManager.commit(status);
    } catch (HibernateException e) {
        txnManager.rollback(status);
        throw ServiceException.FAILURE("hrmsHandler.deleteApplicants", e);
    } finally {
        return new ModelAndView("jsonView", "model", jobj.toString());
    }
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.service.BugzillaXmlRpcClient.java

public void getTaskData(Set<String> taskIds, final TaskDataCollector collector,
        final TaskAttributeMapper mapper, final IProgressMonitor monitor) throws IOException, CoreException {
    HashMap<String, TaskData> taskDataMap = new HashMap<String, TaskData>();

    taskIds = new HashSet<String>(taskIds);
    while (taskIds.size() > 0) {

        Set<String> idsToRetrieve = new HashSet<String>();
        Iterator<String> itr = taskIds.iterator();
        for (int x = 0; itr.hasNext() && x < BugzillaClient.MAX_RETRIEVED_PER_QUERY; x++) {
            String taskId = itr.next();
            String taskIdOrg = taskId;
            // remove leading zeros
            boolean changed = false;
            while (taskId.startsWith("0")) { //$NON-NLS-1$
                taskId = taskId.substring(1);
                changed = true;/* ww  w.  j a v  a  2 s  .co  m*/
            }
            idsToRetrieve.add(taskId);
            if (changed) {
                taskIds.remove(taskIdOrg);
                taskIds.add(taskId);
            }
        }
        Integer[] formData = new Integer[idsToRetrieve.size()];

        if (idsToRetrieve.size() == 0) {
            return;
        }

        RepositoryConfiguration repositoryConfiguration = bugzillaClient.getRepositoryConfiguration();
        if (repositoryConfiguration == null) {
            repositoryConfiguration = bugzillaClient
                    .getRepositoryConfiguration(new SubProgressMonitor(monitor, 1), null);
        }
        List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>();
        if (repositoryConfiguration != null) {
            customFields = repositoryConfiguration.getCustomFields();
        }
        itr = idsToRetrieve.iterator();
        int x = 0;
        for (; itr.hasNext(); x++) {
            String taskId = itr.next();
            formData[x] = new Integer(taskId);

            TaskData taskData = new TaskData(mapper, getConnectorKind(), getLocation().getUrl(), taskId);
            bugzillaClient.setupExistingBugAttributes(getLocation().getUrl(), taskData);
            taskDataMap.put(taskId, taskData);
        }
        try {
            if (getUserID() == -1) {
                login(monitor);
            }
            Object[] result = getBugs(monitor, formData);
            HashMap<String, Object[]> resultAttachments = getAttachmentsInternal(monitor, formData);
            HashMap<String, HashMap<String, Object[]>> resultComments = getCommentsInternal(monitor, formData);
            for (Object resultMap : result) {
                if (resultMap instanceof Map<?, ?>) {
                    Map<?, ?> taskDataResultMap = (Map<?, ?>) resultMap;
                    Integer id = (Integer) taskDataResultMap.get("id"); //$NON-NLS-1$
                    TaskData taskData = taskDataMap.get(id.toString());
                    HashMap<String, Object[]> comments = resultComments.get(id.toString());
                    Object[] attachments = resultAttachments.get(id.toString());
                    updateTaskDataFromMap(mapper, customFields, taskDataResultMap, taskData);
                    addCommentsFromHashToTaskData(mapper, taskData, comments);
                    addAttachmentsFromHashToTaskData(mapper, taskData, attachments);
                    updateCustomFields(taskData);
                    updateAttachmentMetaData(taskData);
                    collector.accept(taskData);
                }
            }

            taskIds.removeAll(idsToRetrieve);
            taskDataMap.clear();
        } catch (XmlRpcException e) {
            throw new CoreException(
                    new Status(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN, "XmlRpcException: ", e)); //$NON-NLS-1$
        }
    }
}

From source file:com.krawler.spring.hrms.common.hrmsCommonController.java

public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response) {
    JSONObject jobj = new JSONObject();
    Integer codeid2 = null;//from  w ww . j av a2 s.co  m
    KwlReturnObject result = null;
    String msg = "";
    int roleflag = 0;
    String employeeIdFormat = "";
    boolean isStadardEmpFormatWithIdAvilable = false;

    //Create transaction
    DefaultTransactionDefinition def = new DefaultTransactionDefinition();
    def.setName("JE_Tx");
    def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
    def.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
    TransactionStatus status = txnManager.getTransaction(def);

    try {

        HashMap<String, Object> requestParams = new HashMap<String, Object>();
        ArrayList filter_names = new ArrayList(), filter_values = new ArrayList();

        HashMap newhm = new FileUploadHandler().getItems(request);
        HashMap<String, String> hm = new HashMap<String, String>();
        for (Object key : newhm.keySet()) {
            hm.put(key.toString(),
                    new String(newhm.get(key.toString()).toString().getBytes("iso-8859-1"), "UTF-8"));
        }
        String id = (String) hm.get("userid");
        //String lastname = (String) hm.get("lastname");
        //lastname = new String (lastname.getBytes ("iso-8859-1"), "UTF-8");

        if (!StringUtil.isNullOrEmpty((String) hm.get("employeeid"))) {
            String[] codeid = ((String) hm.get("employeeid")).split("-");

            for (int x = 0; x < codeid.length; x++) {
                if (codeid[x].matches("[0-9]*") == true) {
                    codeid2 = Integer.parseInt(codeid[x]);
                } else {
                    employeeIdFormat += (codeid[x] + "-");
                }
            }
            if (employeeIdFormat.length() > 0) {
                employeeIdFormat = employeeIdFormat.substring(0, employeeIdFormat.length() - 1);
            }
        }
        if (StringUtil.isNullOrEmpty(employeeIdFormat))
            employeeIdFormat = null;
        String companyid = sessionHandlerImplObj.getCompanyid(request);
        String pwd = null;

        if (!StringUtil.isNullOrEmpty(id)) {
            requestParams.clear();

            //                filter_names.add("employeeid");
            //                filter_values.add(codeid2);
            //
            //                filter_names.add("userID");
            //                filter_values.add(id);
            //
            //                filter_names.add("company.companyID");
            //                filter_values.add(companyid);
            //
            //                requestParams.put("filter_names", filter_names);
            //                requestParams.put("filter_values", filter_values);
            //
            //                result = hrmsCommonDAOObj.getUsers(requestParams);
            //                if (result.getEntityList().isEmpty()) {
            requestParams.put("employeeIdFormat", employeeIdFormat);
            requestParams.put("userID", id);
            requestParams.put("employeeid", codeid2);
            requestParams.put("request", request);
            isStadardEmpFormatWithIdAvilable = isStadardEmpFormatWithIdAvilable(requestParams);
            String standardEmpId = getStadardEmpFormat(requestParams);
            if (standardEmpId != null && employeeIdFormat != null && standardEmpId.equals(employeeIdFormat)) {
                employeeIdFormat = null;
            }
            requestParams.clear();
            filter_names.clear();
            filter_values.clear();

            filter_names.add("employeeid");
            filter_values.add(codeid2);

            if (employeeIdFormat == null) {
                filter_names.add("IS employeeIdFormat");
            } else {
                filter_names.add("employeeIdFormat");
                filter_values.add(employeeIdFormat);
            }
            filter_names.add("!userID");
            filter_values.add(id);

            filter_names.add("user.company.companyID");
            filter_values.add(companyid);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getUseraccount(requestParams);

            if (!result.getEntityList().isEmpty() || isStadardEmpFormatWithIdAvilable) {
                throw new Exception("Employee ID already present.");
            }
            //                }
            requestParams.clear();
            requestParams.put("id", id);
            if (((String) hm.get("formname")).equals("user")) {
                if (!StringUtil.isNullOrEmpty((String) hm.get("templateid"))) {
                    requestParams.put("templateid", (String) hm.get("templateid"));
                } else {
                    requestParams.put("templateid", " ");
                }
            }
        } else {
            requestParams.clear();
            filter_names.clear();
            filter_values.clear();

            filter_names.add("userLogin.userName");
            filter_values.add(hm.get("username"));

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getUsers(requestParams);
            if (!result.getEntityList().isEmpty()) {
                throw new Exception("User name not available.");
            }
            requestParams.clear();
            filter_names.clear();
            filter_values.clear();

            filter_names.add("employeeid");
            filter_values.add(codeid2);

            filter_names.add("company.companyID");
            filter_values.add(companyid);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", filter_values);

            result = hrmsCommonDAOObj.getUsers(requestParams);

            if (!result.getEntityList().isEmpty()) {
                throw new Exception("Employee ID already present.");
            }

            requestParams.clear();
            requestParams.put("username", hm.get("username"));
            pwd = AuthHandler.generateNewPassword();
            requestParams.put("pwd", AuthHandler.getSHA1(pwd));
            requestParams.put("companyid", companyid);
        }

        requestParams.put("fname", hm.get("firstname"));
        requestParams.put("lname", hm.get("lastname"));
        requestParams.put("emailid", hm.get("emailid"));
        requestParams.put("address", hm.get("address"));
        requestParams.put("contactno", hm.get("contactnumber"));
        requestParams.put("empid", codeid2);
        requestParams.put("employeeIdFormat", employeeIdFormat);
        requestParams.put("companyid", companyid);

        int histsave = 0;
        String histdept = "";
        String histdesig = "";
        String histsal = "";
        Date saveDate = new Date();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd");
        saveDate = new Date(fmt.format(saveDate));
        String updatedby = sessionHandlerImplObj.getUserid(request);
        Useraccount ua = (Useraccount) kwlCommonTablesDAOObj.getObject("com.krawler.common.admin.Useraccount",
                id);

        if (!StringUtil.isNullOrEmpty((String) hm.get("roleid"))
                && !hm.get("roleid").equals(ua.getRole().getID())) {
            if (ua.getRole().getID().equals("1") && hrmsCommonDAOObj.isCompanySuperAdmin(id, companyid)) {//Can't Edit role for super admin
                roleflag = 1;
            } else {

                String newRoleId = hm.get("roleid").toString();
                if (StringUtil.equal(newRoleId, Role.COMPANY_USER)) { // Check whether new Role is Company User/ Company Employee

                    List<Empprofile> childList = organizationChartDAOObj.getChildNode(id); // Check for child list before changing its role to Employee.

                    if (childList.size() > 0) {
                        roleflag = 2;
                    } else {
                        requestParams.put("roleid", newRoleId);
                    }
                } else {

                    requestParams.put("roleid", newRoleId);
                }

            }
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("designationid"))) {
            if ((MasterData) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.master.MasterData",
                    (String) hm.get("designationid")) != ua.getDesignationid()) {
                histdesig = (ua.getDesignationid() == null) ? "" : ua.getDesignationid().getId();
                histsave = 1;
            }
            requestParams.put("designationid", hm.get("designationid"));
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("department"))) {
            if ((MasterData) kwlCommonTablesDAOObj.getObject("com.krawler.hrms.master.MasterData",
                    (String) hm.get("department")) != ua.getDepartment()) {
                histdept = (ua.getDepartment() == null) ? "" : ua.getDepartment().getId();
                if (histsave == 0) {
                    histdesig = (ua.getDesignationid() == null) ? "" : ua.getDesignationid().getId();
                }
                histsave = 2;
            }
            requestParams.put("department", hm.get("department"));
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("salary"))) {
            String tempsal = "0";
            if (((String) hm.get("salary")).length() > 0) {
                tempsal = hm.get("salary").toString();
            }
            if (!tempsal.equals(ua.getSalary())) {
                if (ua.getSalary() != null) {
                    histsal = ua.getSalary();
                }
            }
            requestParams.put("salary", tempsal);
        }

        if (!StringUtil.isNullOrEmpty((String) hm.get("accno"))) {
            if (((String) hm.get("accno")).length() > 0) {
                requestParams.put("accno", hm.get("accno"));
            } else {
                requestParams.put("accno", "0");
            }
        }

        if (!StringUtil.isNullOrEmpty((String) hm.get("formatid"))) {
            requestParams.put("formatid", hm.get("formatid"));
        }
        String diff = null;
        if (!StringUtil.isNullOrEmpty((String) hm.get("tzid"))) {
            KWLTimeZone timeZone = (KWLTimeZone) kwlCommonTablesDAOObj
                    .getObject("com.krawler.common.admin.KWLTimeZone", (String) hm.get("tzid"));
            diff = timeZone.getDifference();
            requestParams.put("tzid", hm.get("tzid"));
        }
        if (!StringUtil.isNullOrEmpty((String) hm.get("aboutuser"))) {
            requestParams.put("aboutuser", hm.get("aboutuser"));
        }
        String imageName = "";
        if (newhm.get("userimage") != null) {
            imageName = ((FileItem) (newhm.get("userimage"))).getName();
            if (!StringUtil.isNullOrEmpty(imageName)) {
                requestParams.put("userimage", hm.get("userimage"));
            }
        }

        result = hrmsCommonDAOObj.saveUser(requestParams, RequestContextUtils.getLocale(request));
        if (!StringUtil.isNullOrEmpty(imageName)) {
            User user = (User) result.getEntityList().get(0);
            String fileName = user.getImage().substring(user.getImage().lastIndexOf("/") + 1,
                    user.getImage().length());
            new FileUploadHandler().uploadImage((FileItem) (newhm.get("userimage")), fileName,
                    StorageHandler.GetProfileImgStorePath(), 100, 100, false, false);
        }
        msg = result.getMsg();
        requestParams.clear();
        if (histsave == 1) {
            histdept = ua.getDepartment().getId();
        }
        if (histsave == 1 || histsave == 2) {
            String latestUpdate = "";
            HashMap<String, Object> requestParams2 = new HashMap<String, Object>();
            requestParams2.put("id", id);
            requestParams2.put("cat", Emphistory.Emp_Desg_change);
            result = hrmsCommonDAOObj.getLastUpdatedHistory(requestParams2);
            latestUpdate = result.getEntityList().get(0).toString();
            if (!latestUpdate.equals("")) {
                latestUpdate = latestUpdate.replace("-", "/");
                requestParams.put("Joindate", fmt.parse(latestUpdate));
            }
            requestParams.put("Department", histdept);
            requestParams.put("Designation", histdesig);
            requestParams.put("Userid", id);
            requestParams.put("Empid", ua.getEmployeeid());
            requestParams.put("Updatedon", saveDate);
            requestParams.put("Updatedby", updatedby);
            requestParams.put("Category", Emphistory.Emp_Desg_change);
            result = hrmsCommonDAOObj.addEmphistory(requestParams);
        }
        if (!histsal.equals("")) {
            requestParams.clear();
            requestParams.put("Userid", id);
            requestParams.put("Salary", histsal);
            requestParams.put("Updatedon", saveDate);
            requestParams.put("Updatedby", updatedby);
            requestParams.put("Category", Emphistory.Emp_Salary);
            result = hrmsCommonDAOObj.addEmphistory(requestParams);
        }

        sessionHandlerImplObj.updatePreferences(request, null,
                (StringUtil.isNullOrEmpty((String) hm.get("formatid")) ? null : (String) hm.get("formatid")),
                (StringUtil.isNullOrEmpty((String) hm.get("tzid")) ? null : (String) hm.get("tzid")), diff);
        if (roleflag == 1) {
            msg = msg + " "
                    + messageSource.getMessage("hrms.common.Rolecannotbechangedforsuperadministrator", null,
                            "Role cannot be changed for Super Administrator.",
                            RequestContextUtils.getLocale(request));
            jobj.put("roleflag", roleflag);
        }
        if (roleflag == 2) {
            msg = msg + " <br><br><br>" + messageSource.getMessage(
                    "hrms.common.rolecannotbechangedtocompanyemployee", null,
                    "Note : Role cannot be changed to Company Employee. Please re-assign or remove its child node in Organization Chart before changing its role to Company Employee.",
                    RequestContextUtils.getLocale(request));
            jobj.put("roleflag", roleflag);
        }
        jobj.put("msg", msg);
        jobj.put("success", true);
        txnManager.commit(status);
    } catch (Exception e) {
        try {
            if (e.getMessage().equals("Employee ID already present.")) {
                jobj.put("msg", e.getMessage());
            }
        } catch (Exception ex) {
            e.printStackTrace();
        }
        e.printStackTrace();
        txnManager.rollback(status);
    }
    return new ModelAndView("jsonView", "model", jobj.toString());
}