List of usage examples for org.apache.commons.lang3 StringUtils containsIgnoreCase
public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr)
Checks if CharSequence contains a search CharSequence irrespective of case, handling null .
From source file:com.glaf.oa.seal.web.springmvc.SealController.java
@RequestMapping("/edit") public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) { User user = RequestUtils.getUser(request); RequestUtils.setRequestParameterToAttribute(request); request.removeAttribute("canSubmit"); Seal seal = sealService.getSeal(RequestUtils.getLong(request, "sealid")); if (seal != null) { request.setAttribute("seal", seal); JSONObject rowJSON = seal.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); } else {// ww w. j a va 2s.c o m seal = new Seal(); long deptId01 = user.getDeptId(); SysDepartment curdept = sysDepartmentService.findById(deptId01); // ? String curAreadeptCode = curdept.getCode().substring(0, 2); seal.setArea(curAreadeptCode); seal.setDept(curdept.getCode()); seal.setAppuser(user.getActorId()); seal.setPost(RequestUtil.getLoginUser(request).getHeadship()); request.setAttribute("seal", seal); JSONObject rowJSON = seal.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); } boolean canUpdate = false; String x_method = request.getParameter("x_method"); if (StringUtils.equals(x_method, "submit")) { } if (StringUtils.containsIgnoreCase(x_method, "update")) { if (seal != null) { if (seal.getStatus() == 0 || seal.getStatus() == -1) { canUpdate = true; } } } request.setAttribute("canUpdate", canUpdate); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("seal.edit"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } if (seal != null) { String appusername = BaseDataManager.getInstance().getStringValue(seal.getAppuser(), "SYS_USERS"); request.setAttribute("appusername", appusername); } return new ModelAndView("/oa/seal/sealedit", modelMap); }
From source file:fr.scc.elo.controller.manager.impl.EloManagerImpl.java
private boolean contains(String term, Player p) { return StringUtils.containsIgnoreCase(p.getName(), term); }
From source file:com.kylinolap.cube.CubeManager.java
public static String getHbaseStorageLocationPrefix(String hbaseMetadataUrl) { String defaultPrefix = "KYLIN_CUBE_"; if (StringUtils.containsIgnoreCase(hbaseMetadataUrl, "hbase:")) { int cut = hbaseMetadataUrl.indexOf('@'); String tmp = cut < 0 ? defaultPrefix : hbaseMetadataUrl.substring(0, cut); String prefix = StringUtils.replace(tmp, "_metadata", ""); return (prefix + "_CUBE_").toUpperCase(); } else {//from www. j a v a2s . com return defaultPrefix; } }
From source file:com.marand.thinkmed.medications.business.MedicationsFinderImpl.java
private List<TreeNodeData> filterMedicationsTree(final List<TreeNodeData> medications, final String[] searchSubstrings, final boolean startMustMatch) { final List<TreeNodeData> filteredMedications = new ArrayList<>(); for (final TreeNodeData medicationNode : medications) { final MedicationSimpleDto medicationSimpleDto = (MedicationSimpleDto) medicationNode.getData(); final String medicationSearchName = medicationSimpleDto.getGenericName() != null ? medicationSimpleDto.getGenericName() + " " + medicationNode.getTitle() : medicationNode.getTitle(); medicationNode.setExpanded(false); boolean match = true; if (startMustMatch && searchSubstrings.length > 0) { final String firstSearchString = searchSubstrings[0]; final boolean genericStartsWithFirstSearchString = medicationSimpleDto.getGenericName() != null && StringUtils.startsWithIgnoreCase(medicationSimpleDto.getGenericName(), firstSearchString); final boolean medicationStartsWithFirstSearchString = StringUtils .startsWithIgnoreCase(medicationNode.getTitle(), firstSearchString); if (!genericStartsWithFirstSearchString && !medicationStartsWithFirstSearchString) { match = false;//from ww w. j av a2 s . c o m } } if (match) { for (int i = startMustMatch ? 1 : 0; i < searchSubstrings.length; i++) { if (!StringUtils.containsIgnoreCase(medicationSearchName, searchSubstrings[i])) { match = false; break; } } } if (match) { filteredMedications.add(medicationNode); } else { if (!medicationNode.getChildren().isEmpty()) { final List<TreeNodeData> filteredChildren = filterMedicationsTree(medicationNode.getChildren(), searchSubstrings, startMustMatch); if (!filteredChildren.isEmpty()) { medicationNode.setChildren(filteredChildren); filteredMedications.add(medicationNode); medicationNode.setExpanded(true); } } } } return filteredMedications; }
From source file:com.glaf.oa.contract.web.springmvc.ContractController.java
@RequestMapping("/edit") public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) { User user = RequestUtils.getUser(request); RequestUtils.setRequestParameterToAttribute(request); request.removeAttribute("canSubmit"); Contract contract = contractService.getContract(RequestUtils.getLong(request, "id")); if (contract != null) { request.setAttribute("contract", contract); JSONObject rowJSON = contract.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); }/*w w w . j a v a 2 s . c o m*/ boolean canUpdate = false; String x_method = request.getParameter("x_method"); if (StringUtils.equals(x_method, "submit")) { } if (StringUtils.containsIgnoreCase(x_method, "update")) { if (contract != null) { if (contract.getStatus() == 0 || contract.getStatus() == -1) { canUpdate = true; } } } request.setAttribute("canUpdate", canUpdate); if (contract != null) { } else { contract = new Contract(); long deptId01 = user.getDeptId(); SysDepartment curdept = sysDepartmentService.findById(deptId01); // ? String curAreadeptCode = curdept.getCode().substring(0, 2); contract.setArea(curAreadeptCode); contract.setDept(curdept.getCode()); contract.setAppuser(user.getActorId()); contract.setPost(RequestUtil.getLoginUser(request).getHeadship()); request.setAttribute("contract", contract); JSONObject rowJSON = contract.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); } String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("contract.edit"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/oa/contract/edit", modelMap); }
From source file:com.glaf.oa.salescontract.web.springmvc.SalescontractController.java
@RequestMapping("/edit") public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) { User user = RequestUtils.getUser(request); String actorId = user.getActorId(); RequestUtils.setRequestParameterToAttribute(request); request.removeAttribute("canSubmit"); Salescontract salescontract = salescontractService.getSalescontract(RequestUtils.getLong(request, "id")); if (salescontract != null) { request.setAttribute("salescontract", salescontract); JSONObject rowJSON = salescontract.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); // ???//from w ww .j a v a 2 s. com String appusername = BaseDataManager.getInstance().getStringValue(salescontract.getAppuser(), "SYS_USERS"); request.setAttribute("appusername", appusername); } else { // ? long deptId01 = user.getDeptId(); SysDepartment curdept = sysDepartmentService.findById(deptId01); // ? String curAreadeptCode = curdept.getCode().substring(0, 2); request.setAttribute("area", curAreadeptCode); salescontract = new Salescontract(); salescontract.setArea(curAreadeptCode); salescontract.setDept(curdept.getCode()); salescontract.setAppuser(user.getActorId()); salescontract.setHeadship(RequestUtil.getLoginUser(request).getHeadship()); salescontract.setOptionalsum(0.00); salescontract.setStatus(-1); salescontract.setCreateBy(actorId); salescontract.setAppdate(new Date()); salescontract.setCreatedate(new Date()); salescontractService.save(salescontract); request.setAttribute("salescontract", salescontract); JSONObject rowJSON = salescontract.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); } boolean canUpdate = false; String x_method = request.getParameter("x_method"); if (StringUtils.equals(x_method, "submit")) { } if (StringUtils.containsIgnoreCase(x_method, "update")) { if (salescontract != null) { if (salescontract.getStatus() == 0 || salescontract.getStatus() == -1) { canUpdate = true; } } } request.setAttribute("canUpdate", canUpdate); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("salescontract.edit"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/oa/salesContract/salesContractedit", modelMap); }
From source file:com.glaf.oa.payment.web.springmvc.PaymentController.java
@RequestMapping("/edit") public ModelAndView edit(HttpServletRequest request, ModelMap modelMap) { User user = RequestUtils.getUser(request); RequestUtils.setRequestParameterToAttribute(request); request.removeAttribute("canSubmit"); Payment payment = paymentService.getPayment(RequestUtils.getLong(request, "paymentid")); if (payment != null) { // ???/*from ww w . ja va 2 s . co m*/ String appusername = BaseDataManager.getInstance().getStringValue(payment.getAppuser(), "SYS_USERS"); request.setAttribute("appusername", appusername); request.setAttribute("payment", payment); JSONObject rowJSON = payment.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); } else { payment = new Payment(); long deptId01 = user.getDeptId(); SysDepartment curdept = sysDepartmentService.findById(deptId01); // ? String curAreadeptCode = curdept.getCode().substring(0, 2); payment.setArea(curAreadeptCode); payment.setDept(curdept.getCode()); payment.setAppuser(user.getActorId()); payment.setPost(RequestUtil.getLoginUser(request).getHeadship()); request.setAttribute("payment", payment); JSONObject rowJSON = payment.toJsonObject(); request.setAttribute("x_json", rowJSON.toJSONString()); } boolean canUpdate = false; String x_method = request.getParameter("x_method"); if (StringUtils.equals(x_method, "submit")) { } if (StringUtils.containsIgnoreCase(x_method, "update")) { if (payment != null) { if (payment.getStatus() == 0 || payment.getStatus() == -1) { canUpdate = true; } } } request.setAttribute("canUpdate", canUpdate); String view = request.getParameter("view"); if (StringUtils.isNotEmpty(view)) { return new ModelAndView(view, modelMap); } String x_view = ViewProperties.getString("payment.edit"); if (StringUtils.isNotEmpty(x_view)) { return new ModelAndView(x_view, modelMap); } return new ModelAndView("/oa/payment/payment_edit", modelMap); }
From source file:crawler.HackerEarthCrawler.java
@Override public void crawl() { int flag = 0; //set of urls which should be crawled TreeSet<String> linksset = new TreeSet<String>(); TreeSet<String> tempset = new TreeSet<String>(); TreeSet<String> tutorialset = new TreeSet<String>(); //final set of problem urls TreeSet<String> problemset = new TreeSet<String>(); //visited for maintaing status of if url is already crawled or not TreeMap<String, Integer> visited = new TreeMap<String, Integer>(); //add base url linksset.add(baseUrl);// w ww . jav a2 s. c o m //mark base url as not crawled visited.put(baseUrl, 0); try { while (true) { flag = 0; tempset.clear(); for (String str : linksset) { //check if url is already crawled or not and it has valid domain name if ((visited.get(str) == 0) && (str.startsWith("https://www.hackerearth.com/"))) { System.out.println("crawling " + str); //retriving response of current url as document Document doc = Jsoup.connect(str).timeout(0).userAgent( "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0") .referrer("http://www.google.com").ignoreHttpErrors(true).get(); //retriving all urls from current page Elements links = doc.select("a[href]"); //mark url as crawled visited.put(str, 1); //mark flag as url is crawled flag = 1; //retrive all urls for (Element link : links) { if (link.absUrl("href").endsWith("/tutorial/")) { tutorialset.add(link.absUrl("href")); } //check if url is problem url then add it in problemurlset if (link.absUrl("href").startsWith("https://www.hackerearth.com/") && isProblemUrl(link.absUrl("href"))) { problemset.add(link.absUrl("href")); } //check if url has valid domain and it has problem urls or not if (link.absUrl("href").contains(("https://www.hackerearth.com/")) && isCrawlable(link.absUrl("href"))) { //if link is not visited then mark it as uncrawled if (!visited.containsKey(link.absUrl("href"))) { visited.put(link.absUrl("href"), 0); } //add it in tempsetorary set tempset.add(link.absUrl("href")); //System.out.println("\n base: "+str+" ::: link : " + link.absUrl("href")); } } } } //if nothing is left to crawl break the loop if (flag == 0) { break; } //add all retrieved links to linksset linksset.addAll(tempset); } System.out.println("\n\ntotal problem urls " + problemset.size()); int i = 0; for (String str : problemset) { System.out.println("link " + i + " : " + str); i++; } } catch (IOException ex) { Logger.getLogger(HackerEarthCrawler.class.getName()).log(Level.SEVERE, null, ex); } //scrap and store into database //for every problem url scrap problem page for (String problemUrl : problemset) { System.out.println("problemUrl :" + problemUrl); try { //create problem class to store in database Problem problem = new Problem(); String problemSIOC = "", problemIOC = ""; String problemTitle = "", problemStatement = "", problemInput = "", problemOutput = "", problemConstraints = ""; String sampleInput = "", sampleOutput = ""; String problemExplanation = ""; //set default timelimit to 1 second double problemTimeLimit = 1.0; ArrayList<String> tags = new ArrayList<String>(); //get response for given problem url Response response = Jsoup.connect(problemUrl).execute(); Document doc = response.parse(); //retrieve problem title from page Element elementTitle = doc.getElementsByTag("title").first(); StringTokenizer stTitle = new StringTokenizer(elementTitle.text(), "|"); problemTitle = stTitle.nextToken().trim(); Element content = doc.getElementsByClass("starwars-lab").first(); problemSIOC = content.text(); Elements e = content.children(); //to find problem statement String breakloop[] = { "input", "input:", "input :", "input format:", "input format :", "input format", "Input and output", "constraints :", "constraints:", "constraints", "$$Input :$$" }; flag = 0; for (Element p : e) { String tempStatement = ""; for (Element pp : p.getAllElements()) { for (String strbreak : breakloop) { if (StringUtils.equalsIgnoreCase(pp.ownText(), strbreak)) { //System.out.println("strbreak :"+strbreak); tempStatement = p.text().substring(0, p.text().toLowerCase().indexOf(strbreak.toLowerCase())); // System.out.println("temp "+tempStatement); flag = 1; break; } } } if (flag == 1) { problemStatement += tempStatement; //remove extra space at end if (tempStatement.length() == 0) { problemStatement = problemStatement.substring(0, problemStatement.length() - 1); } break; } problemStatement += p.text() + " "; } System.out.println("problemSIOC :" + problemSIOC); System.out.println("problemStatement :" + problemStatement); if (problemStatement.length() <= problemSIOC.length()) { //remove problem statement from whole text and remove extra spaces at the beginning and the end problemIOC = problemSIOC.substring(problemStatement.length()).trim(); } else { problemIOC = ""; } System.out.println("problemIOC :" + problemIOC); //keywords for identifying input String decideInput[] = { "Input format :", "Input format:", "Input format", "inputformat:", "inputformat :", "inputformat", "input and output", "input :", "input:", "input" }; //keywords for identifying output String decideOutput[] = { "output format :", "output format:", "Output format", "outputformat:", "outputformat :", "outputformat", "output :", "output:", "output" }; //keywords for identifying constraint String decideConstraint[] = { "constraints:", "constraints :", "constraints", "Constraints :", "constraint:", "constraint :", "constraint", "Contraints :" }; int posin = 0, posoutput = 0, poscon = 0, idxin, idxout, idxcon, flaginput = 0, flagoutput = 0, flagcon = 0, inlen = 0, outlen = 0, conlen = 0; //find inputformat position,length of keyword for (idxin = 0; idxin < decideInput.length; idxin++) { if (StringUtils.containsIgnoreCase(problemIOC, decideInput[idxin])) { posin = problemIOC.toLowerCase().indexOf(decideInput[idxin].toLowerCase()); flaginput = 1; inlen = decideInput[idxin].length(); //decide it is keyowrd for actucal input or it is "sample input" if (StringUtils.containsIgnoreCase(problemIOC, "sample input")) { if (posin > problemIOC.toLowerCase().indexOf("sample input")) { flaginput = 0; inlen = 0; } else { break; } } else { break; } } } //find outputformat position,length of keyword for (idxout = 0; idxout < decideOutput.length; idxout++) { if (StringUtils.containsIgnoreCase(problemIOC, decideOutput[idxout])) { posoutput = problemIOC.toLowerCase().indexOf(decideOutput[idxout].toLowerCase()); flagoutput = 1; outlen = decideOutput[idxout].length(); break; } } //find constraint position,length of keyword for (idxcon = 0; idxcon < decideConstraint.length; idxcon++) { if (StringUtils.containsIgnoreCase(problemIOC, decideConstraint[idxcon])) { poscon = problemIOC.toLowerCase().indexOf(decideConstraint[idxcon].toLowerCase()); flagcon = 1; conlen = decideConstraint[idxcon].length(); break; } } System.out.println("input " + flaginput + " " + inlen + " " + posin); System.out.println("output " + flagoutput + " " + outlen + " " + posoutput); System.out.println("constraint " + flagcon + " " + conlen + " " + poscon); //retrieve problem input and output if present in problem page //if input format is present if (flaginput == 1) { //if input keyword is "input and output" and contraint is present in problem page if (idxin == 6 && flagcon == 1) { problemInput = problemIOC.substring(inlen, poscon); } //if input keyword is "input and output" and contraint is not present in problem page else if (idxin == 6 && flagcon == 0) { problemInput = problemIOC.substring(inlen); } //if output format and constraint is present else if (flagoutput == 1 && flagcon == 1) { //if constraint is present before input format if (poscon < posin) { problemInput = problemIOC.substring(posin + inlen, posoutput); problemOutput = problemIOC.substring(posoutput + outlen); } //if constraint is present before sample else if (poscon < posoutput) { problemInput = problemIOC.substring(inlen, poscon); problemOutput = problemIOC.substring(posoutput + outlen); } else { problemInput = problemIOC.substring(inlen, posoutput); problemOutput = problemIOC.substring(posoutput + outlen, poscon); } } //if constraint is not present else if (flagoutput == 1 && flagcon == 0) { problemInput = problemIOC.substring(inlen, posoutput); problemOutput = problemIOC.substring(posoutput + outlen); } else if (flagoutput == 0 && flagcon == 1) { if (poscon < posin) { problemInput = problemIOC.substring(posin + inlen); } else { problemInput = problemIOC.substring(poscon + conlen, posin); } problemOutput = ""; } else { problemInput = problemIOC.substring(inlen); problemOutput = ""; } } //if input format and output format is not present else { problemInput = ""; problemOutput = ""; } //if constraint is present if (flagcon == 1) { //if constraint is present before input format if (poscon < posin) { problemConstraints = problemIOC.substring(0, posin); } //if constraint is present before output format else if (poscon < posoutput) { problemConstraints = problemIOC.substring(poscon + conlen, posoutput); } else { problemConstraints = problemIOC.substring(poscon + conlen); } } System.out.println("problemInput :" + problemInput); System.out.println("problemOutput :" + problemOutput); System.out.println("problemConstraints :" + problemConstraints); //retrieve problem tags from problem page Element elementtag = doc.getElementsByClass("problem-tags").first().child(1); StringTokenizer st = new StringTokenizer(elementtag.text(), ","); while (st.hasMoreTokens()) { tags.add(st.nextToken().trim()); } //retrieve sample input sample output if present Element elementSIO = doc.getElementsByClass("input-output-container").first(); //if sample input output is present if (elementSIO != null) { //find position of sample output int soutpos = elementSIO.text().indexOf("SAMPLE OUTPUT"); sampleInput = elementSIO.text().substring(12, soutpos); sampleOutput = elementSIO.text().substring(soutpos + 13); System.out.println("Sample input :\n" + sampleInput + "\n\n\n"); System.out.println("Sample Output :\n" + sampleOutput); } else { sampleInput = ""; sampleOutput = ""; } //retrieve problem explanation from problem page if present Element elementExplanation = doc.getElementsByClass("standard-margin").first().child(0); if (elementExplanation.text().toLowerCase().contains("explanation")) { problemExplanation = elementExplanation.nextElementSibling().text(); } System.out.println("Explanation :" + problemExplanation); //retrieve timelimit Element elementTL = doc.getElementsByClass("problem-guidelines").first().child(0).child(1); StringTokenizer stTL = new StringTokenizer(elementTL.ownText(), " "); problemTimeLimit = Double.parseDouble(stTL.nextToken()); //System.out.println("problemTimeLimit :"+problemTimeLimit); //set all retrieved information to problem class problem.setProblemUrl(problemUrl); if (problemTitle.length() == 0) { problemTitle = null; } if (problemStatement.length() == 0) { problemStatement = null; } if (problemInput.length() == 0) { problemInput = null; } if (problemOutput.length() == 0) { problemOutput = null; } if (problemExplanation.length() == 0) { problemExplanation = null; } if (problemConstraints.length() == 0) { problemConstraints = null; } problem.setTitle(problemTitle); problem.setProblemUrl(problemUrl); problem.setProblemStatement(problemStatement); problem.setInputFormat(problemInput); problem.setOutputFormat(problemOutput); problem.setTimeLimit(problemTimeLimit); problem.setExplanation(problemExplanation); problem.setConstraints(problemConstraints); //set sample input output to problem class SampleInputOutput sampleInputOutput = new SampleInputOutput(problem, sampleInput, sampleOutput); problem.getSampleInputOutputs().add(sampleInputOutput); //set platform as hackerearth problem.setPlatform(Platform.HackerEarth); for (String strtag : tags) { problem.getTags().add(strtag); } //store in database Session session = null; Transaction transaction = null; try { //start session session = HibernateUtil.getSessionFactory().openSession(); transaction = session.beginTransaction(); //check if problem is already stored in database String hql = "FROM Problem p where p.problemUrl = :problem_url"; Problem oldProblem = (Problem) session.createQuery(hql).setString("problem_url", problemUrl) .uniqueResult(); String task; //if problem is present in database if (oldProblem != null) { //update the old problem task = "updated"; //retrieve id of old problem problem.setId(oldProblem.getId()); session.delete(oldProblem); session.flush(); session.save(problem); } else { task = "saved"; session.save(problem); } transaction.commit(); //log the info to console Logger.getLogger(CodeForcesCrawler.class.getName()).log(Level.INFO, "{0} {1}", new Object[] { task, problem.getProblemUrl() }); } catch (HibernateException ee) { if (transaction != null) { transaction.rollback(); } Logger.getLogger(CodeForcesCrawler.class.getName()).log(Level.SEVERE, "Cannot Insert/Update problem into databse: " + problemUrl, e); } finally { //close the session if (session != null) { session.close(); } } } catch (Exception ee) { System.out.println(ee.toString()); } } System.out.println("\n\n\n\ntutorial urls\n\n"); try { for (String tutorialurl : tutorialset) { //System.out.println(tutorialurl+"\n\n"); Response tutorialres = Jsoup.connect(tutorialurl).execute(); Document doc = tutorialres.parse(); Tutorial tutorial = new Tutorial(); tutorial.setContent(doc.getElementsByClass("tutorial").first().text()); tutorial.setName(baseUrl); tutorialurl = tutorialurl.substring(0, tutorialurl.length() - 10); StringTokenizer tutorialtok = new StringTokenizer(tutorialurl, "/"); String tempstr = ""; while (tutorialtok.hasMoreTokens()) { tempstr = tutorialtok.nextToken(); } Session session = null; Transaction transaction = null; try { //start session session = HibernateUtil.getSessionFactory().openSession(); transaction = session.beginTransaction(); //check if problem is already stored in database String hql = "FROM Tutorial p where p.name = :name"; Tutorial oldProblem = (Tutorial) session.createQuery(hql).setString("name", tempstr) .uniqueResult(); String task; //if problem is present in database if (oldProblem != null) { //update the old problem task = "updated"; //retrieve id of old problem tutorial.setName(oldProblem.getName()); session.delete(oldProblem); session.flush(); session.save(tutorial); } else { task = "saved"; tutorial.setName(tempstr); session.save(tutorial); } transaction.commit(); //log the info to console Logger.getLogger(CodeForcesCrawler.class.getName()).log(Level.INFO, "{0} {1}", new Object[] { task, tutorial.getName() }); } catch (HibernateException ee) { if (transaction != null) { transaction.rollback(); } Logger.getLogger(CodeForcesCrawler.class.getName()).log(Level.SEVERE, "Cannot Insert/Update problem into databse: " + tempstr, ee); } finally { //close the session if (session != null) { session.close(); } } } } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:eu.over9000.skadi.ui.MainWindow.java
private void updateFilterPredicate() { this.filteredChannelList.setPredicate(channel -> { boolean isOnlineResult; boolean containsTextResult; // isOnline returns a Boolean, can be null isOnlineResult = !this.onlineOnly.isSelected() || Boolean.TRUE.equals(channel.isOnline()); final String filter = this.filterText.getText().trim(); if (filter.isEmpty()) { containsTextResult = true;/*from w ww .j ava 2s .c o m*/ } else { final boolean nameContains = StringUtils.containsIgnoreCase(channel.getName(), filter); final boolean gameContains = StringUtils.containsIgnoreCase(channel.getGame(), filter); final boolean titleContains = StringUtils.containsIgnoreCase(channel.getTitle(), filter); containsTextResult = nameContains || gameContains || titleContains; } return isOnlineResult && containsTextResult; }); }
From source file:com.github.fengtan.sophie.tables.DocumentsTable.java
/** * Create the Table.//from w ww . j a v a2 s. co m */ private void createTable() { // Instantiate the table. int style = SWT.SINGLE | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION | SWT.HIDE_SELECTION | SWT.VIRTUAL; table = new Table(composite, style); // Set layout. GridData gridData = new GridData(GridData.FILL_BOTH); gridData.grabExcessVerticalSpace = true; table.setLayoutData(gridData); // Set styles. table.setLinesVisible(true); table.setHeaderVisible(true); // Add KeyListener to delete documents. table.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent event) { if (event.keyCode == SWT.DEL) { deleteSelectedDocument(); } } }); // Initialize item count to 1 so we can populate the first row with // filters. table.setItemCount(1); // Populate subsequent rows with remote documents (virtual table). table.addListener(SWT.SetData, new Listener() { @Override public void handleEvent(Event event) { TableItem item = (TableItem) event.item; int rowIndex = table.indexOf(item); // The first line is populated by filters. if (rowIndex == 0) { return; } SolrDocument document; // The last lines are populated by local additions. if (rowIndex >= table.getItemCount() - documentsAdded.size()) { document = documentsAdded.get(documentsAdded.size() - table.getItemCount() + rowIndex); item.setBackground(GREEN); } else { try { // rowIndex - 1 since the first line is used for // filters. document = getRemoteDocument(rowIndex - 1); } catch (SophieException e) { ExceptionDialog.open(composite.getShell(), new SophieException("Unable to populate table", e)); return; } } // First column is used to show the row ID. item.setText(0, Integer.toString(rowIndex)); // Subsequent columns are used to show field values. for (int index = 1; index < table.getColumnCount(); index++) { TableColumn column = table.getColumn(index); String fieldName = (String) column.getData("fieldName"); FieldInfo field = (FieldInfo) column.getData("field"); // If field is not stored, display message. if (!SolrUtils.getFlags(field).contains(FieldFlag.STORED)) { item.setText(index, LABEL_NOT_STORED); } else { Object value = document.getFieldValue(fieldName); item.setText(index, value == null ? StringUtils.EMPTY : value.toString()); } } // Store document in item. item.setData("document", document); } }); // Add doubleclick listener to edit values. table.addListener(SWT.MouseDoubleClick, new Listener() { public void handleEvent(Event event) { Point point = new Point(event.x, event.y); TableItem item = table.getItem(point); if (item == null) { return; } // The first row is used for filters. if (table.indexOf(item) == 0) { return; } // We add 1 since the first column is used for row ID's. for (int i = 1; i < table.getColumnCount(); i++) { Rectangle rect = item.getBounds(i); if (rect.contains(point)) { SolrDocument document = (SolrDocument) item.getData("document"); String fieldName = (String) table.getColumn(i).getData("fieldName"); FieldInfo field = (FieldInfo) table.getColumn(i).getData("field"); Object defaultValue = document.getFieldValue(fieldName); // Add editor dialog: // - list widget if we are dealing with a multi-valued // field. // - datepicker if we field type contains "date". // - text if we are dealing with any other field type. EditValueDialog dialog; if (SolrUtils.getFlags(field).contains(FieldFlag.MULTI_VALUED)) { dialog = new EditListValueDialog(composite.getShell(), (AbstractList<?>) defaultValue); } else if (StringUtils.containsIgnoreCase(field.getType(), "date")) { dialog = new EditDateValueDialog(composite.getShell(), (Date) defaultValue); } else { String oldValueString = Objects.toString(defaultValue, StringUtils.EMPTY); dialog = new EditTextValueDialog(composite.getShell(), oldValueString); } dialog.open(); if (dialog.getReturnCode() != IDialogConstants.OK_ID) { return; } Object value = dialog.getValue(); if (!Objects.equals(defaultValue, value)) { updateDocument(item, i, value); } } } } }); }