List of usage examples for java.lang StringBuilder indexOf
@Override public int indexOf(String str)
From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java
private void showAccessNotification(int uid) { String name = TextUtils.join(", ", Util.getApplicationNames(uid, ServiceSinkhole.this)); Intent main = new Intent(ServiceSinkhole.this, MainActivity.class); main.putExtra(MainActivity.EXTRA_SEARCH, Integer.toString(uid)); PendingIntent pi = PendingIntent.getActivity(ServiceSinkhole.this, uid + 10000, main, PendingIntent.FLAG_UPDATE_CURRENT); TypedValue tv = new TypedValue(); getTheme().resolveAttribute(R.attr.colorOn, tv, true); int colorOn = tv.data; getTheme().resolveAttribute(R.attr.colorOff, tv, true); int colorOff = tv.data; NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_cloud_upload_white_24dp).setGroup("AccessAttempt").setContentIntent(pi) .setColor(colorOff).setOngoing(false).setAutoCancel(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) builder.setContentTitle(name).setContentText(getString(R.string.msg_access_n)); else/*w ww . j a va 2s. co m*/ builder.setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.msg_access, name)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET); } DateFormat df = new SimpleDateFormat("dd HH:mm"); NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) notification.addLine(getString(R.string.msg_access_n)); else { String sname = getString(R.string.msg_access, name); int pos = sname.indexOf(name); Spannable sp = new SpannableString(sname); sp.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); notification.addLine(sp); } Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessUnset(uid, 7); int colDAddr = cursor.getColumnIndex("daddr"); int colTime = cursor.getColumnIndex("time"); int colAllowed = cursor.getColumnIndex("allowed"); while (cursor.moveToNext()) { StringBuilder sb = new StringBuilder(); sb.append(df.format(cursor.getLong(colTime))).append(' '); String daddr = cursor.getString(colDAddr); if (Util.isNumericAddress(daddr)) try { daddr = InetAddress.getByName(daddr).getHostName(); } catch (UnknownHostException ignored) { } sb.append(daddr); int allowed = cursor.getInt(colAllowed); if (allowed >= 0) { int pos = sb.indexOf(daddr); Spannable sp = new SpannableString(sb); ForegroundColorSpan fgsp = new ForegroundColorSpan(allowed > 0 ? colorOn : colorOff); sp.setSpan(fgsp, pos, pos + daddr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); notification.addLine(sp); } else notification.addLine(sb); } cursor.close(); NotificationManagerCompat.from(this).notify(uid + 10000, notification.build()); }
From source file:org.apache.accumulo.examples.wikisearch.parser.QueryEvaluator.java
public StringBuilder rewriteQuery(StringBuilder query, String fieldName, Collection<FieldValue> fieldValues) { if (log.isDebugEnabled()) { log.debug("rewriteQuery"); }//from w w w.j av a 2 s . c o m // Here we have a field that has multiple values. In this case we need to put // all values into the jexl context as an array and rewrite the query to account for all // of the fields. if (caseInsensitive) { fieldName = fieldName.toLowerCase(); } if (log.isDebugEnabled()) { log.debug("Modifying original query: " + query); } // Pull the values out of the FieldValue object String[] values = new String[fieldValues.size()]; int idx = 0; for (FieldValue fv : fieldValues) { if (caseInsensitive) { values[idx] = (new String(fv.getValue())).toLowerCase(); } else { values[idx] = new String(fv.getValue()); } idx++; } // Add the array to the context ctx.set(fieldName, values); Collection<QueryTerm> qt = terms.get(fieldName); // Add a script to the beginning of the query for this multi-valued field StringBuilder script = new StringBuilder(); script.append("_").append(fieldName).append(" = false;\n"); script.append("for (field : ").append(fieldName).append(") {\n"); for (QueryTerm t : qt) { if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) { script.append("\tif (_").append(fieldName).append(" == false && field ").append(t.getOperator()) .append(" ").append(t.getValue()).append(") { \n"); } else { script.append("\tif (_").append(fieldName).append(" == false && ") .append(t.getValue().toString().replace(fieldName, "field")).append(") { \n"); } script.append("\t\t_").append(fieldName).append(" = true;\n"); script.append("\t}\n"); } script.append("}\n"); // Add the script to the beginning of the query query.insert(0, script.toString()); StringBuilder newPredicate = new StringBuilder(); newPredicate.append("_").append(fieldName).append(" == true"); for (QueryTerm t : qt) { // Find the location of this term in the query StringBuilder predicate = new StringBuilder(); int start = 0; if (!t.getOperator().equals(JexlOperatorConstants.getOperator(ParserTreeConstants.JJTFUNCTIONNODE))) { predicate.append(fieldName).append(" ").append(t.getOperator()).append(" ").append(t.getValue()); start = query.indexOf(predicate.toString()); } else { predicate.append(t.getValue().toString()); // need to find the second occurence of the string. start = query.indexOf(predicate.toString()); } if (-1 == start) { log.warn("Unable to find predicate: " + predicate.toString() + " in rewritten query: " + query.toString()); } int length = predicate.length(); // Now modify the query to check the value of my.fieldName query.replace(start, start + length, newPredicate.toString()); } if (log.isDebugEnabled()) { log.debug("leaving rewriteQuery with: " + query.toString()); } return query; }
From source file:eu.faircode.netguard.ServiceSinkhole.java
private void showAccessNotification(int uid) { String name = TextUtils.join(", ", Util.getApplicationNames(uid, ServiceSinkhole.this)); Intent main = new Intent(ServiceSinkhole.this, ActivityMain.class); main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid)); PendingIntent pi = PendingIntent.getActivity(ServiceSinkhole.this, uid + 10000, main, PendingIntent.FLAG_UPDATE_CURRENT); TypedValue tv = new TypedValue(); getTheme().resolveAttribute(R.attr.colorOn, tv, true); int colorOn = tv.data; getTheme().resolveAttribute(R.attr.colorOff, tv, true); int colorOff = tv.data; NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_cloud_upload_white_24dp).setGroup("AccessAttempt").setContentIntent(pi) .setColor(colorOff).setOngoing(false).setAutoCancel(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) builder.setContentTitle(name).setContentText(getString(R.string.msg_access_n)); else/*from w ww . java2 s . com*/ builder.setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.msg_access, name)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder.setCategory(Notification.CATEGORY_STATUS).setVisibility(Notification.VISIBILITY_SECRET); } DateFormat df = new SimpleDateFormat("dd HH:mm"); NotificationCompat.InboxStyle notification = new NotificationCompat.InboxStyle(builder); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) notification.addLine(getString(R.string.msg_access_n)); else { String sname = getString(R.string.msg_access, name); int pos = sname.indexOf(name); Spannable sp = new SpannableString(sname); sp.setSpan(new StyleSpan(Typeface.BOLD), pos, pos + name.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); notification.addLine(sp); } Cursor cursor = DatabaseHelper.getInstance(ServiceSinkhole.this).getAccessUnset(uid, 7); int colDAddr = cursor.getColumnIndex("daddr"); int colTime = cursor.getColumnIndex("time"); int colAllowed = cursor.getColumnIndex("allowed"); while (cursor.moveToNext()) { StringBuilder sb = new StringBuilder(); sb.append(df.format(cursor.getLong(colTime))).append(' '); String daddr = cursor.getString(colDAddr); if (Util.isNumericAddress(daddr)) try { daddr = InetAddress.getByName(daddr).getHostName(); } catch (UnknownHostException ignored) { } sb.append(daddr); int allowed = cursor.getInt(colAllowed); if (allowed >= 0) { int pos = sb.indexOf(daddr); Spannable sp = new SpannableString(sb); ForegroundColorSpan fgsp = new ForegroundColorSpan(allowed > 0 ? colorOn : colorOff); sp.setSpan(fgsp, pos, pos + daddr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); notification.addLine(sp); } else notification.addLine(sb); } cursor.close(); NotificationManagerCompat.from(this).notify(uid + 10000, notification.build()); }
From source file:org.wso2.carbon.appmgt.hostobjects.APIProviderHostObject.java
private static void validateWsdl(String url) throws AppManagementException { try {/*w ww. j a va2 s.c o m*/ URL wsdl = new URL(url); BufferedReader in = new BufferedReader(new InputStreamReader(wsdl.openStream())); String inputLine; boolean isWsdl2 = false; boolean isWsdl10 = false; StringBuilder urlContent = new StringBuilder(); while ((inputLine = in.readLine()) != null) { String wsdl2NameSpace = "http://www.w3.org/ns/wsdl"; String wsdl10NameSpace = "http://schemas.xmlsoap.org/wsdl/"; urlContent.append(inputLine); isWsdl2 = urlContent.indexOf(wsdl2NameSpace) > 0; isWsdl10 = urlContent.indexOf(wsdl10NameSpace) > 0; } in.close(); if (isWsdl10) { javax.wsdl.xml.WSDLReader wsdlReader11 = javax.wsdl.factory.WSDLFactory.newInstance() .newWSDLReader(); wsdlReader11.readWSDL(url); } else if (isWsdl2) { WSDLReader wsdlReader20 = WSDLFactory.newInstance().newWSDLReader(); wsdlReader20.readWSDL(url); } else { handleException("URL is not in format of wsdl1/wsdl2"); } } catch (Exception e) { handleException("Error occurred while validating the Wsdl", e); } }
From source file:org.medici.bia.common.search.SimpleSearchDocument.java
/** * {@inheritDoc}/*from w w w . ja v a2 s .c om*/ */ @Override public String toJPAQuery() { StringBuilder jpaQuery = new StringBuilder("FROM Document "); if (!empty()) { //MD: We need to re-convert the alias text = text.replace("\\\"", "\""); String toSearch = text; List<String> exactWords = new ArrayList<String>(); //MD: This code is to identify the words between double quotes while (toSearch.contains("\"")) { //First double quote int from = toSearch.indexOf('\"'); //Second double quote int to = toSearch.indexOf('\"', from + 1); //If there is the second double quote or not if (to != -1) { //Add the exact words to the list and remove them from the string exactWords.add(toSearch.substring(from + 1, to)); toSearch = toSearch.substring(0, from) + toSearch.substring(to + 1, toSearch.length()); } else { toSearch = toSearch.replace("\"", " "); } } String[] words = StringUtils.split(toSearch, " "); if (words.length > 0 || exactWords.size() > 0) { jpaQuery.append(" WHERE "); } if (simpleSearchPerimeter.equals(SimpleSearchPerimeter.EXTRACT)) { for (int i = 0; i < exactWords.size(); i++) { jpaQuery.append("(synExtract.docExtract LIKE '% "); jpaQuery.append(exactWords.get(i).trim().replace("'", "''")); jpaQuery.append(" %')"); if (i < exactWords.size() - 1) { jpaQuery.append(" AND "); } } if (exactWords.size() > 0 && words.length > 0) { jpaQuery.append(" AND "); } for (int i = 0; i < words.length; i++) { jpaQuery.append("(synExtract.docExtract like '%"); jpaQuery.append(words[i].replace("'", "''")); jpaQuery.append("%')"); if (i < words.length - 1) { jpaQuery.append(" AND "); } } } else if (simpleSearchPerimeter.equals(SimpleSearchPerimeter.SYNOPSIS)) { for (int i = 0; i < exactWords.size(); i++) { jpaQuery.append("(synExtract.synopsis LIKE '% "); jpaQuery.append(exactWords.get(i).trim().replace("'", "''")); jpaQuery.append(" %')"); if (i < exactWords.size() - 1) { jpaQuery.append(" AND "); } } if (exactWords.size() > 0 && words.length > 0) { jpaQuery.append(" AND "); } for (int i = 0; i < words.length; i++) { jpaQuery.append("(synExtract.synopsis like '%"); jpaQuery.append(words[i].replace("'", "''")); jpaQuery.append("%')"); if (i < words.length - 1) { jpaQuery.append(" AND "); } } } //To discard record deleted if (jpaQuery.indexOf("WHERE") != -1) { jpaQuery.append(" AND logicalDelete = false"); } } else { jpaQuery.append(" WHERE logicalDelete = false"); } return jpaQuery.toString(); }
From source file:com.raweng.ChangeDocStateAction.java
public String execute() { StringBuilder errorInState = new StringBuilder(); StringBuilder nonExistingDocID = new StringBuilder(); StringBuilder successFulDocID = new StringBuilder(); StringBuilder alreadyInState = new StringBuilder(); DbDocumentManager dbDocumentManager = (DbDocumentManager) JiveApplication.getContext().getDocumentManager(); boolean update = request.getParameter("update") != null; Calendar modificationDate = Calendar.getInstance(); if (update && documentID != null && !documentID.trim().equals("")) { arrayDocumentID = commaSeparatedStringToLongArray(documentID); for (String docID : arrayDocumentID) { try { document = documentManager.getDocument(Long.valueOf(docID.trim())); newestDocVersion = document.getVersionManager().getNewestDocumentVersion(); if (documentState.equalsIgnoreCase(document.getDocumentState().toString())) { if (alreadyInState.length() > 0) { alreadyInState.append(", "); }//from www .j av a 2 s .com alreadyInState.append(document.getID()); } else if (documentState.equalsIgnoreCase(DocumentState.PUBLISHED.toString())) { //Change document state to PUBLISHED try { if (document.getDocumentState().equals(DocumentState.EXPIRED)) { utilitiesDao.publishExpiredDocument(expirationDate, modificationDate.getTimeInMillis(), document); } else { if (errorInState.length() > 0) { errorInState.append(", "); } errorInState.append(document.getID()); } log.info("Document state changed to PUBLISHED"); } catch (DataAccessException dae) { log.error(dae); } } else if (documentState.equalsIgnoreCase(DocumentState.EXPIRED.toString())) { //Change document state to EXPIRED try { Calendar expDate = Calendar.getInstance(); expDate.add(Calendar.DATE, -1); if (document.getDocumentState().equals(DocumentState.PUBLISHED)) { utilitiesDao.expiredPublishedDocument(expDate.getTimeInMillis(), document); log.info("Document state changed EXPIRED"); } else { if (errorInState.length() > 0) { errorInState.append(", "); } errorInState.append(document.getID()); } log.info("Document state changed to EXPIRED"); } catch (DataAccessException dae) { log.error(dae); } } //If there is no errorInState change then successFulDocID stringBuilder get updated if (errorInState.indexOf(String.valueOf(document.getID())) == -1 && alreadyInState.indexOf(String.valueOf(document.getID())) == -1) { if (successFulDocID.length() > 0) { successFulDocID.append(", "); } successFulDocID.append(document.getID()); dbDocumentManager.clearCaches(document); } } catch (DocumentObjectNotFoundException e) { if (docID != null || !docID.trim().equals("")) { if (nonExistingDocID.length() > 0) { nonExistingDocID.append(", "); } nonExistingDocID.append(docID.trim()); } log.info(e); } catch (Exception e) { error = true; log.info(e); e.printStackTrace(); return input(); } } if (successFulDocID.length() != 0) { successParameter = true; successfulDocIDString = successFulDocID.toString(); } if (nonExistingDocID.length() != 0) { addFieldError("ERROR_DOC_NOT_EXIST", "Document " + nonExistingDocID.toString() + " Dose not exist"); } if (alreadyInState.length() != 0) { addFieldError("ALREADY_IN_STATE", "Document ID " + alreadyInState.toString() + " already in " + documentState + " state"); } if (errorInState.length() != 0) { if (documentState.trim().equalsIgnoreCase(DocumentState.EXPIRED.toString())) addFieldError("ERROR_STATE", "Document " + errorInState.toString() + " is not in PUBLISHED state"); else if (documentState.trim().equalsIgnoreCase(DocumentState.PUBLISHED.toString())) addFieldError("ERROR_STATE", "Document/s " + errorInState.toString() + " is not in EXPIRED"); } return "success"; } else { if (update) { addFieldError("EMPTY", "Please Enter Document ID/s"); } return input(); } }
From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java
public ActionForward saveAndExit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("saveandexit"); HttpSession session = request.getSession(); String providerNo = getProviderNo(request); String demoNo = getDemographicNo(request); if (session.getAttribute("userrole") == null) return mapping.findForward("expired"); request.setAttribute("change_flag", "false"); CaseManagementEntryFormBean cform = (CaseManagementEntryFormBean) form; ActionMessages messages = new ActionMessages(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("note.saved")); saveMessages(request, messages);/* w w w. j a va 2 s .com*/ long noteId = noteSave(cform, request); if (noteId == -1) { return mapping.findForward("windowClose"); } cform.setMethod("view"); String error = (String) request.getAttribute("DateError"); if (error != null) { String varName = "newNote"; session.setAttribute(varName, false); varName = "saveNote" + demoNo; session.setAttribute(varName, new Boolean(true)); // tell CaseManagementView we have just saved note ActionForward fwd = mapping.findForward("list"); StringBuilder path = new StringBuilder(fwd.getPath()); if (path.indexOf("?") == -1) path.append("?"); else path.append("&"); path.append("DateError=" + error); ActionForward forward = new ActionForward(); forward.setPath(path.toString()); return forward; } String toBill = request.getParameter("toBill"); if (toBill != null && toBill.equalsIgnoreCase("true")) { String region = cform.getBillRegion(); String appointmentNo = cform.getAppointmentNo(); String name = this.getDemoName(demoNo); String date = cform.getAppointmentDate(); String start_time = cform.getStart_time(); String apptProvider = cform.getApptProvider(); String providerview = cform.getProviderview(); String defaultView = oscar.OscarProperties.getInstance().getProperty("default_view", ""); Set setIssues = cform.getCaseNote().getIssues(); Iterator iter = setIssues.iterator(); StringBuilder dxCodes = new StringBuilder(); String strDxCode; int dxNum = 0; while (iter.hasNext()) { CaseManagementIssue cIssue = (CaseManagementIssue) iter.next(); dxCodes.append("&dxCode"); strDxCode = String.valueOf(cIssue.getIssue().getCode()); if (strDxCode.length() > 3) { strDxCode = strDxCode.substring(0, 3); } if (dxNum > 0) { dxCodes.append(String.valueOf(dxNum)); } dxCodes.append("=" + strDxCode); ++dxNum; } String url = "/billing.do?billRegion=" + region + "&billForm=" + defaultView + "&hotclick=&appointment_no=" + appointmentNo + "&demographic_name=" + java.net.URLEncoder.encode(name, "utf-8") + "&status=t&demographic_no=" + demoNo + "&providerview=" + providerview + "&user_no=" + providerNo + "&apptProvider_no=" + apptProvider + "&appointment_date=" + date + "&start_time=" + start_time + "&bNewForm=1" + dxCodes.toString(); logger.debug("BILLING URL " + url); ActionForward forward = new ActionForward(); forward.setPath(url); return forward; } String chain = request.getParameter("chain"); SurveillanceMaster sMaster = SurveillanceMaster.getInstance(); if (!SurveillanceMaster.surveysEmpty()) { request.setAttribute("demoNo", demoNo); if (chain != null && !chain.equals("")) { request.setAttribute("proceedURL", chain); } logger.debug("sending to surveillance"); return mapping.findForward("surveillance"); } if (chain != null && !chain.equals("")) { ActionForward fwd = new ActionForward(); fwd.setPath(chain); return fwd; } return mapping.findForward("windowClose"); }
From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java
public ActionForward save(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); if (session == null || session.getAttribute("userrole") == null) return mapping.findForward("expired"); // String providerNo = getProviderNo(request); CaseManagementEntryFormBean cform = (CaseManagementEntryFormBean) form; request.setAttribute("change_flag", "false"); String demono = getDemographicNo(request); request.setAttribute("demoName", getDemoName(demono)); request.setAttribute("demoAge", getDemoAge(demono)); request.setAttribute("demoDOB", getDemoDOB(demono)); request.setAttribute("from", request.getParameter("from")); long noteId = noteSave(cform, request); /*//ww w . j av a 2s . com * CaseManagementNote preNote=new CaseManagementNote(); if(cform.getNoteId()!=null) { Long nId=Long.parseLong(cform.getNoteId()); preNote.setId(nId); } */ /* prepare the message */ ActionMessages messages = new ActionMessages(); messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("note.saved")); saveMessages(request, messages); // are we in the new encounter and chaining actions? String chain = request.getParameter("chain"); if (chain != null && !chain.equals("")) { String varName = "newNote"; session.setAttribute(varName, false); varName = "saveNote" + demono; session.setAttribute(varName, new Boolean(true)); // tell CaseManagementView we have just saved note ActionForward fwd = mapping.findForward(chain); StringBuilder path = new StringBuilder(fwd.getPath()); ResourceBundle props = ResourceBundle.getBundle("oscarResources"); if (request.getAttribute("DateError") != null) { if (path.indexOf("?") == -1) path.append("?"); else path.append("&"); path.append("DateError=" + props.getString("oscarEncounter.futureDate.Msg")); } ActionForward forward = new ActionForward(); forward.setPath(path.toString()); return forward; } // this.caseManagementMgr.saveNote(); return mapping.findForward("view"); }
From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java
public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { logger.debug("Edit Starts"); long start = System.currentTimeMillis(); long beginning = start; long current = 0; HttpSession session = request.getSession(); if (session.getAttribute("userrole") == null) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return null; }//from www .j a v a 2 s . c o m CaseManagementEntryFormBean cform = (CaseManagementEntryFormBean) form; cform.setChain(""); request.setAttribute("change_flag", "false"); request.setAttribute("from", "casemgmt"); logger.debug("Get demo and provider no"); String demono = getDemographicNo(request); Integer demographicNo = ConversionUtils.fromIntString(demono); String providerNo = getProviderNo(request); current = System.currentTimeMillis(); logger.debug("Get demo and provider no " + String.valueOf(current - start)); start = current; String programIdString = (String) session.getAttribute("case_program_id"); Integer programId = null; try { programId = ConversionUtils.fromIntString(programIdString); } catch (Exception e) { logger.warn("Error parsing programId:" + programIdString, e); } request.setAttribute("demoName", getDemoName(demono)); request.setAttribute("demoAge", getDemoAge(demono)); request.setAttribute("demoDOB", getDemoDOB(demono)); /* process the request from other module */ if (!"casemgmt".equalsIgnoreCase(request.getParameter("from"))) { // no demographic number, no page if (request.getParameter("demographicNo") == null || "".equals(request.getParameter("demographicNo"))) { return mapping.findForward("NoDemoERR"); } request.setAttribute("from", ""); } /* prepare url for billing */ if (request.getParameter("from") != null) { request.setAttribute("from", request.getParameter("from")); } String url = ""; if ("casemgmt".equals(request.getAttribute("from"))) { String ss = (String) session.getAttribute("casemgmt_VlCountry"); String province = OscarProperties.getInstance().getProperty("billregion", "").trim().toUpperCase(); String strBeanName = "casemgmt_oscar_bean" + demono; EctSessionBean bean = (EctSessionBean) session.getAttribute(strBeanName); if (bean.appointmentNo == null) { bean.appointmentNo = "0"; } String bsurl = (String) session.getAttribute("casemgmt_oscar_baseurl"); Date today = new Date(); Calendar todayCal = Calendar.getInstance(); todayCal.setTime(today); String Hour = Integer.toString(todayCal.get(Calendar.HOUR)); String Min = Integer.toString(todayCal.get(Calendar.MINUTE)); if ("BR".equals(ss)) { url = bsurl + "/oscar/billing/procedimentoRealizado/init.do?appId=" + bean.appointmentNo; } else { // StringEncoderUtils.a(); String default_view = OscarProperties.getInstance().getProperty("default_view", ""); url = bsurl + "/billing.do?billRegion=" + java.net.URLEncoder.encode(province, "UTF-8") + "&billForm=" + java.net.URLEncoder.encode(default_view, "UTF-8") + "&hotclick=" + java.net.URLEncoder.encode("", "UTF-8") + "&appointment_no=" + bean.appointmentNo + "&appointment_date=" + bean.appointmentDate + "&start_time=" + Hour + ":" + Min + "&demographic_name=" + java.net.URLEncoder.encode(bean.patientLastName + "," + bean.patientFirstName, "UTF-8") + "&demographic_no=" + bean.demographicNo + "&providerview=" + bean.curProviderNo + "&user_no=" + bean.providerNo + "&apptProvider_no=" + bean.curProviderNo + "&bNewForm=1&status=t"; } session.setAttribute("billing_url", url); } /* remove the remembered echart string */ session.removeAttribute("lastSavedNoteString"); logger.debug("Get Issues and filter them"); current = System.currentTimeMillis(); logger.debug("Get Issues and filter them " + String.valueOf(current - start)); start = current; cform.setDemoNo(demono); CaseManagementNote note = null; String nId = request.getParameter("noteId"); String forceNote = request.getParameter("forceNote"); if (forceNote == null) forceNote = "false"; logger.debug("NoteId " + nId); String maxTmpSave = oscar.OscarProperties.getInstance().getProperty("maxTmpSave", ""); logger.debug("maxTmpSave " + maxTmpSave); // set date 2 weeks in past so we retrieve more recent saved notes Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_MONTH, -14); Date twoWeeksAgo = cal.getTime(); logger.debug("Get tmp note"); CaseManagementTmpSave tmpsavenote; if (maxTmpSave.equalsIgnoreCase("off")) { tmpsavenote = this.caseManagementMgr.restoreTmpSave(providerNo, demono, programIdString); } else { tmpsavenote = this.caseManagementMgr.restoreTmpSave(providerNo, demono, programIdString, twoWeeksAgo); } current = System.currentTimeMillis(); logger.debug("Get tmp note " + String.valueOf(current - start)); start = current; logger.debug("Get Note for editing"); // create a new note if (request.getParameter("note_edit") != null && request.getParameter("note_edit").equals("new")) { logger.debug("NEW NOTE GENERATED"); session.setAttribute("newNote", "true"); session.setAttribute("issueStatusChanged", "false"); request.setAttribute("newNoteIdx", request.getParameter("newNoteIdx")); note = new CaseManagementNote(); note.setProviderNo(providerNo); Provider prov = new Provider(); prov.setProviderNo(providerNo); note.setProvider(prov); note.setDemographic_no(demono); if (!OscarProperties.getInstance().isPropertyActive("encounter.empty_new_note")) { this.insertReason(request, note); } else { note.setNote(""); note.setEncounter_type(""); } String strBeanName = "casemgmt_oscar_bean" + demono; EctSessionBean bean = (EctSessionBean) session.getAttribute(strBeanName); String encType = request.getParameter("encType"); if (encType == null || encType.equals("")) { note.setEncounter_type(""); } else { note.setEncounter_type(encType); } if (bean.encType != null && bean.encType.length() > 0) { note.setEncounter_type(bean.encType); } resetTemp(providerNo, demono, programIdString); } // get the last temp note? else if (tmpsavenote != null && !forceNote.equals("true")) { logger.debug("tempsavenote is NOT NULL"); if (tmpsavenote.getNote_id() > 0) { session.setAttribute("newNote", "false"); request.setAttribute("noteId", String.valueOf(tmpsavenote.getNote_id())); note = caseManagementMgr.getNote(String.valueOf(tmpsavenote.getNote_id())); logger.debug("Restoring " + String.valueOf(note.getId())); } else { session.setAttribute("newNote", "true"); session.setAttribute("issueStatusChanged", "false"); note = new CaseManagementNote(); note.setProviderNo(providerNo); Provider prov = new Provider(); prov.setProviderNo(providerNo); note.setProvider(prov); note.setDemographic_no(demono); } note.setNote(tmpsavenote.getNote()); } // get an existing non-temp note? else if (nId != null && ConversionUtils.fromIntString(nId) > 0) { logger.debug("Using nId " + nId + " to fetch note"); session.setAttribute("newNote", "false"); note = caseManagementMgr.getNote(nId); if (note.getHistory() == null || note.getHistory().equals("")) { // old note - we need to save the original in here note.setHistory(note.getNote()); caseManagementMgr.saveNoteSimple(note); addNewNoteLink(Long.parseLong(nId)); } } // no note specified, get last unsigned else { // A hack to load last unsigned note when not specifying a particular note to edit // if there is no unsigned note load a new one if ((note = getLastSaved(request, demono, providerNo)) == null) { session.setAttribute("newNote", "true"); session.setAttribute("issueStatusChanged", "false"); note = new CaseManagementNote(); note.setProviderNo(providerNo); Provider prov = new Provider(); prov.setProviderNo(providerNo); note.setProvider(prov); note.setDemographic_no(demono); if (!OscarProperties.getInstance().isPropertyActive("encounter.empty_new_note")) { this.insertReason(request, note); } else { note.setNote(""); note.setEncounter_type(""); } String strBeanName = "casemgmt_oscar_bean" + demono; EctSessionBean bean = (EctSessionBean) session.getAttribute(strBeanName); String encType = request.getParameter("encType"); if (encType == null || encType.equals("")) { note.setEncounter_type(""); } else { note.setEncounter_type(encType); } if (bean.encType != null && bean.encType.length() > 0) { note.setEncounter_type(bean.encType); } } } current = System.currentTimeMillis(); logger.debug("Get note to edit " + String.valueOf(current - start)); start = current; /* * do the restore if(restore != null && restore.booleanValue() == true) { String tmpsavenote = this.caseManagementMgr.restoreTmpSave(providerNo,demono,programId); if(tmpsavenote != null) { note.setNote(tmpsavenote); } } */ logger.debug("Set Encounter Type: " + note.getEncounter_type()); logger.debug("Fetched Note " + String.valueOf(note.getId())); logger.debug("Populate Note with editors"); this.caseManagementMgr.getEditors(note); current = System.currentTimeMillis(); logger.debug("Populate Note with editors " + String.valueOf(current - start)); start = current; // put the new/retrieved not in the form object for rendering on page cform.setCaseNote(note); /* set issue checked list */ // get issues for current demographic, based on provider rights Boolean useNewCaseMgmt = new Boolean((String) session.getAttribute("newCaseManagement")); CheckBoxBean[] checkedList = null; if (useNewCaseMgmt) { CaseManagementViewAction caseManagementViewAction = new CaseManagementViewAction(); ArrayList<CheckBoxBean> checkBoxBeanList = new ArrayList<CheckBoxBean>(); caseManagementViewAction.addLocalIssues(checkBoxBeanList, demographicNo, false, programId); caseManagementViewAction.addRemoteIssues(checkBoxBeanList, demographicNo, false); caseManagementViewAction.sortIssuesByOrderId(checkBoxBeanList); checkedList = checkBoxBeanList.toArray(new CheckBoxBean[checkBoxBeanList.size()]); /* * List<CaseManagementIssue> issues = caseManagementMgr.filterIssues(caseManagementMgr.getIssues(ConversionUtils.fromIntString(demono)), programIdString); checkedList = new CheckBoxBean[issues.size()]; // set issue checked list * log.debug("Set Checked Issues " + String.valueOf(current-start)); List allNotes = this.caseManagementMgr.getNotes(demono); for (int i = 0; i < issues.size(); i++) { checkedList[i] = new CheckBoxBean(); CaseManagementIssue iss = * issues.get(i); checkedList[i].setIssue(iss); checkedList[i].setUsed(haveIssue(iss.getId(), allNotes)); current = System.currentTimeMillis(); log.debug("Set Checked Issues " + String.valueOf(current-start)); start = current; } */ Iterator itr = note.getIssues().iterator(); while (itr.hasNext()) { int id = ((CaseManagementIssue) itr.next()).getId().intValue(); SetChecked(checkedList, id); } } else // old CME { CaseManagementViewAction caseManagementViewAction = new CaseManagementViewAction(); ArrayList<CheckBoxBean> checkBoxBeanList = new ArrayList<CheckBoxBean>(); caseManagementViewAction.addLocalIssues(checkBoxBeanList, demographicNo, false, programId); caseManagementViewAction.addRemoteIssues(checkBoxBeanList, demographicNo, false); caseManagementViewAction.addGroupIssues(checkBoxBeanList, demographicNo, false); checkedList = checkBoxBeanList.toArray(new CheckBoxBean[0]); for (CaseManagementIssue cmi : note.getIssues()) { setChecked_oldCme(checkedList, cmi); } } current = System.currentTimeMillis(); cform.setIssueCheckList(checkedList); cform.setSign("off"); if (!note.isIncludeissue()) cform.setIncludeIssue("off"); else cform.setIncludeIssue("on"); boolean passwd = caseManagementMgr.getEnabled(); String chain = request.getParameter("chain"); current = System.currentTimeMillis(); logger.debug("The End of Edit " + String.valueOf(current - beginning)); start = current; LogAction.addLog((String) session.getAttribute("user"), LogConst.EDIT, LogConst.CON_CME_NOTE, String.valueOf(note.getId()), request.getRemoteAddr(), demono, note.getAuditString()); String frmName = "caseManagementEntryForm" + demono; logger.debug("Setting session form - " + frmName + " - " + String.valueOf(cform != null)); session.setAttribute(frmName, cform); ActionForward fwd, finalFwd = null; if (chain != null && chain.length() > 0) { session.setAttribute("passwordEnabled", passwd); fwd = mapping.findForward(chain); } else { request.setAttribute("passwordEnabled", passwd); String ajax = request.getParameter("ajax"); if (ajax != null && ajax.equalsIgnoreCase("true")) { fwd = mapping.findForward("issueList_ajax"); } else { fwd = mapping.findForward("view"); } } if (fwd != null) { StringBuilder path = new StringBuilder(fwd.getPath()); if (path.indexOf("?") == -1) path.append("?"); else path.append("&"); path.append("demographicNo=" + demono); String noteBody = request.getParameter("noteBody"); if (noteBody != null) path.append("¬eBody=" + noteBody); finalFwd = new ActionForward(path.toString()); } return finalFwd; }
From source file:org.mifosplatform.infrastructure.dataqueries.service.ReadWriteNonCoreDataServiceImpl.java
@Transactional @Override/*from w ww .j a va 2 s . c o m*/ public void updateDatatable(final String datatableName, final JsonCommand command) { try { this.context.authenticatedUser(); this.fromApiJsonDeserializer.validateForUpdate(command.json()); final JsonElement element = this.fromJsonHelper.parse(command.json()); final JsonArray changeColumns = this.fromJsonHelper.extractJsonArrayNamed("changeColumns", element); final JsonArray addColumns = this.fromJsonHelper.extractJsonArrayNamed("addColumns", element); final JsonArray dropColumns = this.fromJsonHelper.extractJsonArrayNamed("dropColumns", element); final String apptableName = this.fromJsonHelper.extractStringNamed("apptableName", element); validateDatatableName(datatableName); final List<ResultsetColumnHeaderData> columnHeaderData = this.genericDataService .fillResultsetColumnHeaders(datatableName); final Map<String, ResultsetColumnHeaderData> mapColumnNameDefinition = new HashMap<String, ResultsetColumnHeaderData>(); for (final ResultsetColumnHeaderData columnHeader : columnHeaderData) { mapColumnNameDefinition.put(columnHeader.getColumnName(), columnHeader); } final boolean isConstraintApproach = this.configurationDomainService .isConstraintApproachEnabledForDatatables(); if (!StringUtils.isBlank(apptableName)) { validateAppTable(apptableName); final String oldApptableName = queryForApplicationTableName(datatableName); if (!StringUtils.equals(oldApptableName, apptableName)) { final String oldFKName = oldApptableName.substring(2) + "_id"; final String newFKName = apptableName.substring(2) + "_id"; final String actualAppTableName = mapToActualAppTable(apptableName); final String oldConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + oldFKName; final String newConstraintName = datatableName.toLowerCase().replaceAll("\\s", "_") + "_" + newFKName; StringBuilder sqlBuilder = new StringBuilder(); if (mapColumnNameDefinition.containsKey("id")) { sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ") .append("DROP KEY `fk_" + oldFKName + "`,") .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,") .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName + "` BIGINT(20) NOT NULL,") .append("ADD KEY `fk_" + newFKName + "` (`" + newFKName + "`),") .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ") .append("FOREIGN KEY (`" + newFKName + "`) ") .append("REFERENCES `" + actualAppTableName + "` (`id`)"); } else { sqlBuilder = sqlBuilder.append("ALTER TABLE `" + datatableName + "` ") .append("DROP FOREIGN KEY `fk_" + oldConstraintName + "`,") .append("CHANGE COLUMN `" + oldFKName + "` `" + newFKName + "` BIGINT(20) NOT NULL,") .append("ADD CONSTRAINT `fk_" + newConstraintName + "` ") .append("FOREIGN KEY (`" + newFKName + "`) ") .append("REFERENCES `" + actualAppTableName + "` (`id`)"); } this.jdbcTemplate.execute(sqlBuilder.toString()); deregisterDatatable(datatableName); registerDatatable(datatableName, apptableName); } } if (changeColumns == null && addColumns == null && dropColumns == null) { return; } if (dropColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final List<String> codeMappings = new ArrayList<String>(); for (final JsonElement column : dropColumns) { parseDatatableColumnForDrop(column.getAsJsonObject(), sqlBuilder, datatableName, constrainBuilder, codeMappings); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(codeMappings); } if (addColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final Map<String, Long> codeMappings = new HashMap<String, Long>(); for (final JsonElement column : addColumns) { parseDatatableColumnForAdd(column.getAsJsonObject(), sqlBuilder, datatableName.toLowerCase().replaceAll("\\s", "_"), constrainBuilder, codeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); this.jdbcTemplate.execute(sqlBuilder.toString()); registerColumnCodeMapping(codeMappings); } if (changeColumns != null) { StringBuilder sqlBuilder = new StringBuilder("ALTER TABLE `" + datatableName + "`"); final StringBuilder constrainBuilder = new StringBuilder(); final Map<String, Long> codeMappings = new HashMap<String, Long>(); final List<String> removeMappings = new ArrayList<String>(); for (final JsonElement column : changeColumns) { parseDatatableColumnForUpdate(column.getAsJsonObject(), mapColumnNameDefinition, sqlBuilder, datatableName, constrainBuilder, codeMappings, removeMappings, isConstraintApproach); } // Remove the first comma, right after ALTER TABLE `datatable` final int indexOfFirstComma = sqlBuilder.indexOf(","); if (indexOfFirstComma != -1) { sqlBuilder = sqlBuilder.deleteCharAt(indexOfFirstComma); } sqlBuilder.append(constrainBuilder); try { this.jdbcTemplate.execute(sqlBuilder.toString()); deleteColumnCodeMapping(removeMappings); registerColumnCodeMapping(codeMappings); } catch (final GenericJDBCException e) { if (e.getMessage().contains("Error on rename")) { throw new PlatformServiceUnavailableException( "error.msg.datatable.column.update.not.allowed", "One of the column name modification not allowed"); } } } } catch (final SQLGrammarException e) { final Throwable realCause = e.getCause(); final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>(); final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors) .resource("datatable"); if (realCause.getMessage().toLowerCase().contains("unknown column")) { baseDataValidator.reset().parameter("name").failWithCode("does.not.exist"); } else if (realCause.getMessage().toLowerCase().contains("can't drop")) { baseDataValidator.reset().parameter("name").failWithCode("does.not.exist"); } else if (realCause.getMessage().toLowerCase().contains("duplicate column")) { baseDataValidator.reset().parameter("name").failWithCode("column.already.exists"); } throwExceptionIfValidationWarningsExist(dataValidationErrors); } }