Example usage for java.lang String compareToIgnoreCase

List of usage examples for java.lang String compareToIgnoreCase

Introduction

In this page you can find the example usage for java.lang String compareToIgnoreCase.

Prototype

public int compareToIgnoreCase(String str) 

Source Link

Document

Compares two strings lexicographically, ignoring case differences.

Usage

From source file:org.apache.mahout.classifier.chi_rwcs.mapreduce.BuildModel.java

@Override
public int run(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

    DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
    ArgumentBuilder abuilder = new ArgumentBuilder();
    GroupBuilder gbuilder = new GroupBuilder();

    Option dataOpt = obuilder.withLongName("data").withShortName("d").withRequired(true)
            .withArgument(abuilder.withName("path").withMinimum(1).withMaximum(1).create())
            .withDescription("Data path").create();

    Option datasetOpt = obuilder.withLongName("dataset").withShortName("ds").withRequired(true)
            .withArgument(abuilder.withName("dataset").withMinimum(1).withMaximum(1).create())
            .withDescription("The path of the file descriptor of the dataset").create();

    Option timeOpt = obuilder.withLongName("time").withShortName("tm").withRequired(false)
            .withArgument(abuilder.withName("path").withMinimum(1).withMaximum(1).create())
            .withDescription("Time path").create();

    Option outputOpt = obuilder.withLongName("output").withShortName("o").withRequired(true)
            .withArgument(abuilder.withName("path").withMinimum(1).withMaximum(1).create())
            .withDescription("Output path, will contain the Decision Forest").create();

    Option labelsOpt = obuilder.withLongName("labels").withShortName("l").withRequired(true)
            .withArgument(abuilder.withName("labels").withMinimum(1).withMaximum(1).create())
            .withDescription("Number of Labels").create();

    Option combinationTypeOpt = obuilder.withLongName("combinationType").withShortName("t").withRequired(true)
            .withArgument(abuilder.withName("combinationType").withMinimum(1).withMaximum(1).create())
            .withDescription("T-norm for the computation of the compatibility degree").create();

    Option rule_weightOpt = obuilder.withLongName("rule_weight").withShortName("r").withRequired(true)
            .withArgument(abuilder.withName("rule_weight").withMinimum(1).withMaximum(1).create())
            .withDescription("Rule Weight").create();

    Option fuzzy_r_mOpt = obuilder.withLongName("fuzzy_r_m").withShortName("f").withRequired(true)
            .withArgument(abuilder.withName("fuzzy_r_m").withMinimum(1).withMaximum(1).create())
            .withDescription("Fuzzy Reasoning Method").create();

    Option helpOpt = obuilder.withLongName("help").withShortName("h").withDescription("Print out help")
            .create();/*from   w ww .ja  va  2  s  . co m*/

    Group group = gbuilder.withName("Options").withOption(dataOpt).withOption(datasetOpt).withOption(timeOpt)
            .withOption(outputOpt).withOption(labelsOpt).withOption(combinationTypeOpt)
            .withOption(rule_weightOpt).withOption(fuzzy_r_mOpt).withOption(helpOpt).create();

    try {
        Parser parser = new Parser();
        parser.setGroup(group);
        CommandLine cmdLine = parser.parse(args);

        if (cmdLine.hasOption("help")) {
            CommandLineUtil.printHelp(group);
            return -1;
        }

        dataName = cmdLine.getValue(dataOpt).toString();
        String datasetName = cmdLine.getValue(datasetOpt).toString();
        String outputName = cmdLine.getValue(outputOpt).toString();
        nLabels = Integer.parseInt(cmdLine.getValue(labelsOpt).toString());
        String combinationType_aux = cmdLine.getValue(combinationTypeOpt).toString();
        String ruleWeight_aux = cmdLine.getValue(rule_weightOpt).toString();
        String inferenceType_aux = cmdLine.getValue(fuzzy_r_mOpt).toString();

        if (cmdLine.hasOption(timeOpt)) {
            buildTimeIsStored = true;
            timeName = cmdLine.getValue(timeOpt).toString();
        }

        if (log.isDebugEnabled()) {
            log.debug("data : {}", dataName);
            log.debug("dataset : {}", datasetName);
            log.debug("output : {}", outputName);
            log.debug("labels : {}", nLabels);
            log.debug("t_norm : {}", combinationType_aux);
            log.debug("rule_weight : {}", ruleWeight_aux);
            log.debug("fuzzy_r_m : {}", inferenceType_aux);
            log.debug("time : {}", timeName);
        }

        dataPath = new Path(dataName);
        datasetPath = new Path(datasetName);
        outputPath = new Path(outputName);
        if (buildTimeIsStored)
            timePath = new Path(timeName);

        combinationType = PRODUCT;
        if (combinationType_aux.compareToIgnoreCase("minimum") == 0) {
            combinationType = MINIMUM;
        }

        ruleWeight = PCF_IV;
        if (ruleWeight_aux.compareToIgnoreCase("Certainty_Factor") == 0) {
            ruleWeight = CF;
        } else if (ruleWeight_aux.compareToIgnoreCase("Average_Penalized_Certainty_Factor") == 0) {
            ruleWeight = PCF_II;
        } else if (ruleWeight_aux.compareToIgnoreCase("No_Weights") == 0) {
            ruleWeight = NO_RW;
        }

        inferenceType = WINNING_RULE;
        if (inferenceType_aux.compareToIgnoreCase("Additive_Combination") == 0) {
            inferenceType = ADDITIVE_COMBINATION;
        }

    } catch (OptionException e) {
        log.error("Exception", e);
        CommandLineUtil.printHelp(group);
        return -1;
    }

    buildModel();

    return 0;
}

From source file:hydrograph.ui.dataviewer.filter.FilterConditionsDialog.java

/**
 * Set map of fields and their types respectively
 * @param fieldsAndTypes/*from   w w w  . j a  v a 2s.  c  o  m*/
 */
public void setFieldsAndTypes(Map<String, String> fieldsAndTypes) {
    this.fieldsAndTypes = fieldsAndTypes;
    fieldNames = (String[]) this.fieldsAndTypes.keySet().toArray(new String[this.fieldsAndTypes.size()]);
    Arrays.sort(fieldNames, new Comparator<String>() {
        public int compare(String string1, String string2) {
            return string1.compareToIgnoreCase(string2);
        };
    });
}

From source file:com.krawler.workflow.bizservice.WorkflowServiceImpl.java

@Override
public String reloadWorkflow(String processid) throws ServiceException {
    String result = "{\"success\":false}";
    try {//from   w w w  .j ava  2 s .  c  o m
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

        String path = ConfigReader.getinstance().get("workflowpath") + processid;

        File fdir = new File(path);
        File file = new File(fdir + System.getProperty("file.separator") + "bpmn.xml");
        Document doc = docBuilder.parse(file);
        int s;
        int a;
        String name = "";
        ObjectInfo obj = new ObjectInfo();
        ArrayList taskContainer = new ArrayList();

        String nodeName = "";
        NodeList nodeList = doc.getElementsByTagName("Pool");
        for (s = 1; s < nodeList.getLength(); s++) {
            Node node = nodeList.item(s);
            ObjectInfo processObj = new ObjectInfo();
            processObj.type = "process";
            getNodeInfo(node, processObj);
            NodeList childrenList = node.getChildNodes();
            for (int cnt = 0; cnt < childrenList.getLength(); cnt++) {
                node = childrenList.item(cnt);
                nodeName = node.getNodeName();
                if (nodeName.compareToIgnoreCase("Lanes") == 0) {
                    NodeList laneList = node.getChildNodes();
                    for (int laneCount = 0; laneCount < laneList.getLength(); laneCount++) {
                        node = laneList.item(laneCount);
                        nodeName = node.getNodeName();
                        if (nodeName.compareToIgnoreCase("Lane") == 0) {
                            ObjectInfo laneObj = new ObjectInfo();
                            laneObj.type = "lane";
                            getNodeInfo(node, laneObj);
                            NodeList laneChildren = node.getChildNodes();
                            for (int laneChildrencnt = 0; laneChildrencnt < laneChildren
                                    .getLength(); laneChildrencnt++) {
                                node = laneChildren.item(laneChildrencnt);
                                nodeName = node.getNodeName();
                                if (nodeName.compareToIgnoreCase("NodeGraphicsInfos") == 0) {
                                    getGraphicsNodeInfo(getActivityNode(node, 1), laneObj);
                                }
                            }
                            taskContainer.add(laneObj);
                        }
                    }
                } else {
                    if (nodeName.compareToIgnoreCase("NodeGraphicsInfos") == 0) {
                        getGraphicsNodeInfo(getActivityNode(node, 1), processObj);
                    }
                }

            }
            taskContainer.add(processObj);
        }

        nodeList = doc.getElementsByTagName("Activities");

        for (s = 0; s < nodeList.getLength(); s++) {
            name = "";
            Node node = nodeList.item(s);
            NodeList childrenList = node.getChildNodes();
            for (int cnt = 0; cnt < childrenList.getLength(); cnt++) {
                node = childrenList.item(cnt);
                Node activityNode = getActivityNode(node, 0);
                if (activityNode.getNodeType() == Node.ELEMENT_NODE) {
                    obj = new ObjectInfo();
                    obj.type = "activity";
                    getNodeInfo(activityNode, obj);
                    Node graphicsInfoNode = getActivityNode(activityNode, 1);
                    getGraphicsNodeInfo(graphicsInfoNode, obj);
                    taskContainer.add(obj);
                }
            }
        }

        JSONObject jtemp = new com.krawler.utils.json.base.JSONObject();
        for (int j = 0; j < taskContainer.size(); j++) {
            obj = (ObjectInfo) taskContainer.get(j);
            JSONObject jobj = new com.krawler.utils.json.base.JSONObject();
            jobj.put("Id", obj.objId);
            jobj.put("name", obj.name);
            jobj.put("xpos", obj.xpos);
            jobj.put("ypos", obj.ypos);
            jobj.put("height", obj.height);
            jobj.put("width", obj.width);
            jobj.put("parent", obj.parentId);
            jobj.put("refId", obj.refId);
            jobj.put("hasStart", obj.hasStart);
            jobj.put("hasEnd", obj.hasEnd);
            jobj.put("startRefId", obj.startRefId);
            jobj.put("endRefId", obj.endRefId);
            jobj.put("derivationRule", obj.derivationRule);
            jobj.put("domEl", obj.domEl);
            if (obj.type.compareToIgnoreCase("activity") == 0) {
                jtemp.append("data", jobj);
            } else if (obj.type.compareToIgnoreCase("process") == 0) {
                jtemp.append("processes", jobj);
            } else if (obj.type.compareToIgnoreCase("lane") == 0) {
                jtemp.append("lanes", jobj);
            }
        }

        NodeList transitionList = doc.getElementsByTagName("Transitions");
        for (int i = 0; i < transitionList.getLength(); i++) {
            Node node = transitionList.item(i);
            NodeList childrenList = node.getChildNodes();

            for (int cnt = 0; cnt < childrenList.getLength(); cnt++) {
                node = childrenList.item(cnt);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    JSONObject jobj = new com.krawler.utils.json.base.JSONObject();
                    NamedNodeMap attr = node.getAttributes();
                    for (int b = 0; b < attr.getLength(); b++) {
                        Node attribute = attr.item(b);
                        name = attribute.getNodeName();
                        if (name.compareToIgnoreCase("From") == 0) {
                            jobj.put("fromId", attribute.getNodeValue());
                        } else if (name.compareToIgnoreCase("To") == 0) {
                            jobj.put("toId", attribute.getNodeValue());
                        }
                    }
                    jtemp.append("Lines", jobj);
                }
            }
        }

        return jtemp.toString();
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
        result = "{\"success\":false}";
        throw ServiceException.FAILURE("workflow.reloadWorkflow", ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
        result = "{\"success\":false}";
        throw ServiceException.FAILURE("workflow.reloadWorkflow", ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
        result = "{\"success\":false}";
        throw ServiceException.FAILURE("workflow.reloadWorkflow", ex);
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        result = "{\"success\":false}";
        throw ServiceException.FAILURE("workflow.reloadWorkflow", ex);
    }
}

From source file:org.kuali.kfs.module.bc.document.service.impl.BudgetDocumentServiceImpl.java

/**
 * @see org.kuali.kfs.module.bc.document.service.BudgetDocumentService#updatePendingBudgetGeneralLedgerPlug(org.kuali.kfs.module.bc.document.BudgetConstructionDocument,
 *      org.kuali.rice.core.api.util.type.KualiInteger)
 *///from www.j a  va 2s  .  c  om
@Transactional
public PendingBudgetConstructionGeneralLedger updatePendingBudgetGeneralLedgerPlug(
        BudgetConstructionDocument bcDoc, KualiInteger updateAmount) {

    String twoPlugKey = KFSConstants.BudgetConstructionConstants.OBJECT_CODE_2PLG
            + KFSConstants.getDashFinancialSubObjectCode();
    List<PendingBudgetConstructionGeneralLedger> expenditureRows = bcDoc
            .getPendingBudgetConstructionGeneralLedgerExpenditureLines();
    PendingBudgetConstructionGeneralLedger twoPlugRow = null;

    // update or insert the 2plg row - this assumes at least one row in the set
    // we can't even do salary setting without at least one detail line
    int index = 0;
    boolean insertNeeded = true;
    for (PendingBudgetConstructionGeneralLedger expRow : expenditureRows) {
        String expRowKey = expRow.getFinancialObjectCode() + expRow.getFinancialSubObjectCode();
        if (expRowKey.compareToIgnoreCase(twoPlugKey) == 0) {

            // update the existing row
            insertNeeded = false;
            expRow.setAccountLineAnnualBalanceAmount(
                    expRow.getAccountLineAnnualBalanceAmount().add(updateAmount.negated()));
            expRow.setPersistedAccountLineAnnualBalanceAmount(expRow.getAccountLineAnnualBalanceAmount());
            businessObjectService.save(expRow);
            expRow.refresh();
            twoPlugRow = expRow;
            break;
        } else {
            if (expRowKey.compareToIgnoreCase(twoPlugKey) > 0) {

                // case where offsetting salary setting updates under different object codes - insert a new row here
                break;
            }
        }
        index++;
    }
    if (insertNeeded) {

        // do insert in the middle or at end of list
        String objectCode = KFSConstants.BudgetConstructionConstants.OBJECT_CODE_2PLG;
        String subObjectCode = KFSConstants.getDashFinancialSubObjectCode();
        String objectTypeCode = optionsService.getOptions(bcDoc.getUniversityFiscalYear())
                .getFinObjTypeExpenditureexpCd();

        PendingBudgetConstructionGeneralLedger pendingRecord = new PendingBudgetConstructionGeneralLedger();

        pendingRecord.setDocumentNumber(bcDoc.getDocumentNumber());
        pendingRecord.setUniversityFiscalYear(bcDoc.getUniversityFiscalYear());
        pendingRecord.setChartOfAccountsCode(bcDoc.getChartOfAccountsCode());
        pendingRecord.setAccountNumber(bcDoc.getAccountNumber());
        pendingRecord.setSubAccountNumber(bcDoc.getSubAccountNumber());

        pendingRecord.setFinancialObjectCode(objectCode);
        pendingRecord.setFinancialSubObjectCode(subObjectCode);
        pendingRecord.setFinancialBalanceTypeCode(KFSConstants.BALANCE_TYPE_BASE_BUDGET);
        pendingRecord.setFinancialObjectTypeCode(objectTypeCode);

        pendingRecord.setFinancialBeginningBalanceLineAmount(KualiInteger.ZERO);
        pendingRecord.setAccountLineAnnualBalanceAmount(updateAmount);

        // store and add to memory set
        pendingRecord
                .setPersistedAccountLineAnnualBalanceAmount(pendingRecord.getAccountLineAnnualBalanceAmount());
        businessObjectService.save(pendingRecord);
        expenditureRows.add(index, pendingRecord);
        twoPlugRow = pendingRecord;
        bcDoc.setContainsTwoPlug(true);
    }

    bcDoc.setExpenditureAccountLineAnnualBalanceAmountTotal(
            bcDoc.getExpenditureAccountLineAnnualBalanceAmountTotal().add(updateAmount.negated()));
    return twoPlugRow;
}

From source file:com.magestore.app.pos.api.m2.config.POSConfigDataAccess.java

/**
 * Ly country trong config//w  ww. j a v  a  2  s .  c o m
 *
 * @return
 * @throws DataAccessException
 * @throws ConnectionException
 * @throws ParseException
 * @throws IOException
 * @throws ParseException
 */
@Override
public Map<String, ConfigCountry> getCountryGroup()
        throws DataAccessException, ConnectionException, ParseException, IOException, ParseException {
    // nu cha load config, cn khi to ch  default
    if (mConfig == null)
        mConfig = new PosConfigDefault();

    List<LinkedTreeMap> countryList = (ArrayList) mConfig.getValue("country");
    Map<String, ConfigCountry> listConfigCountry = new LinkedTreeMap<>();
    Collections.sort(countryList, new Comparator<LinkedTreeMap>() {
        @Override
        public int compare(LinkedTreeMap linkedTreeMap, LinkedTreeMap linkedTreeMap1) {
            String name = linkedTreeMap.get("country_name").toString();
            String name1 = linkedTreeMap1.get("country_name").toString();
            return name.compareToIgnoreCase(name1);
        }
    });
    for (LinkedTreeMap country : countryList) {
        ConfigCountry configCountry = new PosConfigCountry();
        String country_id = country.get("country_id").toString();
        String country_name = country.get("country_name").toString();
        configCountry.setCountryID(country_id);
        configCountry.setCountryName(country_name);
        List<LinkedTreeMap> regionList = (ArrayList) country.get("regions");
        if (regionList != null) {
            Map<String, ConfigRegion> listConfigRegion = new LinkedTreeMap<>();
            Collections.sort(regionList, new Comparator<LinkedTreeMap>() {
                @Override
                public int compare(LinkedTreeMap linkedTreeMap, LinkedTreeMap linkedTreeMap1) {
                    String name = linkedTreeMap.get("name").toString();
                    String name1 = linkedTreeMap1.get("name").toString();
                    return name.compareToIgnoreCase(name1);
                }
            });
            for (LinkedTreeMap region : regionList) {
                ConfigRegion configRegion = new PosConfigRegion();
                String code = region.get("code").toString();
                String name = region.get("name").toString();
                String id = region.get("id").toString();
                configRegion.setID(id);
                configRegion.setCode(code);
                configRegion.setName(name);
                listConfigRegion.put(id, configRegion);
            }
            configCountry.setRegions(listConfigRegion);
        }
        listConfigCountry.put(country_id, configCountry);
    }
    return listConfigCountry;
}

From source file:org.openmrs.module.vcttrac.web.controller.VCTProgramEnrollmentController.java

/**
 * Auto generated method comment//from   w  w  w. java 2  s  .  co m
 * 
 * @param request
 * @param response
 * @param mav
 */
private void manageListing(HttpServletRequest request, HttpServletResponse response, ModelAndView mav) {
    VCTModuleService service = Context.getService(VCTModuleService.class);

    String pageNumber = (request.getParameter("page") != null) ? request.getParameter("page") : "1";
    //      StringBuilder parameters = new StringBuilder();
    //      parameters.append("");
    int pageSize;//, type;
    List<VCTClient> clients = new ArrayList<VCTClient>();

    List<Integer> res;

    List<Integer> numberOfPages;

    try {
        if (VCTConfigurationUtil.isConfigured()) {
            //            type = Integer.valueOf(request.getParameter("type"));
            //            parameters.append("&type=" + request.getParameter("type"));

            pageSize = Integer.valueOf(VCTConfigurationUtil.getNumberOfRecordPerPage());
            if (pageNumber.compareToIgnoreCase("1") == 0 || pageNumber.compareToIgnoreCase("") == 0) {
                res = new ArrayList<Integer>();

                //               if (request.getParameter("type") != null && request.getParameter("type").compareToIgnoreCase("0") == 0) {
                res = service.getVCTClientsWaitingToBeEnrolledInHIVProgram();
                /*   type = 0;
                } else if (request.getParameter("type") != null
                        && request.getParameter("type").compareToIgnoreCase("1") == 0) {
                   if (request.getParameter("from") != null
                  && request.getParameter("from").compareToIgnoreCase("pit") == 0)
                      res = service.getVCTClientsFromPIT();
                   else if (request.getParameter("from") != null
                  && request.getParameter("from").compareToIgnoreCase("vct") == 0)
                      res = service.getVoluntaryClients();
                   type = 1;
                   parameters.append("&from=" + request.getParameter("from"));
                } else if (request.getParameter("type") != null
                        && request.getParameter("type").compareToIgnoreCase("2") == 0) {
                   res = service.getVCTClientsBasedOnGender(request.getParameter("gender"));
                   type = 2;
                   parameters.append("&gender=" + request.getParameter("gender"));
                } else if (request.getParameter("type") != null
                        && request.getParameter("type").compareToIgnoreCase("3") == 0) {
                   if (request.getParameter("attributeTypeId") != null && request.getParameter("value") != null)
                      res = service.getVCTClientsBasedOnAttributeType(Integer.valueOf(request
                     .getParameter("attributeTypeId")), Integer.valueOf(request.getParameter("value")));
                           
                   type = 3;
                   parameters.append("&attributeTypeId=" + request.getParameter("attributeTypeId"));
                   parameters.append("&value=" + request.getParameter("value"));
                } else if (request.getParameter("type") != null
                        && request.getParameter("type").compareToIgnoreCase("4") == 0
                        && request.getParameter("tested") != null) {
                   res = service.getVCTClientsTested((request.getParameter("tested").compareTo("yes") == 0) ? true
                  : false);
                           
                   type = 4;
                   parameters.append("&tested=" + request.getParameter("tested"));
                } else if (request.getParameter("type") != null
                        && request.getParameter("type").compareToIgnoreCase("5") == 0) {
                   if (request.getParameter("conceptId") != null && request.getParameter("value") != null
                  && request.getParameter("gotresult") != null) {
                      res = service.getVCTClientsBasedOnConceptObs(Integer.valueOf(request.getParameter("conceptId")),
                 Integer.valueOf(request.getParameter("value")), (request.getParameter("gotresult")
                         .compareToIgnoreCase("true") == 0));
                              
                      parameters.append("&value=" + request.getParameter("value"));
                   } else if (request.getParameter("gotresult") != null) {
                      res = service.getVCTClientsBasedOnConceptObs(Integer.valueOf(request.getParameter("conceptId")),
                 null, (request.getParameter("gotresult").compareToIgnoreCase("true") == 0));
                   }
                   type = 5;
                   parameters.append("&conceptId=" + request.getParameter("conceptId"));
                   parameters.append("&gotresult=" + request.getParameter("gotresult"));
                } else if (request.getParameter("type") != null
                        && request.getParameter("type").compareToIgnoreCase("6") == 0) {
                   if (request.getParameter("counselingType") != null)
                      res = service.getVCTClientsBasedOnCounselingType(Integer.valueOf(request
                     .getParameter("counselingType")));
                           
                   type = 6;
                   parameters.append("&counselingType=" + request.getParameter("counselingType"));
                }*/

                request.getSession().setAttribute("prg_enrollment_res", res);

                //data collection
                for (int i = 0; i < pageSize; i++) {
                    if (res.size() == 0)
                        break;
                    if (i >= res.size() - 1) {
                        clients.add(service.getClientById(res.get(i)));
                        break;
                    } else
                        clients.add(service.getClientById(res.get(i)));
                }

                //---------paging-------navigation between pages--------
                int n = (res.size() == ((int) (res.size() / pageSize)) * pageSize) ? (res.size() / pageSize)
                        : ((int) (res.size() / pageSize)) + 1;
                numberOfPages = new ArrayList<Integer>();
                for (int i = 1; i <= n; i++) {
                    numberOfPages.add(i);
                }

                request.getSession().setAttribute("prg_enrollment_numberOfPages", numberOfPages);

                if (Integer.valueOf(pageNumber) > 1)
                    mav.addObject("prevPage", (Integer.valueOf(pageNumber)) - 1);
                else
                    mav.addObject("prevPage", -1);
                if (Integer.valueOf(pageNumber) < numberOfPages.size())
                    mav.addObject("nextPage", (Integer.valueOf(pageNumber)) + 1);
                else
                    mav.addObject("nextPage", -1);
                mav.addObject("lastPage", ((numberOfPages.size() >= 1) ? numberOfPages.size() : 1));
                //----------------

            } else {
                res = (List<Integer>) request.getSession().getAttribute("prg_enrollment_res");
                numberOfPages = (List<Integer>) request.getSession()
                        .getAttribute("prg_enrollment_numberOfPages");
                for (int i = (pageSize * (Integer.parseInt(pageNumber) - 1)); i < pageSize
                        * (Integer.parseInt(pageNumber)); i++) {
                    if (i >= res.size())
                        break;
                    else
                        clients.add(service.getClientById(res.get(i)));
                }
            }

            String title = VCTTracUtil.getMessage("vcttrac.statistic.clientwaitingenrollment", null);

            mav.addObject("title", title);

            /*switch (type) {
               case 0: {
                  title = "All Clients";
                  mav.addObject("title", title);
                  break;
               }
               case 1: {
                  title = "Clients from " + request.getParameter("from").toUpperCase();
                  mav.addObject("title", title);
                  break;
               }
               case 2: {
                  title = "Gender : " + ((request.getParameter("gender").compareTo("f") == 0) ? "Female" : "Male");
                  mav.addObject("title", title);
                  break;
               }
               case 3: {
                  title = Context.getPersonService().getPersonAttribute(
              Integer.valueOf(request.getParameter("attributeTypeId"))).getAttributeType().getName()
                  + " : "
                  + Context.getConceptService().getConcept(Integer.valueOf(request.getParameter("value")))
                          .getDisplayString();
                  mav.addObject("title", title);
                  break;
               }
               case 4: {
                  title = "Tested : " + request.getParameter("tested").toUpperCase();
                          
                  mav.addObject("title", title);
                  break;
               }
               case 5: {
                  title = Context.getConceptService().getConcept(Integer.valueOf(request.getParameter("conceptId")))
                  .getDisplayString()
                  + " : "
                  + ((request.getParameter("value") != null) ? Context.getConceptService().getConcept(
                      Integer.valueOf(request.getParameter("value"))).getDisplayString() : "ALL RESULTS");
                          
                  mav.addObject("title", title);
                  break;
               }
               case 6: {
                  title = "Counseling Type : "
                  + ((request.getParameter("counselingType").compareToIgnoreCase("1") == 0) ? "Individual"
                          : "Couples");
                          
                  mav.addObject("title", title);
                  break;
               }
               default: {
                  title = "...";
                  mav.addObject("title", "...");
                  break;
               }
            }*/

            //page infos
            Object[] pagerInfos = new Object[3];
            pagerInfos[0] = (res.size() == 0) ? 0 : (pageSize * (Integer.parseInt(pageNumber) - 1)) + 1;
            pagerInfos[1] = (pageSize * (Integer.parseInt(pageNumber)) <= res.size())
                    ? pageSize * (Integer.parseInt(pageNumber))
                    : res.size();
            pagerInfos[2] = res.size();

            ApplicationContext appContext = ContextProvider.getApplicationContext();

            mav.addObject("numberOfPages", numberOfPages);
            mav.addObject("clients", clients);
            //            mav.addObject("parameters", parameters.toString());
            mav.addObject("pageSize", pageSize);
            mav.addObject("pageInfos", appContext.getMessage("vcttrac.pagingInfo.showingResults", pagerInfos,
                    Context.getLocale()));

            FileExporter fexp = new FileExporter();

            if (request.getParameter("export") != null
                    && request.getParameter("export").compareToIgnoreCase("csv") == 0) {
                List<VCTClient> clientList = new ArrayList<VCTClient>();
                for (Integer clientId : res) {
                    clientList.add(service.getClientById(clientId));
                }
                fexp.exportToCSVFile(request, response, clientList,
                        "list_of_clients_in_vct_program_" + title + ".csv",
                        VCTTracUtil.getMessage("vcttrac.statistic.clientlist", null) + " : "
                                + title.toUpperCase(),
                        "Client waiting to be enrolled in Program");
            }
        }

    } catch (Exception e) {
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                VCTTracUtil.getMessage("vcttrac.error.loadingData", null));

        log.error(">>>>>>>>>>>>VCT>>Statistics>>>> An error occured : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:blusunrize.immersiveengineering.client.ClientProxy.java

public static void handleMineralManual() {
    if (ManualHelper.getManual() != null) {
        ArrayList<IManualPage> pages = new ArrayList();
        pages.add(new ManualPages.Text(ManualHelper.getManual(), "minerals0"));
        pages.add(new ManualPages.Crafting(ManualHelper.getManual(), "minerals1",
                new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.SAMPLE_DRILL.getMeta())));
        pages.add(new ManualPages.Text(ManualHelper.getManual(), "minerals2"));

        final ExcavatorHandler.MineralMix[] minerals = ExcavatorHandler.mineralList.keySet()
                .toArray(new ExcavatorHandler.MineralMix[0]);

        ArrayList<Integer> mineralIndices = new ArrayList();
        for (int i = 0; i < minerals.length; i++)
            if (minerals[i].isValid())
                mineralIndices.add(i);//  w w  w  . j ava2  s  .  c o m
        Collections.sort(mineralIndices, new Comparator<Integer>() {
            @Override
            public int compare(Integer paramT1, Integer paramT2) {
                String name1 = Lib.DESC_INFO + "mineral." + minerals[paramT1].name;
                String localizedName1 = I18n.format(name1);
                if (localizedName1 == name1)
                    localizedName1 = minerals[paramT1].name;

                String name2 = Lib.DESC_INFO + "mineral." + minerals[paramT2].name;
                String localizedName2 = I18n.format(name2);
                if (localizedName2 == name2)
                    localizedName2 = minerals[paramT2].name;
                return localizedName1.compareToIgnoreCase(localizedName2);
            }
        });
        for (int i : mineralIndices) {
            String name = Lib.DESC_INFO + "mineral." + minerals[i].name;
            String localizedName = I18n.format(name);
            if (localizedName.equalsIgnoreCase(name))
                localizedName = minerals[i].name;

            String s0 = "";
            if (minerals[i].dimensionWhitelist != null && minerals[i].dimensionWhitelist.length > 0) {
                String validDims = "";
                for (int dim : minerals[i].dimensionWhitelist)
                    validDims += (!validDims.isEmpty() ? ", " : "") + "<dim;" + dim + ">";
                s0 = I18n.format("ie.manual.entry.mineralsDimValid", localizedName, validDims);
            } else if (minerals[i].dimensionBlacklist != null && minerals[i].dimensionBlacklist.length > 0) {
                String invalidDims = "";
                for (int dim : minerals[i].dimensionBlacklist)
                    invalidDims += (!invalidDims.isEmpty() ? ", " : "") + "<dim;" + dim + ">";
                s0 = I18n.format("ie.manual.entry.mineralsDimInvalid", localizedName, invalidDims);
            } else
                s0 = I18n.format("ie.manual.entry.mineralsDimAny", localizedName);

            ArrayList<Integer> formattedOutputs = new ArrayList<Integer>();
            for (int j = 0; j < minerals[i].oreOutput.size(); j++)
                formattedOutputs.add(j);
            final int fi = i;
            Collections.sort(formattedOutputs, new Comparator<Integer>() {
                @Override
                public int compare(Integer paramT1, Integer paramT2) {
                    return -Double.compare(minerals[fi].recalculatedChances[paramT1],
                            minerals[fi].recalculatedChances[paramT2]);
                }
            });

            String s1 = "";
            NonNullList<ItemStack> sortedOres = NonNullList.withSize(minerals[i].oreOutput.size(),
                    ItemStack.EMPTY);
            for (int j = 0; j < formattedOutputs.size(); j++)
                if (!minerals[i].oreOutput.get(j).isEmpty()) {
                    int sorted = formattedOutputs.get(j);
                    s1 += "<br>"
                            + new DecimalFormat("00.00").format(minerals[i].recalculatedChances[sorted] * 100)
                                    .replaceAll("\\G0", " ")
                            + "% " + minerals[i].oreOutput.get(sorted).getDisplayName();
                    sortedOres.set(j, minerals[i].oreOutput.get(sorted));
                }
            String s2 = I18n.format("ie.manual.entry.minerals3", s0, s1);
            pages.add(new ManualPages.ItemDisplay(ManualHelper.getManual(), s2, sortedOres));
        }

        //         String[][][] multiTables = formatToTable_ExcavatorMinerals();
        //         for(String[][] minTable : multiTables)
        //            pages.add(new ManualPages.Table(ManualHelper.getManual(), "", minTable,true));
        if (mineralEntry != null)
            mineralEntry.setPages(pages.toArray(new IManualPage[pages.size()]));
        else {
            ManualHelper.addEntry("minerals", ManualHelper.CAT_GENERAL,
                    pages.toArray(new IManualPage[pages.size()]));
            mineralEntry = ManualHelper.getManual().getEntry("minerals");
        }
    }
}

From source file:org.rdv.ui.TimeSlider.java

/**
 * Gets the text for the tooltip. This will return a description of the
 * markers the mouse pointer is around./*  w ww  .j  av a 2  s.  c o  m*/
 * 
 * @param me  the mouse event that triggered this
 * @return    text describing the markers around the mouse pointer
 */
public String getToolTipText(MouseEvent me) {
    int x = me.getX();
    if (me.getSource() == valueButton) {
        x += valueButton.getX();
    }

    double time = getTimeFromX(x);
    double timeOffset = time - value;

    double markerOffset = 2 * getPixelTime();
    List<EventMarker> markersOver = getMarkersAroundTime(time, markerOffset);

    String text = new String("<html><font size=\"5\">");

    text += DataViewer.formatDateSmart(time);
    if (timeOffset != 0) {
        text += " (" + (timeOffset < 0 ? "-" : "+") + DataViewer.formatSeconds(Math.abs(timeOffset)) + ")";
    }

    int numberOfMarkers = markersOver.size();
    if (numberOfMarkers > 0) {
        text += "<br>Found " + numberOfMarkers + " event" + (numberOfMarkers == 1 ? "" : "s") + " (&plusmn;"
                + DataViewer.formatSeconds(markerOffset) + ")<br><br>";
    }

    for (EventMarker marker : markersOver) {
        String date = DataViewer.formatDate(Double.parseDouble(marker.getProperty("timestamp")));
        String source = marker.getProperty("source");
        String type = marker.getProperty("type");
        String label = marker.getProperty("label");
        String content = marker.getProperty("content");

        boolean showType = false;
        String dateColor;
        if (type == null) {
            dateColor = "black";
        } else if (type.compareToIgnoreCase("annotation") == 0) {
            dateColor = "blue";
        } else if (type.compareToIgnoreCase("start") == 0) {
            dateColor = "green";
        } else if (type.compareToIgnoreCase("stop") == 0) {
            dateColor = "red";
        } else {
            showType = true;
            dateColor = "#FF9900";
        }

        text += "<font color=" + dateColor + ">" + date + "</font> ";

        if (showType) {
            text += "<i>" + type + "</i> ";
        }

        if (source != null && source.length() > 0) {
            text += "by " + source + ": ";
        }

        if (label != null && label.length() > 0) {
            text += "<u>" + label + "</u> ";
        }

        if (content != null && content.length() > 0) {
            int maxLineLength = 75;
            int maxLines = 10;

            String[] words = content.split(" ");
            int lineLength = 0;
            int lines = 0;
            for (String word : words) {
                if (lineLength + word.length() < (lines == 0 ? (maxLineLength - 32) : maxLineLength)) {
                    text += " " + word;
                    lineLength += word.length() + 1;
                } else {
                    if (++lines == maxLines) {
                        text += "...";
                        break;
                    }
                    text += "<br>" + word;
                    lineLength = word.length();
                }
            }
        }
        text += "<br>";
    }
    text += "</font></html>";

    return text;
}

From source file:au.com.wallaceit.reddinator.SubredditSelectActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.subredditselect);

    // load personal list from saved prefereces, if null use default and save
    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(SubredditSelectActivity.this);
    global = ((GlobalObjects) SubredditSelectActivity.this.getApplicationContext());

    // get subreddit list and set adapter
    subredditList = global.getSubredditManager().getSubredditNames();
    subsAdapter = new MySubredditsAdapter(this, subredditList);
    ListView subListView = (ListView) findViewById(R.id.sublist);
    subListView.setAdapter(subsAdapter);
    subListView.setTextFilterEnabled(true);
    subListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String subreddit = ((TextView) view.findViewById(R.id.subreddit_name)).getText().toString();
            global.getSubredditManager().setFeedSubreddit(mAppWidgetId, subreddit);
            updateFeedAndFinish();//w w w. java2  s  .  c o m
            //System.out.println(sreddit+" selected");
        }
    });
    subsAdapter.sort(new Comparator<String>() {
        @Override
        public int compare(String s, String t1) {
            return s.compareToIgnoreCase(t1);
        }
    });
    // get multi list and set adapter
    mMultiAdapter = new MyMultisAdapter(this);
    ListView multiListView = (ListView) findViewById(R.id.multilist);
    multiListView.setAdapter(mMultiAdapter);
    multiListView.setTextFilterEnabled(true);
    multiListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == mMultiAdapter.getCount() - 1) {
                LinearLayout layout = (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_multi_add,
                        parent, false);
                final EditText name = (EditText) layout.findViewById(R.id.new_multi_name);
                AlertDialog.Builder builder = new AlertDialog.Builder(SubredditSelectActivity.this);
                builder.setTitle("Create A Multi").setView(layout)
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                if (name.getText().toString().equals("")) {
                                    Toast.makeText(SubredditSelectActivity.this,
                                            "Please enter a name for the multi", Toast.LENGTH_LONG).show();
                                    return;
                                }
                                new SubscriptionEditTask(SubscriptionEditTask.ACTION_MULTI_CREATE)
                                        .execute(name.getText().toString());
                                dialogInterface.dismiss();
                            }
                        }).show();
            } else {
                JSONObject multiObj = mMultiAdapter.getItem(position);
                try {
                    String name = multiObj.getString("display_name");
                    String path = multiObj.getString("path");
                    global.getSubredditManager().setFeed(mAppWidgetId, name, path, true);
                    updateFeedAndFinish();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(SubredditSelectActivity.this, "Error setting multi.", Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    });

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            mAppWidgetId = 0; // Id of 4 zeros indicates its the app view, not a widget, that is being updated
        } else {
            String action = getIntent().getAction();
            widgetFirstTimeSetup = action != null
                    && action.equals("android.appwidget.action.APPWIDGET_CONFIGURE");
        }
    } else {
        mAppWidgetId = 0;
    }

    final ViewPager pager = (ViewPager) findViewById(R.id.pager);
    pager.setAdapter(new SimpleTabsAdapter(new String[] { "My Subreddits", "My Multis" },
            new int[] { R.id.sublist, R.id.multilist }, SubredditSelectActivity.this, null));

    LinearLayout tabsLayout = (LinearLayout) findViewById(R.id.tab_widget);
    tabs = new SimpleTabsWidget(SubredditSelectActivity.this, tabsLayout);
    tabs.setViewPager(pager);

    addButton = (Button) findViewById(R.id.addsrbutton);
    addButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Intent intent = new Intent(SubredditSelectActivity.this, ViewAllSubredditsActivity.class);
            startActivityForResult(intent, 1);
        }
    });
    refreshButton = (Button) findViewById(R.id.refreshloginbutton);
    refreshButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if (global.mRedditData.isLoggedIn()) {
                if (pager.getCurrentItem() == 1) {
                    refreshMultireddits();
                } else {
                    refreshSubreddits();
                }
            } else {
                global.mRedditData.initiateLogin(SubredditSelectActivity.this);
            }
        }
    });
    // sort button
    sortBtn = (Button) findViewById(R.id.sortselect);
    String sortTxt = "Sort:  "
            + mSharedPreferences.getString("sort-" + (mAppWidgetId == 0 ? "app" : mAppWidgetId), "hot");
    sortBtn.setText(sortTxt);
    sortBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            showSortDialog();
        }
    });

    ActionBar actionBar = getActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    // set theme colors
    setThemeColors();

    GlobalObjects.doShowWelcomeDialog(SubredditSelectActivity.this);
}

From source file:com.datatorrent.contrib.parser.FixedWidthParser.java

/**
 * Function to validate and set the current field.
 * @param currentField the field which is to be validated and set
 * @param value the parsed value of the field
 * @param typeInfo information about the field in POJO
 * @param pojoObject POJO which is to be set
 * @param toEmit the map to be emitted/*from   ww  w .  j  a  va2  s  . c o m*/
 */
private void validateAndSetCurrentField(FixedWidthSchema.Field currentField, String value,
        FixedWidthParser.TypeInfo typeInfo, Object pojoObject, HashMap toEmit) {
    try {
        String fieldName = currentField.getName();
        if (value != null && !value.isEmpty()) {
            Object result;
            switch (currentField.getType()) {
            case INTEGER:
                result = Integer.parseInt(value);
                break;
            case DOUBLE:
                result = Double.parseDouble(value);
                break;
            case STRING:
                result = value;
                break;
            case CHARACTER:
                result = value.charAt(0);
                break;
            case FLOAT:
                result = Float.parseFloat(value);
                break;
            case LONG:
                result = Long.parseLong(value);
                break;
            case SHORT:
                result = Short.parseShort(value);
                break;
            case BOOLEAN:
                if (value.compareToIgnoreCase(currentField.getTrueValue()) == 0) {
                    result = Boolean.parseBoolean("true");
                } else if (value.compareToIgnoreCase(currentField.getFalseValue()) == 0) {
                    result = Boolean.parseBoolean("false");
                } else {
                    throw new NumberFormatException();
                }
                break;
            case DATE:
                DateFormat df = new SimpleDateFormat(currentField.getDateFormat());
                df.setLenient(false);
                result = df.parse(value);
                break;
            default:
                throw new RuntimeException("Invalid Type in Field", new Exception());
            }
            toEmit.put(fieldName, result);
            if (typeInfo != null && pojoObject != null) {
                typeInfo.setter.set(pojoObject, result);
            }
        } else {
            toEmit.put(fieldName, value);
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException("Error parsing" + value + " to Integer type", e);
    } catch (ParseException e) {
        throw new RuntimeException("Error parsing" + value, e);
    } catch (Exception e) {
        throw new RuntimeException("Error setting " + value + " in the given class" + typeInfo.toString(), e);
    }
}