Example usage for java.util HashMap isEmpty

List of usage examples for java.util HashMap isEmpty

Introduction

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

Prototype

public boolean isEmpty() 

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:nl.uva.sne.disambiguators.BabelNet.java

private Set<Term> babelNetDisambiguation(String language, String lemma, Set<String> ngarms) {
    if (ngarms.isEmpty()) {
        return null;
    }//from   w ww. j a v  a 2 s. c  o m
    if (ngarms.size() == 1 && ngarms.iterator().next().length() <= 1) {
        return null;
    }

    HashMap<String, Double> idsMap = new HashMap<>();
    Map<String, Term> termMap = new HashMap<>();
    Set<Term> terms = new HashSet<>();
    int count = 0;
    int breaklimit = 1000;
    int oneElementlimit = 65;
    int difflimit = 60;
    Double persent;
    for (String n : ngarms) {
        if (n.length() <= 1) {
            continue;
        }
        count++;
        if (idsMap.size() == 1 && count > oneElementlimit) {
            //                Double score = idsMap.values().iterator().next();
            //                if (score >= 10) {
            break;
            //                }
        }

        if ((count % 2) == 0 && idsMap.size() >= 2 && count > difflimit) {
            ValueComparator bvc = new ValueComparator(idsMap);
            TreeMap<String, Double> sorted_map = new TreeMap(bvc);
            sorted_map.putAll(idsMap);
            Iterator<String> iter = sorted_map.keySet().iterator();
            Double first = idsMap.get(iter.next());
            Double second = idsMap.get(iter.next());

            persent = first / (first + second);
            if (persent > 0.65) {
                break;
            }
        }
        if (count > breaklimit) {
            break;
        }

        String clearNg = n.replaceAll("_", " ");
        if (clearNg == null) {
            continue;
        }
        if (clearNg.startsWith(" ")) {
            clearNg = clearNg.replaceFirst(" ", "");
        }
        if (clearNg.endsWith(" ")) {
            clearNg = clearNg.substring(0, clearNg.length() - 1);
        }

        Pair<Term, Double> termPair = null;
        try {
            termPair = babelNetDisambiguation(language, lemma, clearNg);
        } catch (Exception ex) {
            if (ex.getMessage() != null && ex.getMessage().contains("Your key is not valid")) {
                try {
                    termPair = babelNetDisambiguation(language, lemma, clearNg);
                } catch (Exception ex1) {
                    //                        Logger.getLogger(BabelNet.class.getName()).log(Level.WARNING, ex1, null);
                }
            } else {
                Logger.getLogger(SemanticUtils.class.getName()).log(Level.WARNING, null, ex);
            }
        }
        if (termPair != null) {
            termMap.put(termPair.first.getUID(), termPair.first);
            Double score;
            if (idsMap.containsKey(termPair.first.getUID())) {
                score = idsMap.get(termPair.first.getUID());
                //                    score++;
                score += termPair.second;
            } else {
                //                    score = 1.0;
                score = termPair.second;
            }
            idsMap.put(termPair.first.getUID(), score);
        }
    }
    if (!idsMap.isEmpty()) {
        ValueComparator bvc = new ValueComparator(idsMap);
        TreeMap<String, Double> sorted_map = new TreeMap(bvc);
        sorted_map.putAll(idsMap);
        count = 0;
        Double firstScore = idsMap.get(sorted_map.firstKey());
        terms.add(termMap.get(sorted_map.firstKey()));
        idsMap.remove(sorted_map.firstKey());
        for (String tvID : sorted_map.keySet()) {
            if (count >= 1) {
                Double secondScore = idsMap.get(tvID);
                persent = secondScore / (firstScore + secondScore);
                if (persent > 0.2) {
                    terms.add(termMap.get(tvID));
                }
                if (count >= 2) {
                    break;
                }
            }
            count++;
        }
        return terms;
    }
    return null;
}

From source file:com.MainFiles.Functions.java

public String[] getBalance(String strAccountNo, String strAgentID, String strTerminalID) throws IOException {
    String[] strBalance = null;//from  w ww.  j  av a  2  s . co  m
    try {
        String referenceNumber = this.PadZeros(12, this.generateCorelationID());
        Map<String, String> params = new HashMap<>();

        params.put("0", "0200");
        params.put("2", "0000000000000");
        params.put("3", "310000");
        params.put("4", "0");
        params.put("7", this.anyDate("MMddHHmmss"));
        params.put("11", this.anyDate("MMddHHmmss"));
        params.put("32", SOURCE_ID);
        params.put("37", referenceNumber);
        params.put("65", "");
        params.put("66", getTerminalID(strTerminalID));
        params.put("68", strTerminalID);
        params.put("88", "BALANCE ENQUIRY FOR ACCOUNT: " + strAccountNo);
        params.put("100", "BI");
        params.put("102", strAccountNo);
        params.put("103", "");
        params.put("104", strAgentID);

        boolean sentToWebLogic = false;
        HashMap ParamsFromAdapter = new HashMap();
        QueueWriter queueWriter = new QueueWriter(QUEUE_REQUEST, PROVIDER_URL);

        int trials = 0;
        do {
            sentToWebLogic = queueWriter.sendObject((HashMap) params, referenceNumber);
            trials++;
        } while (sentToWebLogic == false & trials < 3);

        if (sentToWebLogic) {

            long Start = System.currentTimeMillis();
            long Stop = Start + (Config.flexTimeOut * 1000);
            do {
                Thread.currentThread().sleep(100);
                ParamsFromAdapter = this.getWeblogicMessageFromQueue(referenceNumber);
            } while (ParamsFromAdapter.isEmpty() && System.currentTimeMillis() < Stop);

            if (ParamsFromAdapter.isEmpty()) {
                params.put("39", "999");
                params.put("48", "No response from Flex");
                this.log("No Response " + referenceNumber + ":" + params.toString(), "ERROR");

            } else {
                strBalance = ParamsFromAdapter.get("54").toString().split("\\|");
            }

        }
    } catch (Exception ex) {
        this.log("INFO : Function getBalance()  " + ex.getMessage() + "\n" + this.StackTraceWriter(ex),
                "ERROR");
    }
    return strBalance;
}

From source file:org.aselect.server.request.handler.aselect.authentication.ApplicationBrowserHandler.java

/**
 * This method handles the <code>request=cross_login</code> user request. <br>
 * <br>/*ww w .ja va 2 s .c om*/
 * <b>Description:</b> <br>
 * If the user already has a tgt and it is valid for the current application, then the user does not need be
 * authenticated again. The user is redirected back to the application. If the user's tgt is not valid, then the
 * remote A-Select Server is contacted by sending a <code>request=cross_authenticate_aselect</code> request. If the
 * remote A-Select Server is contacted successfully, the user is redirected to him so that the user can be
 * authenticated there. <br>
 * <br>
 * <b>Concurrency issues:</b> <br>
 * - <br>
 * <br>
 * <b>Preconditions:</b> <br>
 * - <br>
 * <br>
 * <b>Postconditions:</b> <br>
 * - <br>
 * 
 * @param htServiceRequest
 *            HashMap containing request parameters
 * @param servletResponse
 *            Used to send (HTTP) information back to user
 * @param pwOut
 *            PrintWriter that might be needed by the <code>ISelectorHandler</code>
 * @throws ASelectException
 *             the a select exception
 */
private void handleCrossLogin(HashMap htServiceRequest, HttpServletResponse servletResponse, PrintWriter pwOut)
        throws ASelectException {
    String sRemoteOrg = null;
    String sUid = null;
    String sMethod = "handleCrossLogin";

    _systemLogger.log(Level.INFO, _sModule, sMethod, "CrossLogin htServiceRequest=" + htServiceRequest);
    try {
        // is cross enabled? (configuration)
        if (!_crossASelectManager.remoteServersEnabled()) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod,
                    "Cross A-Select is disabled since it is not (properly) configured.");
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_UNKNOWN_ORG);
        }

        // Is equal to the sRid value we already have in the caller
        String sRid = (String) htServiceRequest.get("rid");
        Integer intAppLevel = (Integer) _htSessionContext.get("level");
        if (intAppLevel == null) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod, "could not fetch level from session context.");
            throw new ASelectException(Errors.ERROR_ASELECT_SERVER_INVALID_SESSION);
        }
        sRemoteOrg = (String) _htSessionContext.get("forced_organization");

        // check if the request was done for a specific user_id
        sUid = (String) _htSessionContext.get("forced_uid");
        _systemLogger.log(Level.INFO, _sModule, sMethod, "XLOGIN sRid=" + sRid + ", intAppLevel=" + intAppLevel
                + ", sRemoteOrg=" + sRemoteOrg + ", forced_uid=" + sUid);

        if (sRemoteOrg == null) {
            if (!_crossASelectManager.isCrossSelectorEnabled()) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod,
                        "Dynamic 'cross_selector' is disabled, parameter 'remote_organization' is required but not found.");
                throw new ASelectException(Errors.ERROR_ASELECT_SERVER_UNKNOWN_ORG);
            }

            // No optional parameter 'remote_organization found, determine the remote organization
            // some selector handlers may need the user_id if it is known already
            HashMap htIdentification = null;
            if (sUid != null) {
                htServiceRequest.put("user_id", sUid); // NOTE: in the Service Request, not the Session
            }
            try {
                htIdentification = _crossASelectManager.getSelectorHandler().getRemoteServerId(htServiceRequest,
                        servletResponse, pwOut);
            } catch (ASelectException ace) {
                _systemLogger.log(Level.WARNING, _sModule, sMethod, "Failed to retrieve the remote server id.");
                throw new ASelectCommunicationException(Errors.ERROR_ASELECT_SERVER_UNKNOWN_ORG, ace);
            }
            if (htIdentification == null) {
                _systemLogger.log(Level.INFO, _sModule, sMethod, "XLOGIN !htIdentification");
                // The handler was not ready yet and presented a HTML form to the end user 
                // to gather more information. This form will POST 'request=cross_authenticate' again.
                return;
            }
            sRemoteOrg = (String) htIdentification.get("organization_id");
            String sTemp = (String) htIdentification.get("user_id");
            _systemLogger.log(Level.INFO, _sModule, sMethod, "XLOGIN htIdentification=" + htIdentification);

            // Selector handler might have translated the user_id
            if (sTemp != null)
                sUid = (String) htIdentification.get("user_id");
        }
        //_htSessionContext.put("remote_organization", sRemoteOrg);
        // 20120403, Bauke: no longer needed this method does not change the session
        //_sessionManager.setUpdateSession(_htSessionContext, _systemLogger);  // 20120401, Bauke: postpone session action

        // storage_manager_fix_for_lost_fields
        // 20120403, Bauke: no longer needed this method does not change the session
        //if (!_sessionManager.update Session(sRid, _htSessionContext)) {
        //   _systemLogger.log(Level.WARNING, _sModule, sMethod, "could not update session context");
        //   throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
        //}

        Object oRemoteServer;
        String sRemoteAsUrl;
        String sRemoteServer;
        try {
            // continue cross a-select login processing
            String sResourcegroup = _crossASelectManager.getRemoteParam(sRemoteOrg, "resourcegroup");
            if (sResourcegroup == null) {
                StringBuffer sbWarning = new StringBuffer("Unknown organization '");
                sbWarning.append(sRemoteOrg);
                sbWarning.append("'");
                _systemLogger.log(Level.SEVERE, _sModule, sMethod, sbWarning.toString());
                throw new ASelectException(Errors.ERROR_ASELECT_SERVER_UNKNOWN_ORG);
            }
            SAMResource oSAMResource = ASelectSAMAgent.getHandle().getActiveResource(sResourcegroup);
            oRemoteServer = oSAMResource.getAttributes();
            sRemoteAsUrl = _configManager.getParam(oRemoteServer, "url");
            sRemoteServer = _crossASelectManager.getRemoteParam(sRemoteOrg, "server");
        } catch (ASelectSAMException ase) {
            _systemLogger.log(Level.SEVERE, _sModule, sMethod, "Failed to read SAM.");
            throw ase;
        } catch (ASelectConfigException ace) {
            _systemLogger.log(Level.SEVERE, _sModule, sMethod, "Failed to read config.");
            throw ace;
        }

        StringBuffer sbMyAppUrl = new StringBuffer();
        sbMyAppUrl.append((String) htServiceRequest.get("my_url"));
        sbMyAppUrl.append("?local_rid=").append(sRid);

        RawCommunicator oCommunicator = new RawCommunicator(_systemLogger); // Default = API communciation

        HashMap htRequestTable = new HashMap();
        htRequestTable.put("request", "authenticate");

        Boolean boolForced = (Boolean) _htSessionContext.get("forced_authenticate"); // a Boolean
        if (boolForced == null)
            boolForced = false;
        htRequestTable.put("forced_authenticate", boolForced); // boolean
        htRequestTable.put("forced_logon", boolForced.toString()); // and this is a String!
        htRequestTable.put("local_as_url", sbMyAppUrl.toString());

        Object oASelectConfig = _configManager.getSection(null, "aselect");
        String sMyOrgId = _configManager.getParam(oASelectConfig, "organization");
        htRequestTable.put("local_organization", sMyOrgId);

        Integer intLevel = (Integer) _htSessionContext.get("level");
        htRequestTable.put("required_level", intLevel.toString());
        htRequestTable.put("level", intLevel); // 20090111, Bauke added
        htRequestTable.put("a-select-server", sRemoteServer);

        if (sUid != null) {
            htRequestTable.put("uid", sUid);
        }
        String sCountry = (String) _htSessionContext.get("country");
        if (sCountry != null) {
            htRequestTable.put("country", sCountry);
        }
        String sLanguage = (String) _htSessionContext.get("language");
        if (sLanguage != null) {
            htRequestTable.put("language", sLanguage);
        }

        // check if request should be signed
        if (_crossASelectManager.useRemoteSigning()) {
            _cryptoEngine.signRequest(htRequestTable);
        }
        _systemLogger.log(Level.INFO, _sModule, sMethod, "XLOGIN htRequestTable=" + htRequestTable);

        HashMap htResponseTable = oCommunicator.sendMessage(htRequestTable, sRemoteAsUrl);
        if (htResponseTable.isEmpty()) {
            _systemLogger.log(Level.WARNING, _sModule, sMethod,
                    "Could not reach remote A-Select Server: " + sRemoteAsUrl);
            throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
        }
        _systemLogger.log(Level.INFO, _sModule, sMethod, "XLOGIN htResponseTable=" + htResponseTable);

        String sResultCode = (String) htResponseTable.get("result_code");
        if (sResultCode == null) {
            StringBuffer sbWarning = new StringBuffer("Invalid response from remote A-Select Server '");
            sbWarning.append(sRemoteServer);
            sbWarning.append("' (missing: 'result_code')");
            _systemLogger.log(Level.WARNING, _sModule, sMethod, sbWarning.toString());
            throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
        }
        if (!sResultCode.equals(Errors.ERROR_ASELECT_SUCCESS)) {
            StringBuffer sbWarning = new StringBuffer("A-Select Server '");
            sbWarning.append(sRemoteServer);
            sbWarning.append("' returned error: '");
            sbWarning.append(sResultCode);
            sbWarning.append("'.");
            _systemLogger.log(Level.WARNING, _sModule, sMethod, sbWarning.toString());
            throw new ASelectException(sResultCode);
        }

        // check the response of the A-Select Server
        String sRemoteRid = (String) htResponseTable.get("rid");
        String sRemoteLoginUrl = (String) htResponseTable.get("as_url");
        if ((sRemoteRid == null) || (sRemoteLoginUrl == null)) {
            StringBuffer sbWarning = new StringBuffer("Invalid response from remote A-Select Server: ");
            sbWarning.append(sRemoteServer);
            _systemLogger.log(Level.WARNING, _sModule, sMethod, sbWarning.toString());
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_INTERNAL_ERROR);
        }

        try {
            StringBuffer sbUrl = new StringBuffer(sRemoteLoginUrl);
            sbUrl.append("&rid=").append(sRemoteRid);
            sbUrl.append("&a-select-server=").append(sRemoteServer);
            _systemLogger.log(Level.INFO, _sModule, sMethod, "REDIR " + sbUrl);
            servletResponse.sendRedirect(sbUrl.toString());
        } catch (IOException e) {
            StringBuffer sbWarning = new StringBuffer("Failed to redirect user to: ");
            sbWarning.append(sRemoteServer);
            _systemLogger.log(Level.WARNING, _sModule, sMethod, sbWarning.toString());
            throw new ASelectCommunicationException(Errors.ERROR_ASELECT_IO, e);
        }
    } catch (ASelectException ae) {
        throw ae;
    } catch (Exception e) {
        _systemLogger.log(Level.WARNING, _sModule, sMethod, "Internal error", e);
        throw new ASelectException(Errors.ERROR_ASELECT_INTERNAL_ERROR, e);
    }
}

From source file:sh.isaac.convert.rxnorm.standard.RxNormMojo.java

/**
 * X doc loader helper./* ww  w. j ava2s. c o m*/
 *
 * @param dockey the dockey
 * @param niceName the nice name
 * @param loadAsDefinition the load as definition
 * @param parent the parent
 * @return the hash map
 * @throws Exception the exception
 */

/*
 * Note - may return null, if there were no instances of the requested data
 */
private HashMap<String, UUID> xDocLoaderHelper(String dockey, String niceName, boolean loadAsDefinition,
        UUID parent) throws Exception {
    final HashMap<String, UUID> result = new HashMap<>();

    ConsoleUtil.println("Creating '" + niceName + "' types");
    {
        try (Statement s = this.db.getConnection().createStatement();
                ResultSet rs = s.executeQuery("SELECT VALUE, TYPE, EXPL FROM " + this.tablePrefix
                        + "DOC where DOCKEY='" + dockey + "'")) {
            while (rs.next()) {
                final String value = rs.getString("VALUE");
                final String type = rs.getString("TYPE");
                final String name = rs.getString("EXPL");

                if (value == null) {
                    // there is a null entry, don't care about it.
                    continue;
                }

                if (!type.equals("expanded_form")) {
                    throw new RuntimeException(
                            "Unexpected type in the attribute data within DOC: '" + type + "'");
                }

                final UUID created = this.importUtil.createConcept(
                        ConverterUUID.createNamespaceUUIDFromString(
                                parent + ":" + (loadAsDefinition ? value : name)),
                        (loadAsDefinition ? value : name), null, (loadAsDefinition ? null : value),
                        (loadAsDefinition ? name : null), parent, null).getPrimordialUuid();

                result.put((loadAsDefinition ? value : name), created);

                if (!loadAsDefinition) {
                    result.put(value, created);
                }
            }
        }
    }

    if (result.isEmpty()) {
        // This can happen, depending on what is included during the metamorphosys run
        ConsoleUtil.println("No entries found for '" + niceName + "' - skipping");
        return null;
    }

    return result;
}

From source file:org.epics.archiverappliance.config.DefaultConfigService.java

/**
 * Given a external Archiver data server URL and an archive; 
 * If this is a ChannelArchiver (archives != pbraw); 
 * this adds the PVs in the Channel Archiver so that they can be proxied.
 * @param serverURL//from ww w  . j a  v a  2  s . com
 * @param archive
 * @throws IOException
 * @throws SAXException
 */
private void loadExternalArchiverPVs(String serverURL, String archive) throws IOException, SAXException {
    if (archive.equals("pbraw")) {
        logger.debug(
                "We do not load PV names from external EPICS archiver appliances. These can number in the multiple millions and the respone on retrieval is fast enough anyways");
        return;
    }

    ChannelArchiverDataServerInfo serverInfo = new ChannelArchiverDataServerInfo(serverURL, archive);
    NamesHandler handler = new NamesHandler();
    logger.debug(
            "Getting list of PV's from Channel Archiver Server at " + serverURL + " using index " + archive);
    XMLRPCClient.archiverNames(serverURL, archive, handler);
    HashMap<String, List<ChannelArchiverDataServerPVInfo>> tempPVNames = new HashMap<String, List<ChannelArchiverDataServerPVInfo>>();
    long totalPVsProxied = 0;
    for (NamesHandler.ChannelDescription pvChannelDesc : handler.getChannels()) {
        String pvName = PVNames.normalizePVName(pvChannelDesc.getName());
        if (this.pv2ChannelArchiverDataServer.containsKey(pvName)) {
            List<ChannelArchiverDataServerPVInfo> alreadyExistingServers = this.pv2ChannelArchiverDataServer
                    .get(pvName);
            logger.debug("Adding new server to already existing ChannelArchiver server for " + pvName);
            addExternalCAServerToExistingList(alreadyExistingServers, serverInfo, pvChannelDesc);
            tempPVNames.put(pvName, alreadyExistingServers);
        } else if (tempPVNames.containsKey(pvName)) {
            List<ChannelArchiverDataServerPVInfo> alreadyExistingServers = tempPVNames.get(pvName);
            logger.debug("Adding new server to already existing ChannelArchiver server (in tempspace) for "
                    + pvName);
            addExternalCAServerToExistingList(alreadyExistingServers, serverInfo, pvChannelDesc);
            tempPVNames.put(pvName, alreadyExistingServers);
        } else {
            List<ChannelArchiverDataServerPVInfo> caServersForPV = new ArrayList<ChannelArchiverDataServerPVInfo>();
            caServersForPV.add(new ChannelArchiverDataServerPVInfo(serverInfo, pvChannelDesc.getStartSec(),
                    pvChannelDesc.getEndSec()));
            tempPVNames.put(pvName, caServersForPV);
        }

        if (tempPVNames.size() > 1000) {
            this.pv2ChannelArchiverDataServer.putAll(tempPVNames);
            totalPVsProxied += tempPVNames.size();
            tempPVNames.clear();
        }
    }
    if (!tempPVNames.isEmpty()) {
        this.pv2ChannelArchiverDataServer.putAll(tempPVNames);
        totalPVsProxied += tempPVNames.size();
        tempPVNames.clear();
    }
    if (logger.isDebugEnabled())
        logger.debug("Proxied a total of " + totalPVsProxied + " from server " + serverURL + " using archive "
                + archive);

}

From source file:com.MainFiles.Functions.java

public HashMap getESBResponse(String strAgentID, String cardNumber, String processingCode, String amount,
        String referenceNumber, String narration, String transactionIdentifier, String strAccountNumber,
        String creditAccount, String strField65, String Phonenumber, String strField68)
        throws InterruptedException {
    String response = "";
    String strField_02 = "";
    String strField_00 = "";
    String strFieldPRD = "";
    String strProcessingCode = "";
    String strMessageToPOS = "";
    String STAN = "" + GetSequenceNumber();

    try {//from w  w  w  .  j  a va  2 s  .c om

        if (Phonenumber.toString().trim().equals("") || Phonenumber.toString().trim() == null) {
            strField_02 = cardNumber;
        } else {
            strField_02 = "255" + Phonenumber.substring(Phonenumber.length() - 9);
        }

        switch (processingCode) {
        case "120000": // MERCHANT PAYMENTS
            strProcessingCode = "400000";
            strField_00 = "0200";
            strFieldPRD = "AGMP";
            narration = "PAYMENT OF GOODS AND SERVICES FOR " + strAccountNumber;
            break;
        case "310000":// BALANCE ENQUIRY
            strProcessingCode = processingCode;
            strField_00 = "0200";
            narration = "BALANCE ENQUIRY FOR ACCOUNT " + strAccountNumber;
            break;
        case "300000": // AGENT FLOAT (we do BI for Agent float)
            strProcessingCode = "310000";
            strField_00 = "0200";
            strFieldPRD = "FLBI";
            narration = "AGENT FLOAT FOR ACCOUNT " + strAccountNumber;
            break;
        case "380000": //MINI STATEMENT
            strProcessingCode = processingCode;
            strField_00 = "0200";
            narration = "MINI STATEMENT FOR ACCOUNT " + strAccountNumber;
            break;
        case "340000": // CARD ACTIVATION
            strProcessingCode = processingCode;
            strField_00 = "0100";
            break;
        case "010000": // CASH WITHDRAWAL
            strProcessingCode = processingCode;
            strFieldPRD = "CHWL";
            strField_00 = "0200";
            narration = "CASH WITHDRAWAL FOR ACCOUNT " + strAccountNumber;
            break;
        case "500000": // BILL PAYMENTS
            strProcessingCode = processingCode;
            strFieldPRD = "";
            strField_00 = "0200";
            break;
        case "400000": // FUNDS TRANSFER
            strProcessingCode = processingCode;
            strFieldPRD = "AGFT";
            strField_00 = "0200";
            narration = "FUNDS TRANSFER FOR ACCOUNT " + strAccountNumber;
            break;
        case "210000": // CASH DEPOSIT
            strProcessingCode = processingCode;
            strFieldPRD = "CHDP";
            strField_00 = "0200";
            break;
        case "420000": // TOPUPS
            strField_00 = "0200";
            strField65 = strField_02;
            strProcessingCode = processingCode;
            break;
        default:
            strField_00 = "0200";
            strProcessingCode = processingCode;
            break;
        }

        Map<String, String> ISOdetails = new HashMap<>();

        ISOdetails.put("0", strField_00);
        ISOdetails.put("2", strField_02);
        ISOdetails.put("3", strProcessingCode);
        ISOdetails.put("4", amount);
        ISOdetails.put("7", this.anyDate("MMddHHmmss"));
        ISOdetails.put("11", STAN);
        ISOdetails.put("32", SOURCE_ID);
        ISOdetails.put("37", referenceNumber);
        ISOdetails.put("65", strField65);
        ISOdetails.put("66", getTerminalID(strField68));
        ISOdetails.put("68", strField68);
        ISOdetails.put("88", narration);
        ISOdetails.put("100", transactionIdentifier);
        ISOdetails.put("102", strAccountNumber);
        ISOdetails.put("103", creditAccount);
        ISOdetails.put("104", strAgentID);
        ISOdetails.put("CorrelationID", referenceNumber);
        ISOdetails.put("PRD", strFieldPRD);
        ISOdetails.put("HASH", sendTransactionHash(strAgentID, strField68).toLowerCase());
        this.log("REQUEST :: " + referenceNumber + "\n" + ISOdetails.toString() + "\n\n", "ESB_Request");

        boolean sentToWebLogic = false;
        HashMap ParamsFromAdapter = new HashMap();
        QueueWriter queueWriter = new QueueWriter(QUEUE_REQUEST, PROVIDER_URL);

        int trials = 0;
        do {
            sentToWebLogic = queueWriter.sendObject((HashMap) ISOdetails, referenceNumber);
            trials++;
        } while (sentToWebLogic == false & trials < 3);

        if (sentToWebLogic) {
            long Start = System.currentTimeMillis();
            long Stop = Start + (Integer.parseInt(ISO8583Adaptor.ESB_TIMEOUT) * 1000);
            do {
                Thread.currentThread().sleep(100);
                ParamsFromAdapter = this.getWeblogicMessageFromQueue(referenceNumber);
            } while (ParamsFromAdapter.isEmpty() && System.currentTimeMillis() < Stop);

            if (ParamsFromAdapter.isEmpty()) {
                //Excempt for processing code 340000
                if (!ISOdetails.get("3").equals("340000")) {
                    //printMsg:No reponse from ESB
                    System.out.println("===================== ");
                    System.out.println("===================== ");
                    System.out.println("ESB Timeout Response at "
                            + (new SimpleDateFormat("MMMM dd,yyyy hh:mm:ss.SSS a zzzz"))
                                    .format(new java.util.Date()));
                    System.out.println("LoggedError:CorrelationID:" + referenceNumber + "");
                    System.out.println("LoggedError:StatusCode:999");
                    System.out.println("LoggedError:Status Description:Response timeout from ESB Gateway");

                    //Send Failed Response to POS
                    String TransactionType = getTransactionType(ISOdetails.get("3").toString());

                    strMessageToPOS += this.strResponseHeader(strField68) + "#";
                    strMessageToPOS += "AGENT ID:  " + ISOdetails.get("104").toString() + "#";
                    strMessageToPOS += "TRAN NUM:  " + ISOdetails.get("37").toString() + "#";
                    strMessageToPOS += "--------------------------------" + "#";
                    strMessageToPOS += "                                " + "#";
                    strMessageToPOS += padEqual(TransactionType.toUpperCase()) + "#";
                    strMessageToPOS += "                                " + "#";
                    strMessageToPOS += "   NO RESPONSE FROM ESB GATEWAY " + "#";
                    strMessageToPOS += " " + "#";
                    strMessageToPOS += this.strResponseFooter(ISOdetails.get("104").toString()) + "#";
                    SendPOSResponse(strMessageToPOS, ISOdetails.get("37").toString());
                }
            } else {

                switch (processingCode) {
                case "340000":// For Card Activation Return Array
                    return ParamsFromAdapter;
                case "300000"://AgentFloat
                    ParamsFromAdapter.remove("3");
                    ParamsFromAdapter.put("3", "300000");
                    break;
                case "120000":
                    ParamsFromAdapter.remove("3");
                    ParamsFromAdapter.put("3", "120000");
                    break;
                default:
                    break;
                }
                printScreenMessage(ParamsFromAdapter);
                response = this.genHashDelimiterString(ParamsFromAdapter, referenceNumber);
            }
        }
    } catch (Exception ex) {
        this.log("Error on getESBResponse " + ex.getMessage() + "\n" + this.StackTraceWriter(ex),
                "getESBResponse");
    }
    return null;
}

From source file:servlets.SearchServlet.java

/**
 * A function that assigns points to the result of a search based on its start time and end time, and if the result fulfills a requirement.
 * @param conn, An instance of Connection.
 * @param reqs, A HashMap containing requirements needed to be fulfilled for a degree. 
 * @param schedule, A Schedule instance containing available and unavailable time slots for each day of the week.
 * @param searcher, An instance of Search.
 * @param isTimeBased, A boolean indicating what type of search (time focused or requirement focused search) so the proper point system can be used. 
 *///from  w w  w . j  a v a  2 s. c  o  m
protected void assignPts(Connection conn, HashMap<String, List<JSONObject>> reqs, Schedule schedule,
        Search searcher, boolean isTimeBased) {

    PreparedStatement preparedStatement;
    ResultSet resultSet;
    float value = 0;
    String queryA = "select * from " + searcher.tableName();

    try {

        String days;
        preparedStatement = conn.prepareStatement(queryA);
        preparedStatement.execute();
        resultSet = preparedStatement.executeQuery();
        PreparedStatement update = conn.prepareStatement("UPDATE " + searcher.tableName() + " "
                + "SET points=? WHERE cdept=? AND cnbr=? AND sec=? AND starttime=? AND endtime=?");

        while (resultSet.next()) {
            value = 0;
            update.setString(2, resultSet.getString("cdept"));
            update.setString(3, resultSet.getString("cnbr"));
            update.setString(4, resultSet.getString("sec"));
            update.setInt(5, resultSet.getInt("starttime"));
            update.setInt(6, resultSet.getInt("endtime"));

            days = resultSet.getString("days");

            // skip if section has no times
            if (days != null) {
                for (int i = 0; i < schedule.getWeek().length; ++i) {
                    if (days.contains(schedule.getWeek()[i])) {
                        Day temp = schedule.getElementFromSchedule(i);
                        value = closeTimeMatchAction(resultSet, update, temp, value, isTimeBased);
                    }
                }
                value = addHalfAPt(conn, resultSet, schedule, searcher, value);
            }

            String cnbr = resultSet.getString("cnbr");
            String cdept = resultSet.getString("cdept");

            if (isTimeBased) {
                boolean hasMatch = false;
                List<JSONObject> courses = reqs.get(cdept);
                if (null != courses) {
                    for (JSONObject obj : courses) {
                        try {
                            // check if cnum is null
                            String cnum;
                            if (JSONObject.NULL == obj.get("cnum")) {
                                cnum = null;
                            } else {
                                cnum = Integer.toString(obj.getInt("cnum"));
                            }
                            String dept = obj.getString("dept");
                            if (null == cnum || cnbr.startsWith(cnum)) {
                                hasMatch = true;
                                break;

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    } // end for courses

                } // and if courses!=null
                if (!hasMatch && !reqs.isEmpty()) {
                    value += 1;
                    update.setFloat(1, value);
                    update.execute();
                } else {

                    update.setFloat(1, value);
                    update.execute();
                }
            } else {
                update.setFloat(1, value);
                update.execute();
            } // end if(isTimeBased)
        } // end while(rs.next())
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java

public void populateInvoice(OleInvoiceDocument invoiceDocument) {

    PurchaseOrderDocument purchaseOrderDocument = invoiceDocument.getPurchaseOrderDocument();

    // make a call to search for expired/closed accounts
    HashMap<String, ExpiredOrClosedAccountEntry> expiredOrClosedAccountList = getAccountsPayableService()
            .getExpiredOrClosedAccountList(invoiceDocument);

    //SpringContext.getBean(OleInvoiceService.class).populateInvoiceFromPurchaseOrders(invoiceDocument,expiredOrClosedAccountList);

    // invoiceDocument.getDocumentHeader().setDocumentDescription(createPreqDocumentDescription(invoiceDocument.getPurchaseOrderIdentifier(), invoiceDocument.getVendorName()));

    // write a note for expired/closed accounts if any exist and add a message stating there were expired/closed accounts at the
    // top of the document
    getAccountsPayableService().generateExpiredOrClosedAccountNote(invoiceDocument, expiredOrClosedAccountList);

    // set indicator so a message is displayed for accounts that were replaced due to expired/closed status
    if (!expiredOrClosedAccountList.isEmpty()) {
        invoiceDocument.setContinuationAccountIndicator(true);
    }/*from w  w  w  . jav  a 2 s  . c  o  m*/

    // add discount item
    calculateDiscount(invoiceDocument);
    // distribute accounts (i.e. proration)
    distributeAccounting(invoiceDocument);

    // set bank code to default bank code in the system parameter
    Bank defaultBank = bankService.getDefaultBankByDocType(invoiceDocument.getClass());
    if (defaultBank != null) {
        invoiceDocument.setBankCode(defaultBank.getBankCode());
        invoiceDocument.setBank(defaultBank);
    }
}

From source file:com.MainFiles.Functions.java

public String generateReversal(HashMap<String, String> ISOdetails) throws IOException, InterruptedException {
    String response = "";
    String strResponse = "";
    try {//from  w w w .  j  a va2  s.c om
        // int attempts = Integer.parseInt(ISOdetails.get("trials"));
        String CORR_ID = this.generateCorelationID();
        ISOdetails.remove("CorrelationID");

        ISOdetails.put("0", "0420");
        ISOdetails.put("7", this.anyDate("MMddHHmmss"));
        ISOdetails.put("11", this.anyDate("MMddHHmmss"));
        ISOdetails.put("32", SOURCE_ID);
        ISOdetails.put("CorrelationID", CORR_ID);

        this.log("Reversal" + ISOdetails.get("CorrelationID"), "REVERSE");

        boolean sentToWebLogicAgain = false;
        HashMap ParamsFromAdapterAgain;
        ParamsFromAdapterAgain = new HashMap();

        QueueWriter queueWriter = new QueueWriter(QUEUE_REQUEST, PROVIDER_URL);

        int trials = 0;
        do {
            sentToWebLogicAgain = queueWriter.sendObject((HashMap) ISOdetails, CORR_ID);
            trials++;
        } while (sentToWebLogicAgain == false & trials < 3);

        if (sentToWebLogicAgain) {
            System.out
                    .println("[SENT: Reversal Transaction Sent to ESB   -:]" + ISOdetails.get("CorrelationID"));
            long Start = System.currentTimeMillis();
            long Stop = Start + (20 * 1000);
            do {
                Thread.currentThread().sleep(100);
                ParamsFromAdapterAgain = this.getWeblogicMessageFromQueue(ISOdetails.get("CorrelationID"));
            } while (ParamsFromAdapterAgain.isEmpty() && System.currentTimeMillis() < Stop);

            if (ParamsFromAdapterAgain.isEmpty()) {

                System.out.println("[SENT: Transaction Responses Failed from ESB-:] " + ISOdetails.get("37"));

                //Send Failed Response to POS
                String TransactionType = getTransactionType(ISOdetails.get("3").toString());

                strResponse += this.strResponseHeader(ISOdetails.get("68").toString()) + "#";
                strResponse += "AGENT ID:  " + ISOdetails.get("104").toString() + "#";
                strResponse += "TRAN NUM:  " + ISOdetails.get("37").toString() + "#";
                strResponse += "--------------------------------" + "#";
                strResponse += "                                " + "#";
                strResponse += padEqual(TransactionType.toUpperCase()) + "#";
                strResponse += "                                " + "#";
                strResponse += "   NO RESPONSE FROM ESB GATEWAY " + "#";
                strResponse += " " + "#";
                strResponse += this.strResponseFooter(ISOdetails.get("104").toString()) + "#";
                SendPOSResponse(strResponse, ISOdetails.get("37").toString());

            } else {
                response = this.genHashDelimiterString(ParamsFromAdapterAgain,
                        ISOdetails.get("CorrelationID").toString());
            }
        }
    } catch (Exception ex) {
        this.log("\nINFO fn_Updateagentpassword() :: " + ex.getMessage() + "\n" + this.StackTraceWriter(ex),
                "ERROR");
    }
    return response;
}

From source file:it.unibas.spicy.persistence.DAOMappingTaskLines.java

@SuppressWarnings("unchecked")
private IDataSourceProxy loadCSVSource(Element sourceTargetCsvElement, String mappingTaskFilePath,
        boolean source, int scenarioNo, boolean web) throws DAOException, SQLException {
    HashSet<String> csvFullTableAbsoluteFilePath = new HashSet<String>();
    HashMap<String, ArrayList<Object>> csvFullInstAbsoluteFilePath = new HashMap<String, ArrayList<Object>>();
    Element sourceCsvDatabaseElement = sourceTargetCsvElement.getChild("csv-db-name");
    String csvDatabaseName = sourceCsvDatabaseElement.getTextTrim();
    Element sourceCsvTablesElement = sourceTargetCsvElement.getChild("csv-tables");
    List<Element> sourceCsvTableElementList = sourceCsvTablesElement.getChildren("csv-table");
    for (Element sourceCsvTableElement : sourceCsvTableElementList) {
        Element sourceCsvFileElement = sourceCsvTableElement.getChild("schema");
        String csvTableRelativeFilePath = sourceCsvFileElement.getTextTrim();
        //create the full path for all files that contain schema tables
        String csvTableAbsoluteFilePath = filePathTransformator.expand(mappingTaskFilePath,
                csvTableRelativeFilePath);
        csvFullTableAbsoluteFilePath.add(csvTableAbsoluteFilePath);
        //getting the filename from file's full path
        File userFile = new File(csvTableAbsoluteFilePath);
        String tableName = userFile.getName();
        //exclude filename extension
        if (tableName.indexOf(".") > 0) {
            tableName = tableName.substring(0, tableName.lastIndexOf("."));
        }//from w  w  w. j  av a2  s  . com
        //create the full path for all files that contain instances too
        Element sourceCsvInstancesElement = sourceCsvTableElement.getChild("instances");
        List<Element> sourceCsvInstanceElementList = sourceCsvInstancesElement.getChildren("instance");
        for (Element sourceCsvInstanceElement : sourceCsvInstanceElementList) {
            ArrayList<Object> valSet = new ArrayList<Object>();
            Element sourceCsvInstPathElement = sourceCsvInstanceElement.getChild("path");
            String csvInstRelativeFilePath = sourceCsvInstPathElement.getTextTrim();
            String csvInstAbsoluteFilePath = filePathTransformator.expand(mappingTaskFilePath,
                    csvInstRelativeFilePath);
            Element sourceCsvInstColNamesElement = sourceCsvInstanceElement.getChild("column-names");
            boolean csvInstColNames = Boolean.valueOf(sourceCsvInstColNamesElement.getTextTrim());
            valSet.add(tableName);
            valSet.add(csvInstColNames);
            valSet.add(false);
            csvFullInstAbsoluteFilePath.put(csvInstAbsoluteFilePath, valSet);
        }
    }
    IDataSourceProxy dataSource;
    if (web) {
        dataSource = daoCSV.loadSchemaForWeb(scenarioNo, csvFullTableAbsoluteFilePath, csvDatabaseName);
    } else {
        dataSource = daoCSV.loadSchema(scenarioNo, csvFullTableAbsoluteFilePath, csvDatabaseName, source,
                csvFullInstAbsoluteFilePath);
        if (!csvFullInstAbsoluteFilePath.isEmpty()) {
            daoCSV.loadInstanceSample(dataSource, csvFullInstAbsoluteFilePath, csvDatabaseName);
        }
    }
    return dataSource;
}