text
stringlengths
10
2.72M
package com.zjf.myself.codebase.activity.ExerciseLibrary; import android.os.Bundle; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; import com.zjf.myself.codebase.view.test.CustomView; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * <pre> * author : ZouJianFeng * e-mail : 1434690833@qq.com * time : 2017/10/14 * desc : * version: 1.0 * </pre> */ public class CustomViewAct extends BaseAct { @Bind(R.id.customView) CustomView customView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.win_custom_view); } }
package com.cts.airline.reservation.entities; import java.util.Set; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) int id; String userName; String Password; String firstName; String lastName; String phoneNo; String emailId; @ManyToMany(fetch = FetchType.EAGER) Set<Role> roles; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPhoneNo() { return phoneNo; } public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } }
package com.fanfte.designPattern.decorator; public interface IPackeetCreator { String handleContent(); }
package com.bupsolutions.polaritydetection.nlp; import opennlp.tools.ngram.NGramGenerator; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class NGramExtractor { private static final String SEPARATOR = " "; public List<String> ngrams(List<String> tokens, int n) { return NGramGenerator.generate(tokens, n, SEPARATOR); } public List<List<String>> mapNGrams(List<List<String>> sentences, int n) { return sentences.stream().map(sentence -> ngrams(sentence, n) ).collect(Collectors.toList()); } public List<String> flatMapNGrams(List<List<String>> sentences, int n) { return mapNGrams(sentences, n).stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } }
package be.mxs.common.util.system; import be.dpms.medwan.common.model.vo.authentication.UserVO; import be.dpms.medwan.common.model.vo.occupationalmedicine.ExaminationVO; import be.dpms.medwan.webapp.wo.common.system.SessionContainerWO; import be.mxs.common.model.vo.healthrecord.ItemVO; import be.mxs.common.model.vo.healthrecord.TransactionVO; import be.mxs.common.util.db.MedwanQuery; import be.mxs.webapp.wl.exceptions.SessionContainerFactoryException; import be.mxs.webapp.wl.session.SessionContainerFactory; import be.openclinic.adt.Encounter; import be.openclinic.common.OC_Object; import be.openclinic.finance.Balance; import be.openclinic.finance.Insurance; import be.openclinic.finance.Prestation; import be.openclinic.system.Application; import be.openclinic.system.SH; import net.admin.*; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.PageContext; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.sql.*; import java.sql.Date; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import java.util.zip.Inflater; import java.util.zip.InflaterOutputStream; public class ScreenHelper { public static SimpleDateFormat hourFormat, stdDateFormat, fullDateFormat, fullDateFormatSS,timestampFormat=new SimpleDateFormat("yyyyMMddHHmmssSSS"); public static SimpleDateFormat euDateFormat = new SimpleDateFormat(MedwanQuery.getInstance(false).getConfigString("euDateFormat","dd/MM/yyyy")); // used when storing dates in DB public static String ITEM_PREFIX = "be.mxs.common.model.vo.healthrecord.IConstants."; static{ reloadDateFormats(); } public static void setSync(String name, String id) { Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); try { PreparedStatement ps = conn.prepareStatement("select * from oc_sync where type=? and oldid=? and processed is null"); ps.setString(1, name); ps.setString(2, id); ResultSet rs = ps.executeQuery(); if(!rs.next()) { rs.close(); ps.close(); ps = conn.prepareStatement("insert into oc_sync(type,oldid,created) values(?,?,?)"); ps.setString(1, name); ps.setString(2, id); ps.setTimestamp(3, getSQLTime()); ps.execute(); } rs.close(); ps.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } public static boolean getSyncOpen(String name, String id) { boolean bOpen=false; Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); try { PreparedStatement ps = conn.prepareStatement("select * from oc_sync where type=? and oldid=? and processed is null"); ps.setString(1, name); ps.setString(2, id); ResultSet rs = ps.executeQuery(); if(rs.next()) { bOpen=true; } rs.close(); ps.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } return bOpen; } public static void updateSync(String name, String oldid, String newid) { Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); try { PreparedStatement ps = conn.prepareStatement("update oc_sync set newid=?,processed=? where type=? and oldid=? and processed is null"); ps.setString(1, newid); ps.setTimestamp(2, getSQLTime()); ps.setString(3, name); ps.setString(4, oldid); ps.execute(); ps.close(); conn.close(); MedwanQuery.getInstance().getObjectCache().removeObject(name, oldid); } catch (Exception e) { e.printStackTrace(); } } public static long getTimeSecond() { return 1000; } public static long getTimeMinute() { return 60*getTimeSecond(); } public static long getTimeHour() { return 60*getTimeMinute(); } public static long getTimeDay() { return 24*getTimeHour(); } public static long getTimeYear() { return 365*getTimeDay(); } public static boolean isValidEmailAddress(String email) { boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; } public static String getClientIpAddress(HttpServletRequest request) { return getRemoteAddr(request); } public static long nightsBetween(java.util.Date begin,java.util.Date end){ long nights = 0; if(!formatDate(begin).equals(formatDate(end)) && end.after(begin)){ nights=TimeUnit.DAYS.convert(end.getTime()-begin.getTime(), TimeUnit.MILLISECONDS); } return nights; } public static java.util.Date getPreviousMonthBegin(){ return getPreviousMonthBegin(new java.util.Date()); } public static java.util.Date getPreviousMonthBegin(java.util.Date date){ try{ String firstdayPreviousMonth="01/"+new SimpleDateFormat("MM/yyyy").format(new java.util.Date(ScreenHelper.parseDate("01/"+new SimpleDateFormat("MM/yyyy").format(date)).getTime()-100)); return new SimpleDateFormat("dd/MM/yyyy").parse(firstdayPreviousMonth); } catch(Exception e){ return null; } } public static java.util.Date getPreviousMonthEnd(){ return getPreviousMonthEnd(new java.util.Date()); } public static java.util.Date getPreviousMonthEnd(java.util.Date date){ try{ String lastdayPreviousMonth=ScreenHelper.stdDateFormat.format(new java.util.Date(ScreenHelper.parseDate("01/"+new SimpleDateFormat("MM/yyyy").format(date)).getTime()-100)); return new SimpleDateFormat("dd/MM/yyyy").parse(lastdayPreviousMonth); } catch(Exception e){ return null; } } public static boolean isAcceptableUploadFileExtension(String sFileName) { String[] forbiddenExtensions = MedwanQuery.getInstance().getConfigString("forbiddentUploadFileExtensions",".html,.jsp,.htm,.js,.do").split(","); for(int n=0;n<forbiddenExtensions.length;n++) { if(sFileName.toLowerCase().endsWith(forbiddenExtensions[n].toLowerCase())) { return false; } } return true; } public static Connection getOpenclinicConnection() { return MedwanQuery.getInstance().getOpenclinicConnection(); } public static Connection getAdminConnection() { return MedwanQuery.getInstance().getAdminConnection(); } public static int addHashCounter(Hashtable h,String key, int value) { if(h.get(key)==null) { h.put(key, 0); } h.put(key, (Integer)h.get(key)+value); return (Integer)h.get(key); } public static String getRemoteAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } public static String createDrawingDiv(HttpServletRequest request,String name, String itemtype, Object transaction,String image){ String sContextPath=request.getRequestURI().replaceAll(request.getServletPath(),""); TransactionVO tran = (TransactionVO)transaction; String s = "<script src='"+sContextPath+"/_common/_script/canvas.js'></script>"; s+="<table cellspacing='0' cellpadding='0'>"; s+="<tr><td>"; s+="<img src='"+sContextPath+"/_img/themes/default/canvas_small.png' width='14px' onclick='canvasSetRadius(1)'/>"; s+="<img src='"+sContextPath+"/_img/themes/default/canvas_normal.png' width='14px' onclick='canvasSetRadius(5)'/>"; s+="<img src='"+sContextPath+"/_img/themes/default/canvas_big.png' width='14px' onclick='canvasSetRadius(10)'/>"; s+="</td><td>"; s+="<img src='"+sContextPath+"/_img/themes/default/previous.jpg' width='14px' onclick='canvasReloadBaseImage()'/>"; s+="<img src='"+sContextPath+"/_img/themes/default/erase.png' width='14px' onclick='canvasLoadImage(\""+sContextPath+image+"\")'/>"; s+="</td><td/></tr><tr><td colspan='2'>"; s+="<div id='"+name+"' onmouseover='this.style.cursor=\"hand\"'></div>"; s+="</td><td valign='top'><table cellspacing='0' cellpadding='0'>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_black.png' width='14px' onclick='canvasSetColor(\"black\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_white.png' width='14px' onclick='canvasSetColor(\"white\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_red.png' width='14px' onclick='canvasSetColor(\"red\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_blue.png' width='14px' onclick='canvasSetColor(\"blue\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_yellow.png' width='14px' onclick='canvasSetColor(\"yellow\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_green.png' width='14px' onclick='canvasSetColor(\"green\")'/></td></tr>"; s+="</table></td></tr></table>"; s+="<input type='hidden' name='drawingContent' id='drawingContent'/>"; s+="<input type='hidden' name='currentTransactionVO.items.<ItemVO[hashCode="+tran.getItem(itemtype).hashCode()+"]>.value' value='drawingContent'/>"; s+="<script>"; String sDrawing=ScreenHelper.getDrawing(tran.getServerId(),tran.getTransactionId(),itemtype); if(sDrawing.length()<10){ s+="context = initCanvas('"+name+"',100,100,'"+sContextPath+image+"');"; } else { s+="context = initCanvas('"+name+"',100,100,'"+sDrawing+"');"; } s+="</script>"; return s; } public static String createDrawingDiv(HttpServletRequest request,String name, String itemtype, Object transaction,String image, String imageType){ String sContextPath=request.getRequestURI().replaceAll(request.getServletPath(),""); TransactionVO tran = (TransactionVO)transaction; String s = "<script src='"+sContextPath+"/_common/_script/canvas.js'></script>"; s+="<table cellspacing='0' cellpadding='0'>"; s+="<tr><td>"; s+="<img src='"+sContextPath+"/_img/themes/default/canvas_small.png' width='14px' onclick='canvasSetRadius(1)'/>"; s+="<img src='"+sContextPath+"/_img/themes/default/canvas_normal.png' width='14px' onclick='canvasSetRadius(5)'/>"; s+="<img src='"+sContextPath+"/_img/themes/default/canvas_big.png' width='14px' onclick='canvasSetRadius(10)'/>"; s+="</td><td>"; s+="<img src='"+sContextPath+"/_img/themes/default/previous.jpg' width='14px' onclick='canvasReloadBaseImage()'/>"; //s+="<img src='"+sContextPath+"/_img/themes/default/erase.png' width='14px' onclick='updateDrawing()'/>"; s+="</td><td>"; s+="<select onchange='updateDrawing()' id='drawingtype' class='text'>"+writeSelect(request,imageType,"",((User)request.getSession().getAttribute("activeUser")).person.language)+"</select>"; s+="<img src='"+sContextPath+"/_img/icons/icon_default.gif' width='14px' onclick='updateDrawing()'/>"; s+="</td><td/></tr><tr><td colspan='3'>"; s+="<div id='"+name+"' onmouseover='this.style.cursor=\"hand\"'></div>"; s+="</td><td valign='top'><table cellspacing='0' cellpadding='0'>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_black.png' width='14px' onclick='canvasSetColor(\"black\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_white.png' width='14px' onclick='canvasSetColor(\"white\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_red.png' width='14px' onclick='canvasSetColor(\"red\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_blue.png' width='14px' onclick='canvasSetColor(\"blue\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_yellow.png' width='14px' onclick='canvasSetColor(\"yellow\")'/></td></tr>"; s+="<tr><td><img src='"+sContextPath+"/_img/themes/default/canvas_green.png' width='14px' onclick='canvasSetColor(\"green\")'/></td></tr>"; s+="</table></td></tr></table>"; s+="<input type='hidden' name='drawingContent' id='drawingContent'/>"; s+="<input type='hidden' id='"+name+"Drawing' name='currentTransactionVO.items.<ItemVO[hashCode="+tran.getItem(itemtype).hashCode()+"]>.value' value='drawingContent'/>"; s+="<script>"; String sDrawing=ScreenHelper.getDrawing(tran.getServerId(),tran.getTransactionId(),itemtype); if(sDrawing.length()<10){ s+="context = initCanvas('"+name+"',100,100,'"+sContextPath+image+"');"; } else { s+="context = initCanvas('"+name+"',100,100,'"+sDrawing+"');"; } s+="function updateDrawing(){"; s+=" drawingtype=document.getElementById('drawingtype').value.replace(new RegExp('<sl>', 'g'), '/');"; s+=" canvasLoadImage('"+sContextPath+"'+drawingtype);"; s+="}"; s+="</script>"; return s; } public static String createSignatureDiv(HttpServletRequest request,String name, String fieldname,String documentuid, String image){ String sContextPath=request.getRequestURI().replaceAll(request.getServletPath(),""); String s = "<script src='"+sContextPath+"/_common/_script/canvas.js'></script>"; s+="<table cellspacing='0' cellpadding='0'>"; s+="<tr><td>"; s+="<div id='"+name+"' onmouseover='this.style.cursor=\"hand\"'></div>"; s+="</td></tr></table>"; s+="<input type='hidden' name='drawingContent' id='drawingContent'/>"; s+="<input type='hidden' name='"+fieldname+"' value='drawingContent'/>"; s+="<script>"; String sDrawing=ScreenHelper.getDrawing(Integer.parseInt(documentuid.split("\\.")[0]),Integer.parseInt(documentuid.split("\\.")[1]),documentuid.split("\\.")[2]); if(sDrawing.length()<10){ s+="context = initCanvas('"+name+"',100,100,'"+sContextPath+image+"');"; } else { s+="context = initCanvas('"+name+"',100,100,'"+sDrawing+"');"; } s+="</script>"; return s; } public static java.util.Date endOfDay(java.util.Date date){ if(date!=null){ try { return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(new SimpleDateFormat("dd/MM/yyyy").format(date)+" 23:59:59"); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return date; } public static String getDrawing(int serverid, int transactionid, String itemtype){ String drawing=""; Connection conn=MedwanQuery.getInstance().getOpenclinicConnection(); PreparedStatement ps=null; ResultSet rs=null; try{ ps=conn.prepareStatement("select OC_DRAWING_DRAWING from OC_DRAWINGS where OC_DRAWING_SERVERID=? and OC_DRAWING_TRANSACTIONID=? and OC_DRAWING_ITEMTYPE=?"); ps.setInt(1, serverid); ps.setInt(2, transactionid); ps.setString(3, itemtype); rs=ps.executeQuery(); if(rs.next()){ drawing=base64Decompress(rs.getBytes("OC_DRAWING_DRAWING")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); conn.close(); } catch(SQLException se){ se.printStackTrace(); } } return drawing; } //--- GET OBJECT ID --------------------------------------------------------------------------- public static String getObjectId(String sUIDorID){ String sObjectId = ""; if(sUIDorID.indexOf(".") > 0){ sObjectId = sUIDorID.split("\\.")[1]; // seems to be a UID (serverid.objectid) } else{ sObjectId = sUIDorID; // seems to be just the objectid } return sObjectId; } public static String capitalize(String s){ if(s==null){ return null; } else if(s.length()==0){ return ""; } else if(s.length()==1){ return s.toUpperCase(); } else { return s.substring(0,1).toUpperCase()+s.substring(1).toLowerCase(); } } public static String capitalizeFirst(String s){ if(s==null){ return null; } else if(s.length()==0){ return ""; } else if(s.length()==1){ return s.toUpperCase(); } else { return s.substring(0,1).toUpperCase()+s.substring(1); } } public static String capitalizeAllWords(String s){ if(s==null){ return null; } else if(s.length()==0){ return ""; } else if(s.length()==1){ return s.toUpperCase(); } else { String s2=""; for(int n=0;n<s.split(" ").length;n++) { for(int i=0;i<s.split(" ")[n].split("-").length;i++) { if(i>0) { s2+="-"; } s2+=s.split(" ")[n].split("-")[i].substring(0,1).toUpperCase()+s.split(" ")[n].split("-")[i].substring(1).toLowerCase(); } s2+=" "; } return s2.trim(); } } public static String sortedMap2String(SortedMap m){ String s=""; Iterator i = m.keySet().iterator(); while(i.hasNext()){ String key=(String)i.next(); String value=(String)m.get(key); if(s.length()>0){ s+="|"; } s+=key+"$"+value; } return s; } public static SortedMap string2SortedMap(String s){ String[] ss=s.split("\\|"); SortedMap m = new TreeMap(); for(int i=0;i<ss.length;i++){ if(ss[i].split("\\$").length>1){ String key = ss[i].split("\\$")[0]; String value = ss[i].split("\\$")[1]; m.put(key, value); } } return m; } //--- RELOAD DATE FORMATS --------------------------------------------------------------------- public static void reloadDateFormats(){ hourFormat = new SimpleDateFormat(MedwanQuery.getInstance().getConfigString("hourFormat","HH:mm")); stdDateFormat = new SimpleDateFormat(MedwanQuery.getInstance().getConfigString("dateFormat","dd/MM/yyyy")); fullDateFormat = new SimpleDateFormat(stdDateFormat.toPattern()+" "+hourFormat.toPattern()); fullDateFormatSS = new SimpleDateFormat(stdDateFormat.toPattern()+" "+hourFormat.toPattern()+":ss"); hourFormat.setLenient(false); // do not roll into the next year when passing the 12th month stdDateFormat.setLenient(false); fullDateFormat.setLenient(false); fullDateFormatSS.setLenient(false); } //--- CONVERT TO EU DATE ---------------------------------------------------------------------- public static String convertToEUDate(String sDate){ if(sDate.length() > 0){ java.util.Date date = parseDate(sDate); try{ sDate = ScreenHelper.euDateFormat.format(date); } catch(Exception e){ //e.printStackTrace(); } } return sDate; } public static String getDuration(java.util.Date begin, java.util.Date end){ String duration="?"; long minute = 60000; long hour = 60*minute; long day = 24*hour; try{ long d = end.getTime()-begin.getTime(); int days = new Long(d/day).intValue(); d=d-days*day; int hours = new Long(d/hour).intValue(); d=d-hours*hour; int minutes = new Long(d/minute).intValue(); duration = minutes+"min"; if(hours>0 || days>0){ duration=hours+"h "+duration; } if(days>0){ duration=days+"d "+duration; } } catch(Exception e){ e.printStackTrace(); } return duration; } //--- CONVERT TO EU DATE CONCATINATED --------------------------------------------------------- public static String convertToEUDateConcatinated(String sConcatinatedValue){ if(sConcatinatedValue.length() > 0){ // check for $ (row) in the value if(sConcatinatedValue.indexOf("$") > -1){ String sOrigValue = sConcatinatedValue; boolean dateFound = false; String sCell; Vector rows = new Vector(); // run thru rows of the concatinated value while(sConcatinatedValue.indexOf("$") > -1){ // row by row String sRow = sConcatinatedValue.substring(0,sConcatinatedValue.indexOf("$")+1); Vector cells = new Vector(); // cell by cell while(sRow.indexOf("$") > 0){ if(sRow.indexOf("£") > -1){ sCell = sRow.substring(0,sRow.indexOf("£")); } else{ sCell = sRow.substring(0,sRow.indexOf("$")); } // convert to EU date, which is the format to store dates in the DB if(ScreenHelper.isDateValue(sCell)){ // convert to EU date sCell = ScreenHelper.convertToEUDate(sCell); dateFound = true; } cells.add(sCell); // trim-off treated cell if(sRow.indexOf("£") > -1){ sRow = sRow.substring(sRow.indexOf("£")+1); } else{ sRow = sRow.substring(sRow.indexOf("$")); } // treat next cell } // trim-off treated row sConcatinatedValue = sConcatinatedValue.substring(sConcatinatedValue.indexOf("$")+1); // compose row again sRow = ""; for(int i=0; i<cells.size(); i++){ sRow+= (String)cells.get(i)+"£"; // terminate cell } sRow = sRow.substring(0,sRow.length()-1); // trim-off £ sRow+= "$"; // terminate row // save treated row in vector rows.add(sRow); // treat next row } // reconstruct value from rows in vector if(dateFound){ sConcatinatedValue = ""; // reset for(int i=0; i<rows.size(); i++){ sConcatinatedValue+= (String)rows.get(i); } // trim-off last separator } else{ sConcatinatedValue = sOrigValue; } } } return sConcatinatedValue; } //--- CONVERT DATE ---------------------------------------------------------------------------- // typically from EU (database) to EU or US (display) public static String convertDate(String sDate){ if(sDate.length() > 0){ java.util.Date date = parseDate(sDate,euDateFormat); try{ sDate = ScreenHelper.stdDateFormat.format(date); } catch(Exception e){ //e.printStackTrace(); } return sDate; } else{ return ""; } } public static java.util.Date endOfDay(String sDate) throws ParseException{ java.util.Date date = null; date = parseDate(sDate); date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(new SimpleDateFormat("dd/MM/yyyy").format(date)+" 23:59:59"); return date; } //--- PARSE DATE ------------------------------------------------------------------------------ public static java.util.Date parseDate(String sDate){ return parseDate(sDate,stdDateFormat); } public static String getParam(String[] args,String name, String defaultValue) { for(int n=0;n<args.length;n++) { if(args[n].equals(name) && n<args.length-1) { return args[n+1]; } } return defaultValue; } public static void updateTableColumn(String table, String column, String oldValue, String newValue) { Connection conn = SH.getOpenClinicConnection(); try { PreparedStatement ps = conn.prepareStatement("update "+table+" set "+column+"=? where "+column+"=?"); ps.setString(1, newValue); ps.setString(2, oldValue); ps.execute(); ps.close(); conn.close(); } catch(Exception e) { e.printStackTrace(); } } public static void updateTableColumn(String table, String column, int oldValue, int newValue) throws SQLException { Connection conn = SH.getOpenClinicConnection(); PreparedStatement ps = conn.prepareStatement("update "+table+" set "+column+"=? where "+column+"=?"); ps.setInt(1, newValue); ps.setInt(2, oldValue); ps.execute(); ps.close(); conn.close(); } public static boolean updateEncounterUid(String oldUid, String newUid) { boolean bSuccess = false; Connection conn = SH.getOpenClinicConnection(); try { Encounter encounter = Encounter.get(oldUid); //Update Encounters String sSql="update oc_encounters set oc_encounter_objectid=? where oc_encounter_serverid=? and oc_encounter_objectid=?"; PreparedStatement ps = conn.prepareStatement(sSql); ps.setInt(1, OC_Object.getObjectId(newUid)); ps.setInt(2, OC_Object.getServerId(oldUid)); ps.setInt(3, OC_Object.getObjectId(oldUid)); ps.execute(); ps.close(); conn.close(); //Update Transactions Vector<TransactionVO> transactions = MedwanQuery.getInstance().getTransactionsByEncounter(Integer.parseInt(encounter.getPatientUID()), encounter.getUid()); for(int n=0;n<transactions.size();n++) { TransactionVO transaction = transactions.elementAt(n); ItemVO item = transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_CONTEXT_ENCOUNTERUID"); item.updateValue(newUid); } updateTableColumn("OC_CREDITS", "OC_CREDIT_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_DEBETS", "OC_DEBET_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_DIAGNOSES", "OC_DIAGNOSIS_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_DRUGSOUTLIST", "OC_LIST_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_IKIREZIACTIONS", "OC_ACTION_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_IKIREZISYMPTOMS", "OC_SYMPTOM_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_PATIENTCREDITS", "OC_PATIENTCREDIT_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_PRESTATIONDEBETS", "OC_DEBET_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_RFE", "OC_RFE_ENCOUNTERUID", oldUid, newUid); updateTableColumn("OC_SNOMEDCT", "OC_SNOMEDCT_ENCOUNTERUID", oldUid, newUid); bSuccess=true; } catch(Exception e) { e.printStackTrace(); } return bSuccess; } public static boolean updateTransactionUid(String oldUid, String newUid) { boolean bSuccess = false; try { updateTableColumn("Transactions", "transactionid", oldUid, newUid); updateTableColumn("Items", "transactionid", oldUid, newUid); updateTableColumn("OC_PLANNING", "OC_PLANNING_TRANSACTIONUID", oldUid, newUid); updateTableColumn("Requestedlabanalyses", "transactionid", oldUid, newUid); bSuccess=true; } catch(Exception e) { e.printStackTrace(); } return bSuccess; } public static java.util.Date parseDate(String sDate, SimpleDateFormat dateFormat){ reloadDateFormats(); java.util.Date date = null; try{ date = dateFormat.parse(sDate); } catch(Exception e){ // try parsing with the other format try{ if(stdDateFormat.toPattern().equals("dd/MM/yyyy")){ // EU gave error --> try US date = new SimpleDateFormat("MM/dd/yyyy").parse((String)sDate); sDate = dateFormat.format(date); } else if(stdDateFormat.toPattern().equals("MM/dd/yyyy")){ // US gave error --> try EU date = new SimpleDateFormat("dd/MM/yyyy").parse((String)sDate); sDate = dateFormat.format(date); } } catch(Exception e2){ //e2.printStackTrace(); } } return date; } public static java.util.Date parseDate(String sDate, String dateFormat){ reloadDateFormats(); java.util.Date date = null; try{ date = new SimpleDateFormat(dateFormat).parse(sDate); } catch(Exception e){ e.printStackTrace(); } return date; } //--- IS DATE VALUE --------------------------------------------------------------------------- // recognises date-values public static boolean isDateValue(String sValue){ boolean isDateValue = false; if(parseDate(sValue)!=null){ isDateValue = true; } return isDateValue; } //--- GET TODAY ------------------------------------------------------------------------------- public static java.util.Date getToday(){ Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date()); // now cal.set(Calendar.HOUR,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); return cal.getTime(); // past midnight } //--- GET TOMORROW ---------------------------------------------------------------------------- public static java.util.Date getTomorrow(){ Calendar cal = Calendar.getInstance(); cal.setTime(new java.util.Date()); // now cal.set(Calendar.HOUR,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); cal.add(Calendar.DAY_OF_YEAR,1); return cal.getTime(); // next midnight } //--- GET LABEL ------------------------------------------------------------------------------- public static String getLabel(String sType, String sID, String sLanguage, String sObject){ return "<label for='"+sObject+"'>"+getTran(null,sType,sID,sLanguage)+"</label>"; } //--- LEFT ------------------------------------------------------------------------------------ public static String left(String s,int n){ if(s==null){ return ""; } else if(s.length()<=n){ return s; } else{ return s.substring(0,n-3)+"..."; } } //--- UPPERCASE FIRST LETTER ------------------------------------------------------------------ public static String uppercaseFirstLetter(String sValue){ String sFirstLetter; if(sValue.length() > 0){ sFirstLetter = sValue.substring(0,1).toUpperCase(); sValue = sFirstLetter+sValue.substring(1); } return sValue; } //--- BOLD FIRST LETTER ----------------------------------------------------------------------- // html public static String boldFirstLetter(String sValue){ String sFirstLetter; if(sValue.length() > 0){ sFirstLetter = sValue.substring(0,1).toUpperCase(); sValue = "<b>"+sFirstLetter+"</b>"+sValue.substring(1); } return sValue; } //--- COUNT MATCHES IN STRING ----------------------------------------------------------------- public static int countMatchesInString(String sText, String sTarget){ int count = 0; while(sText.indexOf(sTarget) > -1){ sText = sText.substring(sText.indexOf(sTarget)+sTarget.length()); count++; } return count; } //--- GET PRICE FORMAT ------------------------------------------------------------------------ public static String getPriceFormat(double value){ DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(); formatSymbols.setGroupingSeparator(MedwanQuery.getInstance().getConfigString("decimalThousandsSeparator"," ").toCharArray()[0]); return new DecimalFormat(MedwanQuery.getInstance().getConfigString("priceFormat"),formatSymbols).format(value); } //--- VECTOR TO STRING ------------------------------------------------------------------------ public static String vectorToString(Vector vector, String sDelimeter){ return vectorToString(vector,sDelimeter,true); } public static String vectorToString(Vector vector, String sDelimeter, boolean addApostrophes){ StringBuffer stringBuffer = new StringBuffer(); for(int i=0; i<vector.size(); i++){ if(addApostrophes) stringBuffer.append("'"); stringBuffer.append((String)vector.get(i)); if(addApostrophes) stringBuffer.append("'"); if(i<vector.size()-1){ stringBuffer.append(sDelimeter); } } return stringBuffer.toString(); } //--- CUSTOMER INCLUDE ------------------------------------------------------------------------ public static String customerInclude(String fileName, String sAPPFULLDIR, String sAPPDIR){ if(fileName.indexOf("?") > 0){ fileName = fileName.substring(0,fileName.indexOf("?")); } if(new File((sAPPFULLDIR+"/"+sAPPDIR+"/"+fileName).replaceAll("//","/")).exists()){ Debug.println("Customer file "+(sAPPFULLDIR+"/"+sAPPDIR+"/"+fileName).replaceAll("//","/")+" found"); return ("/"+sAPPDIR+"/"+fileName).replaceAll("//","/"); } else{ Debug.println("Customer file "+(sAPPFULLDIR+"/"+sAPPDIR+"/"+fileName).replaceAll("//","/")+" not found, using "+("/"+fileName).replaceAll("//","/")); return ("/"+fileName).replaceAll("//","/"); } } //--- GET TRAN -------------------------------------------------------------------------------- public static String getTran(String sType, String sID, String sLanguage){ return getTran(null,sType,sID,sLanguage,false); } public static String getTran(HttpServletRequest request,String sType, String sID, String sLanguage){ return getTran(request,sType,sID,sLanguage,false); } public static boolean isTimeout(String sName, long intervalInSeconds) { java.util.Date dLastValue = new java.util.Date(); try{ dLastValue=new SimpleDateFormat("yyyyMMddHHmmss").parse(SH.cs(sName,"19000101000000")); } catch(Exception e) { e.printStackTrace(); } return new java.util.Date().getTime()-dLastValue.getTime()>1000*intervalInSeconds; } public static void setTimer(String sName) { MedwanQuery.getInstance().setConfigString(sName, new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date())); } public static String getTran(HttpServletRequest request,String sType, String sID, String sLanguage, boolean displaySimplePopup){ String labelValue = ""; try{ if(sLanguage==null || sLanguage.length()!=2){ return sID; } if(sType.equalsIgnoreCase("service") || sType.equalsIgnoreCase("function")){ labelValue = MedwanQuery.getInstance().getLabel(sType.toLowerCase(),sID.toLowerCase(),sLanguage); if(labelValue.length()==0){ if(checkString(MedwanQuery.getInstance().getConfigString("showLinkNoTranslation")).equals("on")){ String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select"; return "<a href='#' onClick=javascript:openPopup('"+url+"');>"+sID+"</a>"; // onclick without parenthesis } else{ return sID; } } else{ return labelValue.replaceAll("'", "´"); } } else{ Hashtable langHashtable = MedwanQuery.getInstance().getLabels(); if(langHashtable==null){ saveUnknownLabel(sType, sID, sLanguage); return sID; } Hashtable typeHashtable = (Hashtable)langHashtable.get(sLanguage.toLowerCase()); if(typeHashtable==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } if(checkString(MedwanQuery.getInstance().getConfigString("showLinkNoTranslation")).equals("on")){ String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select"; return "<a href='#' onClick=javascript:openPopup('"+url+"');>"+sID+"</a>"; // onclick without parenthesis } else{ return sID; } } Hashtable idHashtable = (Hashtable)typeHashtable.get(sType.toLowerCase()); if(idHashtable==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } if(checkString(MedwanQuery.getInstance().getConfigString("showLinkNoTranslation")).equals("on")){ String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select"; return "<a href='#' onClick=javascript:openPopup('"+url+"');>"+sID+"</a>"; // onclick without parenthesis } else{ return sID; } } Label label = (Label)idHashtable.get(sID.toLowerCase()); if(label==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } if(checkString(MedwanQuery.getInstance().getConfigString("showLinkNoTranslation")).equals("on")){ String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select"; return "<a href='#' onClick=javascript:openPopup('"+url+"');>"+sID+"</a>"; // onclick without parenthesis } else{ return sID; } } if(!label.value.contains("<NOREPLACE/>")) { labelValue = label.value.replaceAll("'", "´"); } else { labelValue = label.value; } // display link to label if(labelValue==null || labelValue.trim().length()==0){ if(label.showLink==null || label.showLink.equals("1")){ String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select"; return "<a href='#' onClick=javascript:openPopup('"+url+"');>"+sID+"</a>"; // onclick without parenthesis } } else if(request!=null && request.getSession().getAttribute("editmode")!=null && ((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select&Mode=mini"; return "<span style='cursor: pointer;color: white;background-color: black;font-weight: bold' onclick=\"openPopup('"+url+"',700,100,'Edit');return false;\">"+(labelValue.length()>0?labelValue.substring(0, 1):"")+"</span>"+(labelValue.length()>1?labelValue.substring(1):""); // onclick without parenthesis } } } catch(Exception e){ e.printStackTrace(); } return labelValue.replaceAll("##CR##","\n").replaceAll("'", labelValue.contains("<NOREPLACE/>")?"'":"´"); } //--- GET TRAN WITH LINK ---------------------------------------------------------------------- public static String getTranWithLink(String sType, String sID, String sLanguage){ return getTranWithLink(sType,sID,sLanguage,false); } public static String getTranWithLink(String sType, String sID, String sLanguage, boolean displaySimplePopup){ String labelValue = ""; String url = "system/"+(displaySimplePopup?"manageTranslationsPopupSimple":"manageTranslationsPopup")+".jsp&EditOldLabelID="+sID+"&EditOldLabelType="+sType+"&EditOldLabelLang="+sLanguage+"&Action=Select"; try{ if(sLanguage.length()!=2) throw new Exception("Language must be a two-letter notation."); if(sType.equalsIgnoreCase("service") || sType.equalsIgnoreCase("function")){ labelValue = MedwanQuery.getInstance().getLabel(sType.toLowerCase(),sID.toLowerCase(),sLanguage); if(labelValue.length()==0){ return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+sID+"</a>"; } else{ return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+labelValue+"</a>"; } } else{ Hashtable langHashtable = MedwanQuery.getInstance().getLabels(); if(langHashtable==null){ saveUnknownLabel(sType, sID, sLanguage); return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+sID+"</a>"; } Hashtable typeHashtable = (Hashtable)langHashtable.get(sLanguage.toLowerCase()); if(typeHashtable==null){ return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+sID+"</a>"; } Hashtable idHashtable = (Hashtable)typeHashtable.get(sType.toLowerCase()); if(idHashtable==null){ return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+sID+"</a>"; } Label label = (Label)idHashtable.get(sID.toLowerCase()); if(label==null){ return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+sID+"</a>"; } labelValue = label.value; // display link to label if(labelValue==null || labelValue.trim().length()==0){ return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+sID+"</a>"; } } } catch(Exception e){ e.printStackTrace(); } return "<a href='#' onClick=\"javascript:openPopup('"+url+"');\">"+labelValue+"</a>"; } //--- GET TRAN DB ----------------------------------------------------------------------------- public static String getTranDb(String sType, String sID, String sLang){ String labelValue = ""; if(sType!=null && sID!=null && sLang!=null){ PreparedStatement ps = null; ResultSet rs = null; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ if(sLang.length()!=2) throw new Exception("Language must be a two-letter notation."); // LOWER String sSelect = "SELECT OC_LABEL_VALUE FROM OC_LABELS"+ " WHERE OC_LABEL_TYPE=? AND OC_LABEL_ID=? AND OC_LABEL_LANGUAGE=?"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sType.toLowerCase()); ps.setString(2,sID.toLowerCase()); ps.setString(3,sLang.toLowerCase()); rs = ps.executeQuery(); if(rs.next()){ labelValue = checkString(rs.getString("OC_LABEL_VALUE")); } else{ labelValue = sID; } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException se){ se.printStackTrace(); } } } return labelValue.replaceAll("##CR##","\n").replaceAll("'", "´"); } //--- GET TRAN NO LINK ------------------------------------------------------------------------ public static String getTranNoLink(String sType, String sID, String sLanguage){ if(sType==null){ Debug.println("WARNING - getTranNoLink : sType is null for sID:"+sID+" and sLanguage:"+sLanguage); return ""; } if(sID==null){ Debug.println("WARNING - getTranNoLink : sID is null for sType:"+sType+" and sLanguage:"+sLanguage); return ""; } String labelValue = ""; if(sLanguage!=null && sLanguage.equalsIgnoreCase("f")){ sLanguage = "fr"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("n")){ sLanguage = "nl"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("e")){ sLanguage = "en"; } try{ if(sLanguage!=null && sLanguage.length()==2){ if(sType.equalsIgnoreCase("service") || sType.equalsIgnoreCase("function")){ labelValue = MedwanQuery.getInstance().getLabel(sType.toLowerCase(),sID.toLowerCase(),sLanguage); } else{ Hashtable labels = MedwanQuery.getInstance().getLabels(); if(labels==null){ saveUnknownLabel(sType,sID,sLanguage); return sID; } else{ Hashtable langHashtable = MedwanQuery.getInstance().getLabels(); if(langHashtable==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } return sID; } Hashtable typeHashtable = (Hashtable)langHashtable.get(sLanguage.toLowerCase()); if(typeHashtable==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } return sID; } Hashtable idHashtable = (Hashtable)typeHashtable.get(sType.toLowerCase()); if(idHashtable==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } return sID; } Label label = (Label)idHashtable.get(sID.toLowerCase()); if(label==null){ if(MedwanQuery.getInstance().getConfigInt("enableAutoTranslate",0)==1){ String sLabel=Translate.translateLabel(sType,sID,MedwanQuery.getInstance().getConfigString("autoTranslateSourceLanguage","en"),sLanguage); if(sLabel!=null){ return sLabel.replaceAll("'", "´"); } } return sID; } labelValue = label.value.replaceAll("'", "´"); // empty label : return id as labelValue if(labelValue==null || labelValue.trim().length()==0){ return sID; } } } } } catch(Exception e){ e.printStackTrace(); } return labelValue.replaceAll("##CR##","\n").replaceAll("'", "´"); } public static String getTranNoLinkNoTranslate(String sType, String sID, String sLanguage){ if(sType==null){ Debug.println("WARNING - getTranNoLink : sType is null for sID:"+sID+" and sLanguage:"+sLanguage); return ""; } if(sID==null){ Debug.println("WARNING - getTranNoLink : sID is null for sType:"+sType+" and sLanguage:"+sLanguage); return ""; } String labelValue = ""; if(sLanguage!=null && sLanguage.equalsIgnoreCase("f")){ sLanguage = "fr"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("n")){ sLanguage = "nl"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("e")){ sLanguage = "en"; } try{ if(sLanguage!=null && sLanguage.length()==2){ if(sType.equalsIgnoreCase("service") || sType.equalsIgnoreCase("function")){ labelValue = MedwanQuery.getInstance().getLabel(sType.toLowerCase(),sID.toLowerCase(),sLanguage); } else{ Hashtable labels = MedwanQuery.getInstance().getLabels(); if(labels==null){ saveUnknownLabel(sType,sID,sLanguage); return sID; } else{ Hashtable langHashtable = MedwanQuery.getInstance().getLabels(); if(langHashtable==null){ return sID; } Hashtable typeHashtable = (Hashtable)langHashtable.get(sLanguage.toLowerCase()); if(typeHashtable==null){ return sID; } Hashtable idHashtable = (Hashtable)typeHashtable.get(sType.toLowerCase()); if(idHashtable==null){ return sID; } Label label = (Label)idHashtable.get(sID.toLowerCase()); if(label==null){ return sID; } labelValue = label.value; // empty label : return id as labelValue if(labelValue==null || labelValue.trim().length()==0){ return sID; } } } } } catch(Exception e){ e.printStackTrace(); } return labelValue.replaceAll("##CR##","\n").replaceAll("'", "´"); } //--- GET TRAN NO ID -------------------------------------------------------------------------- public static String getTranNoId(String sType, String sID, String sLanguage){ if(sType==null){ Debug.println("WARNING - getTranNoLink : sType is null for sID:"+sID+" and sLanguage:"+sLanguage); return ""; } if(sID==null){ Debug.println("WARNING - getTranNoLink : sID is null for sType:"+sType+" and sLanguage:"+sLanguage); return ""; } String labelValue = ""; if(sLanguage!=null && sLanguage.equalsIgnoreCase("f")){ sLanguage = "fr"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("n")){ sLanguage = "nl"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("e")){ sLanguage = "en"; } try{ if(sLanguage!=null && sLanguage.length()==2){ if(sType.equalsIgnoreCase("service") || sType.equalsIgnoreCase("function")){ labelValue = MedwanQuery.getInstance().getLabel(sType.toLowerCase(),sID.toLowerCase(),sLanguage); } else{ Hashtable labels = MedwanQuery.getInstance().getLabels(); if(labels==null){ saveUnknownLabel(sType,sID,sLanguage); return ""; } else{ Hashtable langHashtable = MedwanQuery.getInstance().getLabels(); if(langHashtable==null){ return ""; } Hashtable typeHashtable = (Hashtable)langHashtable.get(sLanguage.toLowerCase()); if(typeHashtable==null){ return ""; } Hashtable idHashtable = (Hashtable)typeHashtable.get(sType.toLowerCase()); if(idHashtable==null){ return ""; } Label label = (Label)idHashtable.get(sID.toLowerCase()); if(label==null){ return ""; } labelValue = label.value; // empty label : return id as labelValue if(labelValue==null || labelValue.trim().length()==0){ return ""; } } } } } catch(Exception e){ e.printStackTrace(); } return labelValue.replaceAll("##CR##","\n"); } //--- GET TRAN NO LINK ------------------------------------------------------------------------ public static String getTranExists(String sType, String sID, String sLanguage){ String labelValue = ""; if(sLanguage!=null && sLanguage.equalsIgnoreCase("f")){ sLanguage = "fr"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("n")){ sLanguage = "nl"; } else if(sLanguage!=null && sLanguage.equalsIgnoreCase("e")){ sLanguage = "en"; } try{ if(sLanguage!=null && sLanguage.length()==2){ if(sType.equalsIgnoreCase("service") || sType.equalsIgnoreCase("function")){ labelValue = MedwanQuery.getInstance().getLabel(sType.toLowerCase(),sID.toLowerCase(),sLanguage); if(labelValue==sID){ return ""; } } else{ Hashtable labels = MedwanQuery.getInstance().getLabels(); if(labels==null){ saveUnknownLabel(sType,sID,sLanguage); return ""; } else{ Hashtable langHashtable = MedwanQuery.getInstance().getLabels(); if(langHashtable==null){ return ""; } Hashtable typeHashtable = (Hashtable)langHashtable.get(sLanguage.toLowerCase()); if(typeHashtable==null){ return ""; } Hashtable idHashtable = (Hashtable)typeHashtable.get(sType.toLowerCase()); if(idHashtable==null){ return ""; } Label label = (Label)idHashtable.get(sID.toLowerCase()); if(label==null){ return ""; } labelValue = label.value; // empty label : return id as labelValue if(labelValue==null || labelValue.trim().length()==0){ return ""; } } } } } catch(Exception e){ e.printStackTrace(); } return labelValue.replaceAll("##CR##","\n"); } //--- CONVERT HTML CODE TO CHAR --------------------------------------------------------------- public static String convertHtmlCodeToChar(String text){ text = text.replaceAll("&eacute;","é"); text = text.replaceAll("&egrave;","è"); text = text.replaceAll("&euml;","ë"); text = text.replaceAll("&ouml;","ö"); text = text.replaceAll("&agrave;","à"); text = text.replaceAll("&#231;","ç"); text = text.replaceAll("&#156;","œ"); text = text.replaceAll("<br>","\r\n"); text = text.replaceAll("&gt;",">"); text = text.replaceAll("&lt;","<"); return text; } //--- NORMALIZE SPECIAL CHARACTERS ------------------------------------------------------------ public static String normalizeSpecialCharacters(String sTest){ sTest = sTest.replaceAll("'",""); sTest = sTest.replaceAll("´",""); // difference ! sTest = sTest.replaceAll(" ",""); sTest = sTest.replaceAll("-",""); sTest = sTest.replaceAll("é","e"); sTest = sTest.replaceAll("è","e"); sTest = sTest.replaceAll("ë","e"); sTest = sTest.replaceAll("ê","e"); sTest = sTest.replaceAll("ï","i"); sTest = sTest.replaceAll("í","i"); sTest = sTest.replaceAll("ö","o"); sTest = sTest.replaceAll("ô","o"); sTest = sTest.replaceAll("ä","a"); sTest = sTest.replaceAll("á","a"); sTest = sTest.replaceAll("à","a"); sTest = sTest.replaceAll("â","a"); sTest = sTest.replaceAll("ñ","n"); sTest = sTest.replaceAll("É","E"); sTest = sTest.replaceAll("È","E"); sTest = sTest.replaceAll("Ë","E"); sTest = sTest.replaceAll("Ê","E"); sTest = sTest.replaceAll("Ï","I"); sTest = sTest.replaceAll("Ö","O"); sTest = sTest.replaceAll("Ô","O"); sTest = sTest.replaceAll("Ï","I"); sTest = sTest.replaceAll("Í","I"); sTest = sTest.replaceAll("Ó","O"); sTest = sTest.replaceAll("Ä","A"); sTest = sTest.replaceAll("Á","A"); sTest = sTest.replaceAll("À","A"); sTest = sTest.replaceAll("Â","A"); sTest = sTest.replaceAll("Ñ","N"); return sTest; } public static String removeAccents(String sTest){ sTest = sTest.replaceAll("é","e"); sTest = sTest.replaceAll("è","e"); sTest = sTest.replaceAll("ë","e"); sTest = sTest.replaceAll("ê","e"); sTest = sTest.replaceAll("ï","i"); sTest = sTest.replaceAll("ö","o"); sTest = sTest.replaceAll("ô","o"); sTest = sTest.replaceAll("ä","a"); sTest = sTest.replaceAll("á","a"); sTest = sTest.replaceAll("à","a"); sTest = sTest.replaceAll("â","a"); sTest = sTest.replaceAll("ñ","n"); sTest = sTest.replaceAll("É","E"); sTest = sTest.replaceAll("È","E"); sTest = sTest.replaceAll("Ë","E"); sTest = sTest.replaceAll("Ê","E"); sTest = sTest.replaceAll("Ï","I"); sTest = sTest.replaceAll("Ö","O"); sTest = sTest.replaceAll("Ô","O"); sTest = sTest.replaceAll("Í","I"); sTest = sTest.replaceAll("Ó","O"); sTest = sTest.replaceAll("Ä","A"); sTest = sTest.replaceAll("Á","A"); sTest = sTest.replaceAll("À","A"); sTest = sTest.replaceAll("Ñ","N"); return sTest; } //--- GET CONFIG STRING ----------------------------------------------------------------------- public static String getConfigString(String key, Connection conn){ String cs = ""; try{ Statement st = conn.createStatement(); ResultSet Configrs = st.executeQuery("SELECT oc_value FROM OC_Config WHERE oc_key like '"+key+"'"+ " AND deletetime IS NULL ORDER BY oc_key"); while(Configrs.next()){ cs+= Configrs.getString("oc_value"); } Configrs.close(); st.close(); } catch(Exception e){ e.printStackTrace(); } return cs; } //--- GET CONFIG PARAM ------------------------------------------------------------------------ public static String getConfigParam(String key, String param, Connection conn){ return getConfigString(key,conn).replaceAll("<param>",param); } //--- GET CONFIG PARAM ------------------------------------------------------------------------ public static String getConfigParam(String key, String[] params, Connection conn){ String result = getConfigString(key,conn); for(int i=0; i<params.length; i++){ result = result.replaceAll("<param"+(i+1)+">",params[i]); } return result; } //--- SET ROW --------------------------------------------------------------------------------- public static String setRow(String sType, String sID, String sValue, String sLanguage){ return "<tr><td class='admin'>"+getTran(null,sType,sID,sLanguage)+"</td><td class='admin2'>"+sValue+"</td></tr>"; } public static String setRow(HttpServletRequest request,String sType, String sID, String sValue, String sLanguage){ return "<tr><td class='admin'>"+getTran(request,sType,sID,sLanguage)+"</td><td class='admin2'>"+sValue+"</td></tr>"; } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setMaliAdminPrivateContact(AdminPrivateContact apc, String sLanguage){ return setMaliAdminPrivateContact(null, apc, sLanguage); } public static String setMaliAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length() > 0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length() > 0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","region",apc.sanitarydistrict,sLanguage)+ setRow(request,"Web","district",apc.district,sLanguage)+ setRow(request,"Web","community",apc.sector,sLanguage)+ setRow(request,"Web","sector",apc.quarter,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","zipcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setCameroonAdminPrivateContact(AdminPrivateContact apc, String sLanguage){ return setCameroonAdminPrivateContact(null, apc, sLanguage); } public static String setCameroonAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","region",apc.sanitarydistrict,sLanguage)+ setRow(request,"Web","country.department",apc.district,sLanguage)+ setRow(request,"Web","arrondissement",apc.sector,sLanguage)+ setRow(request,"Web","sector",apc.quarter,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","postcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } public static String setBurkinaAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","region",apc.sanitarydistrict,sLanguage)+ setRow(request,"Web","province",apc.district,sLanguage)+ setRow(request,"Web","country.department",apc.sector,sLanguage)+ setRow(request,"Web","sector",apc.quarter,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","postcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } public static String setPeruAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","country.department",apc.sanitarydistrict,sLanguage)+ setRow(request,"Web","region",apc.district,sLanguage)+ setRow(request,"Web","arrondissement",apc.sector,sLanguage)+ setRow(request,"Web","postcode",apc.zipcode,sLanguage)+ setRow(request,"Web","municipality",apc.city,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setGuineaAdminPrivateContact(AdminPrivateContact apc, String sLanguage){ return setGuineaAdminPrivateContact(null, apc, sLanguage); } public static String setGuineaAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","region",apc.sanitarydistrict,sLanguage)+ setRow(request,"Web","prefecture",apc.district,sLanguage)+ setRow(request,"Web","subprefecture",apc.sector,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","postcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setOpenclinicAdminPrivateContact(AdminPrivateContact apc, String sLanguage){ return setOpenclinicAdminPrivateContact(null, apc, sLanguage); } public static String setOpenclinicAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","region",apc.sanitarydistrict,sLanguage)+ setRow(request,"Web","province",apc.province,sLanguage)+ setRow(request,"Web","district",apc.district,sLanguage)+ setRow(request,"Web","community",apc.sector,sLanguage)+ setRow(request,"Web","sector",apc.quarter,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","zipcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setAdminPrivateContact(AdminPrivateContact apc, String sLanguage){ return setAdminPrivateContact(null, apc, sLanguage); } public static String setAdminPrivateContact(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } if(MedwanQuery.getInstance().getConfigInt("cnarEnabled",0)==1){ return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","district",apc.district,sLanguage)+ setRow(request,"Web","zipcode",apc.zipcode,sLanguage)+ setRow(request,"Web","province",sProvince,sLanguage)+ setRow(request,"Web","city",apc.city,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } else{ return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","zipcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","province",sProvince,sLanguage)+ setRow(request,"Web","district",apc.district,sLanguage)+ setRow(request,"Web","sector",apc.sector,sLanguage)+ setRow(request,"Web","cell",apc.cell,sLanguage)+ setRow(request,"Web","city",apc.city,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setAdminPrivateContactBurundi(AdminPrivateContact apc, String sLanguage){ return setAdminPrivateContactBurundi(null, apc, sLanguage); } public static String setAdminPrivateContactBurundi(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web.admin","addresschangesince",apc.begin,sLanguage)+ setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","province",apc.district,sLanguage)+ setRow(request,"Web","community",apc.sector,sLanguage)+ setRow(request,"Web","hill_quarter",apc.city,sLanguage)+ setRow(request,"Web","zipcode",apc.zipcode,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","email",apc.email,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","cell",apc.cell,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage)+ setRow(request,"Web","comment",apc.comment,sLanguage) ); } //--- SET ADMIN PRIVATE CONTACT --------------------------------------------------------------- public static String setAdminPrivateContactCDO(AdminPrivateContact apc, String sLanguage){ return setAdminPrivateContactCDO(null, apc, sLanguage); } public static String setAdminPrivateContactCDO(HttpServletRequest request,AdminPrivateContact apc, String sLanguage){ String sCountry = "&nbsp;"; if(checkString(apc.country).trim().length()>0){ sCountry = getTran(null,"Country",apc.country,sLanguage); } String sProvince = "&nbsp;"; if(checkString(apc.province).trim().length()>0){ sProvince = getTran(null,"province",apc.province,sLanguage); } return( setRow(request,"Web","address",apc.address,sLanguage)+ setRow(request,"Web","country",sCountry,sLanguage)+ setRow(request,"Web","telephone",apc.telephone,sLanguage)+ setRow(request,"Web","mobile",apc.mobile,sLanguage)+ setRow(request,"Web","province",apc.district,sLanguage)+ setRow(request,"Web","community",apc.sector,sLanguage)+ setRow(request,"Web","function",apc.businessfunction,sLanguage)+ setRow(request,"Web","business",apc.business,sLanguage) ); } //--- WRITE LOOSE DATE FIELD YEAR ------------------------------------------------------------- public static String writeLooseDateFieldYear(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR){ String gfPopType = "1"; // default if(allowPastDates && allowFutureDates){ gfPopType = "1"; } else{ if(allowFutureDates){ gfPopType = "3"; } else if(allowPastDates){ gfPopType = "2"; } } // datefield that ALSO accepts just a year return "<input type='text' maxlength='10' class='text' id='"+sName+"' name='"+sName+"' value='"+sValue+"' size='12' onblur='if(!checkDateOnlyYearAllowed(this)){dateError(this);this.value=\"\";}'>" +"&nbsp;<img name='popcal' style='vertical-align:-1px;' onclick='gfPop"+gfPopType+".fPopCalendar(document."+sForm+"."+sName+");return false;' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"'></a>"+ "&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("Web","PutToday",sWebLanguage)+"' onclick='getToday(document."+sForm+"."+sName+");'>"; } //--- WRITE DATE FIELD ------------------------------------------------------------------------ public static String writeDateField(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR){ return writeDateField(sName,sForm,sValue,allowPastDates,allowFutureDates,sWebLanguage,sCONTEXTDIR,""); } public static String writeDateField(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR, String sExtraOnBlur){ String gfPopType = "1"; // default if(allowPastDates && allowFutureDates){ gfPopType = "1"; } else{ if(allowFutureDates) gfPopType = "3"; else if(allowPastDates) gfPopType = "2"; } String sExtraCondition = ""; if(!allowFutureDates){ sExtraCondition = " || isForbiddenFutureDate(this,false)"; } if(!allowPastDates){ sExtraCondition = " || isForbiddenPastDate(this,false)"; } return "<span style='white-space: nowrap'><input type='text' maxlength='10' class='text' id='"+sName+"' name='"+sName+"' value='"+sValue+"' size='10' onblur='if(!checkDate(this)"+sExtraCondition+"){dateError(this);}else{"+sExtraOnBlur+"}'>"+ "&nbsp;<img height='16px' name='popcal' style='vertical-align:middle;' onclick='gfPop"+gfPopType+".fPopCalendar(document."+sForm+"."+sName+");return false;' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"'></a>"+ "&nbsp;<img height='16px' style='vertical-align:middle;' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("Web","PutToday",sWebLanguage)+"' onclick='getToday(document."+sForm+"."+sName+");'></span>"; } public static String writeDateFieldWithReadonly(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR, String sExtraOnBlur){ String gfPopType = "1"; // default if(allowPastDates && allowFutureDates){ gfPopType = "1"; } else{ if(allowFutureDates) gfPopType = "3"; else if(allowPastDates) gfPopType = "2"; } String sExtraCondition = ""; if(!allowFutureDates){ sExtraCondition = " || isForbiddenFutureDate(this,false)"; } if(!allowPastDates){ sExtraCondition = " || isForbiddenPastDate(this,false)"; } return "<span style='white-space: nowrap'><input type='text' maxlength='10' class='text' id='"+sName+"' name='"+sName+"' value='"+sValue+"' size='10' onblur='if(!checkDate(this)"+sExtraCondition+"){dateError(this);}else{"+sExtraOnBlur+"}'>"+ "&nbsp;<img height='16px' name='popcal' style='vertical-align:middle;' onclick='if(document.getElementById(\""+sName+"\").getAttribute(\"readonly\")){}else{gfPop"+gfPopType+".fPopCalendar(document."+sForm+"."+sName+");return false;}' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"'></a>"+ "&nbsp;<img height='16px' style='vertical-align:middle;' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("Web","PutToday",sWebLanguage)+"' onclick='if(document.getElementById(\""+sName+"\").getAttribute(\"readonly\")){}else{getToday(document."+sForm+"."+sName+");}'></span>"; } public static String writeDateFieldMPI(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR, String imageSize){ String gfPopType = "1"; // default if(allowPastDates && allowFutureDates){ gfPopType = "1"; } else{ if(allowFutureDates) gfPopType = "3"; else if(allowPastDates) gfPopType = "2"; } String sExtraCondition = ""; if(!allowFutureDates){ sExtraCondition = " || isForbiddenFutureDate(this,false)"; } if(!allowPastDates){ sExtraCondition = " || isForbiddenPastDate(this,false)"; } return "<span style='white-space: nowrap'><input type='text' maxlength='10' class='text' id='"+sName+"' name='"+sName+"' value='"+sValue+"' size='10' onblur='if(!checkDate(this)"+sExtraCondition+"){dateError(this);}else{}'>"+ "&nbsp;<img height='"+imageSize+"' name='popcal' style='vertical-align:middle;' onclick='gfPop"+gfPopType+".fPopCalendar(document."+sForm+"."+sName+");return false;' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"'></a>"+ "&nbsp;<img height='"+imageSize+"' style='vertical-align:middle;' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("Web","PutToday",sWebLanguage)+"' onclick='getToday(document."+sForm+"."+sName+");'></span>"; } //--- WRITE DATE FIELD WITH DELETE ------------------------------------------------------------ public static String writeDateFieldWithDelete(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR){ return writeDateFieldWithDelete(sName,sForm,sValue,allowPastDates,allowFutureDates,sWebLanguage,sCONTEXTDIR,""); } public static String writeDateFieldWithDelete(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR, String sExtraOnBlur){ String gfPopType = "1"; // default if(allowPastDates && allowFutureDates){ gfPopType = "1"; } else{ if(allowFutureDates) gfPopType = "3"; else if(allowPastDates) gfPopType = "2"; } String sExtraCondition = ""; if(!allowFutureDates){ sExtraCondition = " || isForbiddenFutureDate(this,false)"; } if(!allowPastDates){ sExtraCondition = " || isForbiddenPastDate(this,false)"; } return "<span style='white-space: nowrap'><input type='text' maxlength='10' class='text' id='"+sName+"' name='"+sName+"' value='"+sValue+"' size='10' onblur='if(!checkDate(this)"+sExtraCondition+"){dateError(this);}else{"+sExtraOnBlur+"}'>" +"&nbsp;<img name='popcal' style='vertical-align:-1px;' onclick='gfPop"+gfPopType+".fPopCalendar(document."+sForm+"."+sName+");return false;' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"'></a>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("web","PutToday",sWebLanguage)+"' onclick='getToday(document."+sForm+"."+sName+");'>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_delete.png' alt='"+getTranNoLink("web","clear",sWebLanguage)+"' onclick=\"document."+sForm+"."+sName+".value='';\"></span>"; } //--- NEW WRITE DATE TIME FIELD --------------------------------------------------------------- public static String newWriteDateTimeField(String sName, java.util.Date dValue, String sWebLanguage, String sCONTEXTDIR){ return "<span style='white-space: nowrap'><input id='"+sName+"' type='text' maxlength='10' class='text' name='"+sName+"' value='"+getSQLDate(dValue)+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";}'>" +"&nbsp;<img id='"+sName+"_popcal' name='popcal' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"' onclick='gfPop1.fPopCalendar($(\""+sName+"\"));return false;'>" +"&nbsp;<img id='"+sName+"_today' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","putToday",sWebLanguage))+"' onclick=\"putTime($('"+sName+"Time'));getToday($('"+sName+"'));\">" +"&nbsp;"+writeTimeField(sName+"Time", formatSQLDate(dValue, "HH:mm")) +"&nbsp;"+getTran(null,"web.occup", "medwan.common.hour", sWebLanguage)+"</span>"; } //--- NEW WRITE DATE TIME FIELD --------------------------------------------------------------- public static String newWriteDateField(String sName, java.util.Date dValue, String sWebLanguage, String sCONTEXTDIR){ return "<span style='white-space: nowrap'><input id='"+sName+"' type='text' maxlength='10' class='text' name='"+sName+"' value='"+getSQLDate(dValue)+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";}'>" +"&nbsp;<img name='popcal' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"' onclick='gfPop1.fPopCalendar($(\""+sName+"\"));return false;'>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","putToday",sWebLanguage))+"' onclick=\"getToday($('"+sName+"'));\"></span>"; } //--- NEW WRITE DATE TIME FIELD --------------------------------------------------------------- public static String newWriteDateField(String sName, java.util.Date dValue, String sWebLanguage, String sCONTEXTDIR, String onBlur){ return "<span style='white-space: nowrap'><input id='"+sName+"' type='text' maxlength='10' class='text' name='"+sName+"' value='"+getSQLDate(dValue)+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";};"+onBlur+"' onfocus='"+onBlur+"'>" +"&nbsp;<img name='popcal' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"' onclick='gfPop1.fPopCalendar($(\""+sName+"\"));return false;'>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","putToday",sWebLanguage))+"' onclick=\"getToday($('"+sName+"'));\"></span>"; } //--- PLANNING DATE TIME FIELD ---------------------------------------------------------------- public static String planningDateTimeField(String sName, String dValue, String sWebLanguage, String sCONTEXTDIR){ return "<span style='white-space: nowrap'><input id='"+sName+"' type='text' maxlength='10' class='text' name='"+sName+"' value='"+dValue+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";}'>" +"&nbsp;<img name='popcal' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"' onclick='gfPop1.fPopCalendar($(\""+sName+"\"));return false;'>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","putToday",sWebLanguage))+"' onclick=\"getToday($('"+sName+"'));\"></span>"; } //--- WRITE DATEE FIELD WITHOUT TODAY --------------------------------------------------------- public static String writeDateFieldWithoutToday(String sName, String sForm, String sValue, boolean allowPastDates, boolean allowFutureDates, String sWebLanguage, String sCONTEXTDIR){ String gfPopType = "1"; // default if(allowPastDates && allowFutureDates){ gfPopType = "1"; } else{ if(allowFutureDates) gfPopType = "3"; else if(allowPastDates) gfPopType = "2"; } return "<span style='white-space: nowrap'><input type='text' maxlength='10' class='text' id='"+sName+"' name='"+sName+"' value='"+sValue+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";}'>" +"&nbsp;<img name='popcal' style='vertical-align:-1px;' onclick='gfPop"+gfPopType+".fPopCalendar(document."+sForm+"."+sName+");return false;' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+HTMLEntities.htmlentities(getTran(null,"Web","Select",sWebLanguage))+"'></a></span>"; } public static String checkPermission(HttpServletResponse response, String sScreen, String sPermission, User activeUser, boolean screenIsPopup, String sCONTEXTPATH){ String s = ScreenHelper.checkPermission(sScreen,sPermission,activeUser,false,sCONTEXTPATH); if(s.length()>0) { try { response.sendRedirect(sCONTEXTPATH+"/util/noaccess.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "<script>alert('"+sCONTEXTPATH+"/util/noaccess.jsp');</script>"; } return s; } public static String checkPermissionNoSA(HttpServletResponse response, String sScreen, String sPermission, User activeUser, boolean screenIsPopup, String sCONTEXTPATH){ String s = ScreenHelper.checkPermissionNoSA(sScreen,sPermission,activeUser,false,sCONTEXTPATH); if(s.length()>0) { try { response.sendRedirect(sCONTEXTPATH+"/util/noaccess.jsp"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "<script>alert('"+sCONTEXTPATH+"/util/noaccess.jsp');</script>"; } return s; } //--- CHECK PERMISSION ------------------------------------------------------------------------ public static String checkPermission(String sScreen, String sPermission, User activeUser, boolean screenIsPopup, String sAPPFULLDIR){ sPermission = sPermission.toLowerCase(); String jsAlert = "Error in checkPermission : no screen specified !"; if(sScreen.trim().length() > 0){ if(Application.isDisabled(sScreen)){ jsAlert = "Application is disabled : '"+sScreen+"'"; } else if(activeUser!=null && activeUser.getParameter("sa")!=null && activeUser.getParameter("sa").length() > 0){ jsAlert = ""; } else{ // screen and permission specified if(activeUser!=null && sPermission.length() > 0 && !sPermission.equals("all")){ if(sPermission.equals("none")){ jsAlert = ""; } else if(activeUser.getAccessRight(sScreen+"."+sPermission)){ jsAlert = ""; } } // no permission specified -> interprete as all permissions required // Managing a page, means you can add, edit and delete. else if(activeUser!=null && activeUser.getAccessRight(sScreen+".edit") && activeUser.getAccessRight(sScreen+".add") && activeUser.getAccessRight(sScreen+".delete")){ jsAlert = ""; } if(jsAlert.length() > 0){ String sMessage = getTranNoLink("web","nopermission",activeUser==null || activeUser.person==null?"en":activeUser.person.language); jsAlert = "<script>"+ "var popupUrl = '"+sAPPFULLDIR+"/_common/search/okPopup.jsp?ts="+getTs()+"&labelValue="+sMessage; // display permission when in Debug mode if(Debug.enabled) jsAlert+= " --> "+sScreen+(sPermission.length()==0?"":"."+sPermission); jsAlert+= "';"+ "var modalities = 'dialogWidth:266px;dialogHeight:143px;center:yes;scrollbars:no;resizable:no;status:no;location:no;';"+ "var answer = (window.showModalDialog)?window.showModalDialog(popupUrl,\"\",modalities):window.confirm(\""+sMessage+"\");"+ (screenIsPopup?"window.close();":"window.history.go(-1);")+ "</script>"; } } } return jsAlert; } //--- CHECK PERMISSION ------------------------------------------------------------------------ public static String checkPermissionNoSA(String sScreen, String sPermission, User activeUser, boolean screenIsPopup, String sAPPFULLDIR){ sPermission = sPermission.toLowerCase(); String jsAlert = "Error in checkPermission : no screen specified !"; if(sScreen.trim().length() > 0){ if(Application.isDisabled(sScreen)){ jsAlert = "Application is disabled : '"+sScreen+"'"; } else if(activeUser!=null && activeUser.getParameter("sa")!=null && activeUser.getParameter("sa").length() > 0){ jsAlert = ""; } else{ // screen and permission specified if(activeUser!=null && sPermission.length() > 0 && !sPermission.equals("all")){ if(sPermission.equals("none")){ jsAlert = ""; } else if(activeUser.getAccessRightNoSA(sScreen+"."+sPermission)){ jsAlert = ""; } } // no permission specified -> interprete as all permissions required // Managing a page, means you can add, edit and delete. else if(activeUser!=null && activeUser.getAccessRightNoSA(sScreen+".edit") && activeUser.getAccessRightNoSA(sScreen+".add") && activeUser.getAccessRightNoSA(sScreen+".delete")){ jsAlert = ""; } if(jsAlert.length() > 0){ String sMessage = getTranNoLink("web","nopermission",activeUser==null || activeUser.person==null?"en":activeUser.person.language); jsAlert = "<script>"+ "var popupUrl = '"+sAPPFULLDIR+"/_common/search/okPopup.jsp?ts="+getTs()+"&labelValue="+sMessage; // display permission when in Debug mode if(Debug.enabled) jsAlert+= " --> "+sScreen+(sPermission.length()==0?"":"."+sPermission); jsAlert+= "';"+ "var modalities = 'dialogWidth:266px;dialogHeight:143px;center:yes;scrollbars:no;resizable:no;status:no;location:no;';"+ "var answer = (window.showModalDialog)?window.showModalDialog(popupUrl,\"\",modalities):window.confirm(\""+sMessage+"\");"+ (screenIsPopup?"window.close();":"window.history.go(-1);")+ "</script>"; } } } return jsAlert; } //--- CHECK TRANSACTION PERMISSION ------------------------------------------------------------ static public String checkTransactionPermission(TransactionVO transaction, User activeUser, boolean screenIsPopup, String sAPPFULLDIR){ String jsAlert = ""; if(checkString(transaction.getItemValue("be.mxs.common.model.vo.healthrecord.IConstants.ITEM_TYPE_PRIVATETRANSACTION")).equalsIgnoreCase("1")){ try{ if(!(transaction.getUser().getUserId()+"").equalsIgnoreCase(activeUser.userid)){ String sMessage = getTranNoLink("web","privatetransactionerror",activeUser.person.language); jsAlert = "<script>"+(screenIsPopup?"window.confirm('"+sMessage+"');window.close();":"window.confirm('"+sMessage+"');window.history.go(-1);")+"</script>"; } } catch(Exception e){ e.printStackTrace(); } } return jsAlert; } public static boolean executeQuery(PreparedStatement ps) { try { ps.execute(); return true; } catch(Exception e) { return false; } } //--- CHECK PERMISSION ------------------------------------------------------------------------ public static String checkPrestationToday(String sPersonId, String sAPPFULLDIR, boolean screenIsPopup, User activeUser, TransactionVO transaction){ String jsAlert = ""; String sMessage =""; String sEncounterUid=""; String sPrestationCode = MedwanQuery.getInstance().getConfigString(transaction.getTransactionType()+".requiredPrestation",""); String sPrestationClass = MedwanQuery.getInstance().getConfigString(transaction.getTransactionType()+".requiredPrestationClass",""); int nInvoicable = MedwanQuery.getInstance().getConfigInt(transaction.getTransactionType()+".requiredInvoicable",0); if(transaction.getTransactionId()<0 && MedwanQuery.getInstance().getConfigInt("negativePatientBalanceAllowed",1)==0){ Balance balance = Balance.getActiveBalance(sPersonId); double saldo = Balance.getPatientBalance(sPersonId); if(saldo<balance.getMinimumBalance()){ sMessage = getTranNoLink("web","notpermittedwithnegativebalance",activeUser.person.language); } } if(sMessage.length()==0) { Encounter encounter = Encounter.getActiveEncounter(sPersonId); if(encounter!=null){ sEncounterUid=encounter.getUid(); } if(sEncounterUid.length()>0 && sEncounterUid.split("\\.").length==2 && transaction.getTransactionId()<0 && MedwanQuery.getInstance().getConfigInt("activateOutpatientConsultationPrestationCheck",0)==1){ if(checkString(sPrestationCode).length() > 0){ Prestation prestation = Prestation.getByCode(sPrestationCode); if(prestation.getUid()!=null && prestation.getUid().split("\\.").length==2){ try{ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); String sQuery = "select * from oc_debets"+ " where oc_debet_date>=? and oc_debet_encounteruid=? and oc_debet_prestationuid=?"; if(MedwanQuery.getInstance().getConfigInt(transaction.getTransactionType()+".requiredPrestation.invoiced",0)==1){ sQuery = "select * from oc_debets"+ " where oc_debet_date>=? and oc_debet_encounteruid=? and oc_debet_prestationuid=?"+ " and oc_debet_patientinvoiceuid like '%.%'"; } PreparedStatement ps = conn.prepareStatement(sQuery); ps.setDate(1,new java.sql.Date(ScreenHelper.parseDate(ScreenHelper.stdDateFormat.format(new java.util.Date())).getTime())); ps.setString(2,sEncounterUid); ps.setString(3,prestation.getUid()); ResultSet rs = ps.executeQuery(); if(!rs.next()){ sMessage = getTranNoLink("web","noactiveprestation",activeUser.person.language)+" `"+prestation.getCode()+": "+prestation.getDescription()+"`"; } rs.close(); ps.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } } } } if(transaction.getTransactionId()<0) { if(nInvoicable==1){ //Check if invoicing conditions have been met if(Encounter.getActiveEncounter(sPersonId)==null || Insurance.getMostInterestingInsuranceForPatient(sPersonId)==null){ sMessage = getTranNoLink("web","notinvoicable",activeUser.person.language); } } if(checkString(sPrestationClass).length() > 0){ try{ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); String sQuery = "select * from oc_debets a, oc_prestations b where a.oc_debet_date>=? and a.oc_debet_encounteruid=? and b.oc_prestation_objectid=replace(a.oc_debet_prestationuid,'"+MedwanQuery.getInstance().getConfigString("serverId","1")+".','') and b.oc_prestation_class=?"; if(MedwanQuery.getInstance().getConfigInt(transaction.getTransactionType()+".requiredPrestationClass.invoiced",0)==1){ sQuery = "select * from oc_debets a, oc_prestations b where a.oc_debet_date>=? and a.oc_debet_encounteruid=? and a.oc_debet_patientinvoiceuid like '%.%' and b.oc_prestation_objectid=replace(a.oc_debet_prestationuid,'"+MedwanQuery.getInstance().getConfigString("serverId","1")+".','') and b.oc_prestation_class=?"; } PreparedStatement ps = conn.prepareStatement(sQuery); ps.setDate(1,new java.sql.Date(ScreenHelper.parseDate(ScreenHelper.stdDateFormat.format(new java.util.Date())).getTime())); ps.setString(2,sEncounterUid); ps.setString(3,sPrestationClass); ResultSet rs = ps.executeQuery(); if(!rs.next()){ sMessage = getTranNoLink("web","noactiveprestationclass",activeUser.person.language)+" `"+getTran(null,"prestation.class",sPrestationClass,activeUser.person.language)+"`"; } rs.close(); ps.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } } } } if(checkString(sMessage).length()>0){ jsAlert = "<script>"+ "var popupUrl = '"+sAPPFULLDIR+"/_common/search/okPopup.jsp?ts="+getTs()+"&labelValue="+sMessage; jsAlert+= "';"+ " var modalities = 'dialogWidth:266px;dialogHeight:143px;center:yes;scrollbars:no;resizable:no;status:no;location:no;';"+ " var answer = (window.showModalDialog)?window.showModalDialog(popupUrl,\"\",modalities):window.confirm(\""+sMessage+"\");"+ (screenIsPopup?"window.close();":"window.history.go(-1);")+ "</script>"; } else if (transaction.getTransactionId()<0 && MedwanQuery.getInstance().getConfigInt("activateOutpatientConsultationPrestationCheck",0)==1 && sPrestationCode.length()>0){ Prestation prestation = Prestation.getByCode(sPrestationCode); if(prestation!=null){ sMessage = getTranNoLink("web","noactiveprestation",activeUser.person.language)+" `"+prestation.getCode()+": "+prestation.getDescription()+"`"; jsAlert = "<script>"+(screenIsPopup?"window.close();":"window.history.go(-1);")+ "var popupUrl = '"+sAPPFULLDIR+"/_common/search/okPopup.jsp?ts="+getTs()+"&labelValue="+sMessage; jsAlert+= "';"+ " var modalities = 'dialogWidth:266px;dialogHeight:143px;center:yes;scrollbars:no;resizable:no;status:no;location:no;';"+ " var answer = (window.showModalDialog)?window.showModalDialog(popupUrl,\"\",modalities):window.confirm(\""+sMessage+"\");"+ "</script>"; } } else if (transaction.getTransactionId()<0 && MedwanQuery.getInstance().getConfigInt("activateOutpatientConsultationPrestationCheck",0)==1 && sPrestationClass.length()>0){ sMessage = getTranNoLink("web","noactiveprestationclass",activeUser.person.language)+" `"+getTran(null,"prestation.class",sPrestationClass,activeUser.person.language)+"`"; jsAlert = "<script>"+(screenIsPopup?"window.close();":"window.history.go(-1);")+ "var popupUrl = '"+sAPPFULLDIR+"/_common/search/okPopup.jsp?ts="+getTs()+"&labelValue="+sMessage; jsAlert+= "';"+ " var modalities = 'dialogWidth:266px;dialogHeight:143px;center:yes;scrollbars:no;resizable:no;status:no;location:no;';"+ " var answer = (window.showModalDialog)?window.showModalDialog(popupUrl,\"\",modalities):window.confirm(\""+sMessage+"\");"+ "</script>"; } else if (transaction.getTransactionId()<0 && MedwanQuery.getInstance().getConfigInt("activateOutpatientConsultationPrestationCheck",0)==1 && nInvoicable==1){ sMessage = getTranNoLink("web","notinvoicable",activeUser.person.language); jsAlert = "<script>"+(screenIsPopup?"window.close();":"window.history.go(-1);")+ "var popupUrl = '"+sAPPFULLDIR+"/_common/search/okPopup.jsp?ts="+getTs()+"&labelValue="+sMessage; jsAlert+= "';"+ " var modalities = 'dialogWidth:266px;dialogHeight:143px;center:yes;scrollbars:no;resizable:no;status:no;location:no;';"+ " var answer = (window.showModalDialog)?window.showModalDialog(popupUrl,\"\",modalities):window.confirm(\""+sMessage+"\");"+ "</script>"; } return jsAlert; } //--- WRITE SEARCH BUTTON --------------------------------------------------------------------- public static String writeSearchButton(String sButtonName, String sLabelType, String sVarCode, String sVarText, String sShowID, String sWebLanguage, String sCONTEXTDIR){ return "<img src='"+sCONTEXTDIR+"/_img/icons/icon_search.png' id='"+sButtonName+"' class='link' alt='"+getTranNoLink("Web","select",sWebLanguage)+"'" +"onclick='openPopup(\"_common/search/searchScreen.jsp&LabelType="+sLabelType+"&VarCode="+sVarCode+"&VarText="+sVarText+"&ShowID="+sShowID+"\");'>" +"&nbsp;<img src='"+sCONTEXTDIR+"/_img/icons/icon_delete.png' class='link' alt='"+getTranNoLink("Web","clear",sWebLanguage)+"' onclick=\""+sVarCode+".value='';"+sVarText+".value='';\">"; } public static String writeSearchButton(String sButtonName, String sLabelType, String sVarCode, String sVarText, String sShowID,String sWebLanguage, String defaultValue, String sCONTEXTDIR){ return "<img src='"+sCONTEXTDIR+"/_img/icons/icon_search.png' id='"+sButtonName+"' class='link' alt='"+getTranNoLink("Web","select",sWebLanguage)+"'" +" onclick='openPopup(\"_common/search/searchScreen.jsp&LabelType="+sLabelType+"&VarCode="+sVarCode+"&VarText="+sVarText+"&ShowID="+sShowID+"&DefaultValue="+defaultValue+"\");'>" +"&nbsp;<img src='"+sCONTEXTDIR+"/_img/icons/icon_delete.png' class='link' alt='"+getTranNoLink("Web","clear",sWebLanguage)+"' onclick=\""+sVarCode+".value='';"+sVarText+".value='';\">"; } //--- WRITE SERVICE BUTTON -------------------------------------------------------------------- public static String writeServiceButton(String sButtonName, String sVarCode, String sVarText,String sWebLanguage, String sCONTEXTDIR){ return writeServiceButton(sButtonName,sVarCode,sVarText,false,sWebLanguage,sCONTEXTDIR); } public static String writeServiceButton(String sButtonName, String sVarCode, String sVarText, boolean onlySelectContractWithDivision, String sWebLanguage, String sCONTEXTDIR){ return "<img style='vertical-align: middle' src='"+sCONTEXTDIR+"/_img/icons/icon_search.png' id='"+sButtonName+"' class='link' alt='"+getTranNoLink("Web","select",sWebLanguage)+"'" +"onclick='openPopup(\"_common/search/searchService.jsp&VarCode="+sVarCode+"&VarText="+sVarText+"&onlySelectContractWithDivision="+onlySelectContractWithDivision+"\");'>" +"&nbsp;<img style='vertical-align: middle' src='"+sCONTEXTDIR+"/_img/icons/icon_delete.png' class='link' alt='"+getTranNoLink("Web","clear",sWebLanguage)+"' onclick=\"document.getElementsByName('"+sVarCode+"')[0].value='';document.getElementsByName('"+sVarText+"')[0].value='';\">"; } public static void saveTransactionItemTranslation(String sItemTypeId,String sTranslationId) throws SQLException{ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); PreparedStatement ps = conn.prepareStatement("select modifier from transactionitems where itemtypeid=?"); ps.setString(1, sItemTypeId); ResultSet rs = ps.executeQuery(); if(!rs.next()){ String modifier = checkString(rs.getString("modifier")); if(!modifier.contains(";"+sTranslationId)){ String[] modifierparts = modifier.split(";"); modifier=""; if(modifierparts.length>=2){ for(int n=0;n<modifierparts.length;n++){ if(n==0){ modifier+=modifierparts[0]; } else if(n==1){ modifier+=";"+sTranslationId; } else { modifier+=";"+modifierparts[n]; } } } else{ modifier+=modifierparts[0]+";"+sTranslationId; } rs.close(); ps.close(); ps = conn.prepareStatement("update transactionitems set modifier=? where itemtypeid=?"); ps.setString(1, modifier); ps.setString(2, sItemTypeId); ps.execute(); } } rs.close(); ps.close(); conn.close(); } public static void saveTransactionItemTranslation(String sTransactionTypeId, String sItemTypeId,String sTranslationId){ try{ Connection conn = MedwanQuery.getInstance().getOpenclinicConnection(); PreparedStatement ps = conn.prepareStatement("select modifier from transactionitems where transactiontypeid=? and itemtypeid=?"); ps.setString(1, sTransactionTypeId); ps.setString(2, sItemTypeId); ResultSet rs = ps.executeQuery(); if(rs.next()){ String modifier = checkString(rs.getString("modifier")); if(!modifier.contains(";"+sTranslationId)){ String[] modifierparts = modifier.split(";"); modifier=""; if(modifierparts.length>=2){ for(int n=0;n<modifierparts.length;n++){ if(n==0){ modifier+=modifierparts[0]; } else if(n==1){ modifier+=";"+sTranslationId; } else { modifier+=";"+modifierparts[n]; } } } else{ modifier+=modifierparts[0]+";"+sTranslationId; } rs.close(); ps.close(); ps = conn.prepareStatement("update transactionitems set modifier=? where transactiontypeid=? and itemtypeid=?"); ps.setString(1, modifier); ps.setString(2, sTransactionTypeId); ps.setString(3, sItemTypeId); ps.execute(); } } rs.close(); ps.close(); conn.close(); } catch(Exception e){ e.printStackTrace(); } } public static String writeDefaultCheckBox(TransactionVO transaction,HttpServletRequest request,String sLabelType, String sName, String sWebLanguage, String sEvent){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else { StringBuffer s = new StringBuffer(); s.append("<input "+setRightClickMini(request.getSession(), sName)+" "+sEvent+" type='checkbox' id='"+sName+"' value='1'"); s.append(" name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue().equalsIgnoreCase("1")){ s.append(" checked"); } s.append(">"); return s.toString(); } } public static String writeDefaultCheckBox(TransactionVO transaction,HttpServletRequest request,String sValue, String sName, String sEvent){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else { StringBuffer s = new StringBuffer(); s.append("<input "+setRightClickMini(request.getSession(), sName)+" "+sEvent+" type='checkbox' id='"+sName+"' value='"+sValue+"'"); s.append(" name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue().equalsIgnoreCase(sValue)){ s.append(" checked"); } s.append(">"); return s.toString(); } } public static String writeDefaultCheckBoxes(TransactionVO transaction,HttpServletRequest request,String sLabelType, String sName, String sWebLanguage, boolean sorted){ return writeDefaultCheckBoxes(transaction, request, sLabelType, sName, sWebLanguage, sorted, ""); } public static String writeDefaultCheckBoxes(TransactionVO transaction,HttpServletRequest request,String sLabelType, String sName, String sWebLanguage, boolean sorted, String sEvent){ return writeDefaultCheckBoxes(transaction, request, sLabelType, sName, sWebLanguage, sorted, sEvent,""); } public static String writeDefaultCheckBoxes(TransactionVO transaction,HttpServletRequest request,String sLabelType, String sName, String sWebLanguage, boolean sorted, String sEvent,String separator){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ String sSelected = transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue(); StringBuffer s = new StringBuffer(); s.append(writeDefaultHiddenInput(transaction, sName)); if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ saveTransactionItemTranslation(transaction.getTransactionType(), "be.mxs.common.model.vo.healthrecord.IConstants."+sName, sLabelType); s.append("<img width='16' src='"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/_img/icons/icon_plus.png' onclick='window.open(\""+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1\",\"popup\",\"toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no\")'/>"); } Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } s.append("<label style='display: inline-block;'><input "+setRightClickMini(request.getSession(), sName)+" "+(checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")?"title='"+sName+"' ":"")+sEvent+" onclick='updateMultiCheckbox(this,\""+sName+"\",\""+sLabelID+"\")' type='checkbox' name='"+sName+"."+sLabelID+"' id='"+sName+"."+sLabelID+"' value='"+sLabelID+"'"); if(arrayContains(sSelected,sLabelID,";")){ s.append(" checked"); } s.append(">"+sLabelValue+"</label> "+(it.hasNext()?separator:"")); } } } return s.toString(); } } public static String writeDefaultRadioButtons(TransactionVO transaction,HttpServletRequest request,String sLabelType, String sName, String sWebLanguage, boolean sorted, String sEvent, String separator){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ String sSelected = transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue(); StringBuffer s = new StringBuffer(); s.append(writeDefaultHiddenInput(transaction, sName)); if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ saveTransactionItemTranslation(transaction.getTransactionType(), "be.mxs.common.model.vo.healthrecord.IConstants."+sName, sLabelType); s.append("<img width='16' src='"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/_img/icons/icon_plus.png' onclick='window.open(\""+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1\",\"popup\",\"toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no\")'/>"); } Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } s.append("<label style='display: inline-block;'><input "+setRightClickMini(request.getSession(), sName)+" "+sEvent+" ondblclick='uncheckRadio(this)' onclick='document.getElementById(\""+sName+"\").value=\""+sLabelID+";\";' type='radio' name='"+sName+".radio' id='"+sName+"."+sLabelID+"' value='"+sLabelID+"'"); if(arrayContains(sSelected,sLabelID,";")){ s.append(" checked"); } s.append(">"+sLabelValue+"</label> "+separator); } } } return s.toString(); } } public static String writeDefaultNomenclatureField(HttpSession session, TransactionVO transaction, String sName, String type, int cols,String language,String contextPath, String sEvent){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ if(session!=null && checkString((String)session.getAttribute("editmode")).equalsIgnoreCase("1")){ saveTransactionItemTranslation(transaction.getTransactionType(), "be.mxs.common.model.vo.healthrecord.IConstants."+sName, type); } String sItemValue=transaction.getItemValue("be.mxs.common.model.vo.healthrecord.IConstants."+sName); StringBuffer s = new StringBuffer(); s.append("<input class='text' "+setRightClick(session, sName)+" type='text' name='"+sName+"_text' id='"+sName+"_text' READONLY size='"+cols+"' title='"+getTranNoLink(type,sItemValue,language)+"' value='"+getTranNoLink(type,sItemValue,language)+"'>"); s.append("<img src='"+contextPath+"/_img/icons/icon_search.png' class='link' alt='"+getTranNoLink("Web","select",language)+"' onclick='searchGeneralNomenclature(\""+sName+"_code\",\""+sName+"_text\",\""+type+"\");'>"); s.append("<img src='"+contextPath+"/_img/icons/icon_delete.png' class='link' alt='"+getTranNoLink("Web","clear",language)+"' onclick='document.getElementById(\""+sName+"_code\").value=\"\";document.getElementById(\""+sName+"_text\").value=\"\";'>"); s.append("<input "+sEvent+" type='hidden' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' id='"+sName+"_code' value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"'>"); return s.toString(); } } public static String writeDefaultTextArea(HttpSession session, TransactionVO transaction, String sName,int cols, int rows){ boolean bMandatory=false; if(sName.startsWith("!")) { sName=sName.substring(1); bMandatory=true; } if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<textarea onkeyup='resizeTextarea(this,10);limitChars(this,5000);' "); s.append(setRightClick(session,sName)); if(bMandatory) { s.append(" "+SH.cdm()+" "); } s.append(" class='text' cols='"+cols+"' rows='"+rows+"' id='"+sName+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'>"); s.append(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"</textarea>"); return s.toString(); } } public static String writeDefaultTextInput(HttpSession session, TransactionVO transaction, String sName,int cols){ return writeDefaultTextInput(session, transaction, sName, cols, ""); } public static String writeDefaultTextInput(HttpSession session, TransactionVO transaction, String sName,int cols,String event){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session,sName)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' "+event+"/>"); return s.toString(); } } public static String writeDefaultTextInputNoClass(HttpSession session, TransactionVO transaction, String sName,int cols,String event){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(" size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' "+event+"/>"); return s.toString(); } } public static java.util.Date getEndOfMonth(java.util.Date date){ try { java.util.Date newdate = new SimpleDateFormat("dd/MM/yyyy").parse("01/"+new SimpleDateFormat("MM/yyyy").format(date)); newdate = new java.util.Date(newdate.getTime()+getTimeDay()*32); newdate = new SimpleDateFormat("dd/MM/yyyy").parse("01/"+new SimpleDateFormat("MM/yyyy").format(newdate)); newdate = new java.util.Date(newdate.getTime()-getTimeSecond()); return newdate; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static java.util.Date getBeginOfMonth(java.util.Date date){ try { return new SimpleDateFormat("dd/MM/yyyy").parse("01/"+new SimpleDateFormat("MM/yyyy").format(date)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public static java.util.Date getBeginOfNextMonth(java.util.Date date){ return getBeginOfMonth(new java.util.Date(getBeginOfMonth(date).getTime()+32*getTimeDay())); } public static String writeDefaultTextInputSticky(HttpSession session, TransactionVO transaction, String sName,int cols){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ String sValue=transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue(); if(sValue.length()==0) { AdminPerson activePatient = (AdminPerson)session.getAttribute("activePatient"); if(activePatient!=null) { sValue=MedwanQuery.getInstance().getLastItemValue(Integer.parseInt(activePatient.personid), "be.mxs.common.model.vo.healthrecord.IConstants."+sName); } } StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session,sName)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+sValue+"'/>"); return s.toString(); } } public static String writeDefaultTextInputSticky(HttpSession session, TransactionVO transaction, String sName,int cols,String onblur){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ String sValue=transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue(); if(sValue.length()==0) { AdminPerson activePatient = (AdminPerson)session.getAttribute("activePatient"); if(activePatient!=null) { sValue=MedwanQuery.getInstance().getLastItemValue(Integer.parseInt(activePatient.personid), "be.mxs.common.model.vo.healthrecord.IConstants."+sName); } } StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session,sName)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+sValue+"'"+(onblur.length()>0?" onblur=\""+onblur+"\"":"")+"/>"); return s.toString(); } } public static String writeDefaultTextInputCenter(HttpSession session, TransactionVO transaction, String sName,int cols){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClickCenter(session,sName)); s.append(" class='textcenter' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"'/>"); return s.toString(); } } public static String writeDefaultTextInputReadonly(HttpSession session, TransactionVO transaction, String sName,int cols){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input readonly type='text' id='"+sName+"' "); //s.append(setRightClick(session,sName)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"'/>"); return s.toString(); } } public static String writeDefaultTextInputReadonly(HttpSession session, TransactionVO transaction, String sName,int cols, String sOnEvent){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input readonly type='text' id='"+sName+"' "); //s.append(setRightClick(session,sName)); s.append(" size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' "+sOnEvent+"/>"); return s.toString(); } } public static String writeDefaultDateInput(HttpSession session, TransactionVO transaction, String sName, String language,String contextpath){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session,sName)); s.append(" class='text' size='12' maxlength='10' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" onblur='checkDate(this);' value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"'/>"); s.append("<script>writeMyDate('"+sName+"', '"+contextpath+"/_img/icons/icon_agenda.png', '"+ScreenHelper.getTranNoLink("web","PutToday",language)+"');</script>"); return s.toString(); } } public static String writeDefaultDateInput(HttpSession session, TransactionVO transaction, String sName, String language,String contextpath, String event){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session,sName)); s.append(" class='text' size='12' maxlength='10' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" onblur='checkDate(this);' "+event+" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"'/>"); s.append("<script>writeMyDate('"+sName+"', '"+contextpath+"/_img/icons/icon_agenda.png', '"+ScreenHelper.getTranNoLink("web","PutToday",language)+"');</script>"); return s.toString(); } } public static String writeDefaultKeywordField(HttpSession session, TransactionVO transaction, String sName,String keywordstype, String keywordsdiv,String contextpath,String language, HttpServletRequest request){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName+"CODES")==null){ return("Unknown items: <br/>"+ "<a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"CODES\");'>"+sName+"CODES</a><br/>"+ "<a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"TEXT\");'>"+sName+"TEXT</a>" ); } else{ String sKeywords=getKeywordsHTML(transaction,ScreenHelper.ITEM_PREFIX+sName+"CODES",sName+"IDS",sName+"CODES",language,contextpath); StringBuffer s = new StringBuffer(); s.append("<table width='100%' cellspacing='0' cellpadding='0'>"); s.append("<tr onclick='selectKeywords(\""+sName+"CODES\",\""+sName+"IDS\",\""+keywordstype+"\",\""+keywordsdiv+"\",\"keywords_title_"+sName+"\",\"keywords_key_"+sName+"\",event.clientY)'>"); s.append("<td>"); s.append(writeDefaultTextArea(session, (TransactionVO)transaction, sName+"TEXT", 45, 1)); s.append("</td>"); s.append("<td width='40' nowrap style='text-align:center'>"); s.append("<img width='16' id='keywords_key_"+sName+"' class='link' src='"+contextpath+"/_img/themes/default/keywords.jpg'/>"); if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ saveTransactionItemTranslation(transaction.getTransactionType(), "be.mxs.common.model.vo.healthrecord.IConstants."+sName, keywordstype); s.append("<img width='16' src='"+contextpath+"/_img/icons/icon_plus.png' onclick='window.open(\""+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+keywordstype+"&find=1\",\"popup\",\"toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no\")'/>"); } s.append("</td>"); s.append("<td width='50%' style='vertical-align:top;'>"); s.append("<div "+setRightClickMini(session, sName+"CODES")+" id='"+sName+"IDS'>"+(sKeywords.trim().length()==0?"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;":sKeywords)+"</div>"); s.append(writeDefaultHiddenInput((TransactionVO)transaction, sName+"CODES")); s.append("</td>"); s.append("</tr>"); s.append("</table>"); return s.toString(); } } public static String writeDefaultHiddenInput(TransactionVO tran, String sName){ if(tran.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+tran.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='hidden' id='"+sName+"' "); s.append(" name='currentTransactionVO.items.<ItemVO[hashCode="+tran.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'"); s.append(" value='"+tran.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue().replaceAll("'", "´")+"'/>"); return s.toString(); } } public static String writeDefaultSelect(HttpServletRequest request,TransactionVO transaction, String sName,String type, String language, String sEvent){ return writeDefaultSelect(request, transaction, sName, type, language, sEvent, ""); } public static String writeDefaultSelect(HttpServletRequest request,TransactionVO transaction, String sName,String type, String language, String sEvent,String sDefault){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); String itemValue=checkString(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()); if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ saveTransactionItemTranslation(transaction.getTransactionType(), "be.mxs.common.model.vo.healthrecord.IConstants."+sName, type); s.append("<select style='vertical-align: top' title='"+sName+"' "+setRightClickMini(request.getSession(),sName)+" name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' style='border:2px solid black; border-style: dotted' id='"+sName+"' onclick='window.open(\""+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+type+"&find=1\",\"popup\",\"toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no\")'>"); s.append(" <option/>"); s.append(writeSelect(request,type,itemValue.length()==0 && checkString(sDefault).length()>0?sDefault:itemValue,language)); s.append("</select>"); } else{ s.append("<select style='vertical-align: top' "+(request==null?"":setRightClickNoClass(request.getSession(),sName)+" ")+sEvent+" class='text' id='"+sName+"' "); s.append(" name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'>"); s.append(" <option/>"); s.append(writeSelect(request,type,itemValue.length()==0 && checkString(sDefault).length()>0?sDefault:itemValue,language)); s.append(" </select>"); } return s.toString(); } } public static String writeDefaultToggle(HttpServletRequest request,TransactionVO transaction, String sName,String type, String language, String sEvent){ return writeDefaultToggle(request, transaction, sName, type, language, sEvent, ""); } public static String writeDefaultToggle(HttpServletRequest request,TransactionVO transaction, String sName,String type, String language, String sEvent,String sDefault){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); String itemValue=checkString(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()); if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ saveTransactionItemTranslation(transaction.getTransactionType(), "be.mxs.common.model.vo.healthrecord.IConstants."+sName, type); s.append("<div class='switch-field'>"); s.append(writeToggleMain(request,type,itemValue.length()==0 && checkString(sDefault).length()>0?sDefault:itemValue,language,"currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value",sName,sEvent)); s.append("</div>"); } else{ s.append("<div class='switch-field'>"); s.append(writeToggleMain(request,type,itemValue.length()==0 && checkString(sDefault).length()>0?sDefault:itemValue,language,"currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value",sName,sEvent)); s.append("</div>"); } return s.toString(); } } public static String writeDefaultSelect(HttpServletRequest request,TransactionVO transaction, String sName, String language, String sEvent,int min,int max){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ s.append("<select style='vertical-align: top' title='"+sName+"' "+sEvent+" class='text' id='"+sName+"' "+setRightClickMini(request.getSession(),sName)); s.append(" name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'>"); s.append(" <option/>"); for(int n=min;n<=max;n++){ s.append("<option value='"+n+"' "+(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue().equalsIgnoreCase(n+"")?"selected":"")+">"+n+"</option>"); } s.append("</select>"); } else{ s.append("<select style='vertical-align: top' "+sEvent+" class='text' id='"+sName+"' title='"+setRightClick(request.getSession(),sName)+"' "); s.append(" name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value'>"); s.append(" <option/>"); for(int n=min;n<=max;n++){ s.append("<option value='"+n+"' "+(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue().equalsIgnoreCase(n+"")?"selected":"")+">"+n+"</option>"); } s.append(" </select>"); } return s.toString(); } } public static String writeDefaultNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,String language){ return writeDefaultNumericInput(session, transaction, sName, cols, language, ""); } public static String writeDefaultNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,String language, String onChange){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session, sName,onChange)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' "); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' onblur='isNumber(this)'/>"); return s.toString(); } } public static String writeDefaultNumericInputReadonly(HttpSession session, TransactionVO transaction, String sName,int cols,String language, String onChange){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input readonly type='text' id='"+sName+"' "); s.append(setRightClick(session, sName,onChange)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' "); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' onblur='isNumber(this)'/>"); return s.toString(); } } public static String writeDefaultVisualNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,String language,String contextpath){ return writeDefaultVisualNumericInput(session, transaction, sName, cols, language, contextpath, ""); } public static String writeDefaultVisualNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,String language,String contextpath, String onChange){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<label style='display: inline-block;'><img onclick='document.getElementById(\""+sName+"\").value=document.getElementById(\""+sName+"\").value*1-1;document.getElementById(\""+sName+"\").onchange();' style='vertical-align:bottom;' src='"+contextpath+"/_img/icons/mobile/decrease.png' height='16px'/>"); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session, sName, onChange)); s.append(" class='text' style='text-align: center;' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' "); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' onblur='isNumber(this)'/>"); s.append("<img onclick='document.getElementById(\""+sName+"\").value=document.getElementById(\""+sName+"\").value*1+1;document.getElementById(\""+sName+"\").onchange();' style='vertical-align:top;' src='"+contextpath+"/_img/icons/mobile/increase.png' height='16px'/></label>"); return s.toString(); } } public static String writeDefaultNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,double min,double max,String language){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session, sName)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' "); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' onblur='if(!this.value==\"\" && !isNumberLimited(this,"+min+","+max+")){this.value=\"\";alert(\""+getTranNoLink("web","valueoutofrange",language)+": "+min+" - "+max+"\");this.focus();}'/>"); return s.toString(); } } public static String writeDefaultNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,double min,double max,String language, String sOnBlur){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(setRightClick(session, sName)); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' "); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' onblur='if(!this.value==\"\" && !isNumberLimited(this,"+min+","+max+")){this.value=\"\";alert(\""+getTranNoLink("web","valueoutofrange",language)+": "+min+" - "+max+"\");this.focus();}else{"+sOnBlur+";}'/>"); return s.toString(); } } public static String writeDefaultNumericInput(HttpSession session, TransactionVO transaction, String sName,int cols,double min,double max,String language, String sOnBlur, String sOnEvent){ if(transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName)==null){ return("Unknown item: <a href='javascript:createTransactionItem(\""+transaction.getTransactionType()+"\",\"be.mxs.common.model.vo.healthrecord.IConstants."+sName+"\");'>"+sName+"</a>"); } else{ StringBuffer s = new StringBuffer(); s.append("<input type='text' id='"+sName+"' "); s.append(" class='text' size='"+cols+"' name='currentTransactionVO.items.<ItemVO[hashCode="+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getItemId()+"]>.value' "); s.append(" value='"+transaction.getItem("be.mxs.common.model.vo.healthrecord.IConstants."+sName).getValue()+"' onblur='if(!this.value==\"\" && !isNumberLimited(this,"+min+","+max+")){this.value=\"\";alert(\""+getTranNoLink("web","valueoutofrange",language)+": "+min+" - "+max+"\");this.focus();}else{"+sOnBlur+";}' "+sOnEvent+"/>"); return s.toString(); } } public static String getKeywordsHTML(TransactionVO transaction, String itemId, String textField, String idsField, String language, String contextpath){ StringBuffer sHTML = new StringBuffer(); ItemVO item = transaction.getItem(itemId); if(item!=null && item.getValue()!=null && item.getValue().length()>0){ String[] ids = item.getValue().split(";"); String keyword = ""; for(int n=0; n<ids.length; n++){ if(ids[n].split("\\$").length==2){ keyword = getTran(null,ids[n].split("\\$")[0],ids[n].split("\\$")[1] , language); sHTML.append("<span style='white-space: nowrap;'><a href='javascript:deleteKeyword(\"").append(idsField).append("\",\"").append(textField).append("\",\"").append(ids[n]).append("\");'>") .append("<img width='8' src='"+contextpath+"/_img/themes/default/erase.png' class='link' style='vertical-align:-1px'/>") .append("</a>") .append("&nbsp;<b>").append(keyword.startsWith("/")?keyword.substring(1):keyword).append("</b></span> | "); } } } String sHTMLValue = sHTML.toString(); if(sHTMLValue.endsWith("| ")){ sHTMLValue = sHTMLValue.substring(0,sHTMLValue.lastIndexOf("| ")); } return sHTMLValue; } //--- WRITE SELECT (SORTED) ------------------------------------------------------------------- public static String writeSelect(HttpServletRequest request,String sLabelType, String sSelected,String sWebLanguage){ return writeSelect(request,sLabelType,sSelected,sWebLanguage,false,true); } public static String writeToggleMain(HttpServletRequest request,String sLabelType, String sSelected,String sWebLanguage,String sName,String sBaseName, String sEvent){ return writeToggle(request,sLabelType,sSelected,sWebLanguage,false,true,sName,sBaseName, sEvent); } public static String writeSelect(HttpServletRequest request,String sLabelType, String sSelected,String sWebLanguage,int maxSize){ return writeSelect(request,sLabelType,sSelected,sWebLanguage,false,true, maxSize); } //--- WRITE SELECT (SORTED) ------------------------------------------------------------------- public static String writeSelectWithStyle(HttpServletRequest request,String sLabelType, String sSelected,String sWebLanguage, String sStyle){ return writeSelectWithStyle(request,sLabelType,sSelected,sWebLanguage,false,true,sStyle); } public static String writeSelect(HttpServletRequest request,String sLabelType, String sSelected,String sWebLanguage, boolean showLabelID){ return writeSelect(request,sLabelType,sSelected,sWebLanguage,showLabelID,true); } //--- WRITE SELECT UNSORTED ------------------------------------------------------------------- public static String writeSelectUnsorted(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage){ return writeSelect(request,sLabelType,sSelected,sWebLanguage,false,false); } public static SortedSet<String> getLabelIds(String sLabelType, String sWebLanguage) { TreeSet ids = new TreeSet(); Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); while(idsEnum.hasMoreElements()) { ids.add(((Label)idsEnum.nextElement()).id); } } } return ids; } public static String writeCheckBoxes(HttpServletRequest request,String sLabelType, String name, String sSelected, String sWebLanguage, boolean sorted){ String sResult=""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } sResult+= "<input type='checkbox' name='"+name+"."+sLabelID+"' id='"+name+"."+sLabelID+"' value='"+sLabelID+"'"; if(arrayContains(sSelected,sLabelID,";")){ sResult+= " checked"; } sResult+= ">"+sLabelValue+" "; } } } return sResult; } public static String makeArrayFromParameters(HttpServletRequest request,String name,String separator){ String array=""; Enumeration pars = request.getParameterNames(); while(pars.hasMoreElements()){ String par = (String)pars.nextElement(); if(par.startsWith(name+".")){ if(array.length()>0){ array+=separator; } array+=request.getParameter(par); } } return array; } public static double dateDiffInDays(java.util.Date begin, java.util.Date end) { return (end.getTime()-begin.getTime())/SH.getTimeDay(); } public static boolean arrayContains(String array,String value,String separator){ String[] options = array.split(separator); for(int n=0;n<options.length;n++){ if(options[n].equalsIgnoreCase(value)){ return true; } } return false; } //--- WRITE SELECT ---------------------------------------------------------------------------- public static String writeSelect(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted){ String sOptions = ""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } sOptions+= "<option value='"+sLabelID+"'"; if(sLabelID.toLowerCase().equals(sSelected.toLowerCase())){ sOptions+= " selected"; } if(showLabelID){ sOptions+= ">"+sLabelValue+" ("+sLabelID+")</option>"; } else{ sOptions+= ">"+sLabelValue+"</option>"; } } } } if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String optionUid = sLabelType+"."+new SimpleDateFormat("mmssSSS").format(new java.util.Date()); sOptions+="<option style='display: none' id='"+optionUid+"'>test</option>"; sOptions+="<script>"; sOptions+="myselect=document.getElementById('"+optionUid+"').parentElement;"; sOptions+="myselect.style='border:2px solid black; border-style: dotted';"; sOptions+="myselect.onclick=function(){window.open('"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1','popup','toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no');return false;};"; sOptions+="</script>"; } return sOptions; } public static String writeToggle(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted,String sName,String sBaseName, String sEvent){ String sOptions = ""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } sOptions+= "<input type='radio' name='"+sName+"' value='"+sLabelID+"' id='"+sBaseName+"-"+sLabelID+"' "+sEvent+" "; if(sLabelID.toLowerCase().equals(sSelected.toLowerCase())){ sOptions+= " checked='checked'"; } sOptions+= "/><label for='"+sBaseName+"-"+sLabelID+"'>"+sLabelValue+"</label>"; } } } if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String optionUid = sLabelType+"."+new SimpleDateFormat("mmssSSS").format(new java.util.Date()); sOptions+="<option style='display: none' id='"+optionUid+"'>test</option>"; sOptions+="<script>"; sOptions+="myselect=document.getElementById('"+optionUid+"').parentElement;"; sOptions+="myselect.style='border:2px solid black; border-style: dotted';"; sOptions+="myselect.onclick=function(){window.open('"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1','popup','toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no');return false;};"; sOptions+="</script>"; } return sOptions; } public static String writeSelect(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted, int maxSize){ String sOptions = ""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } sOptions+= "<option value='"+sLabelID+"'"; if(sLabelID.toLowerCase().equals(sSelected.toLowerCase())){ sOptions+= " selected"; } String sTitle=""; if(sLabelValue.length()>maxSize){ sTitle="title='"+sLabelValue+"'"; } if(showLabelID){ sOptions+= " "+sTitle+">"+checkString(sLabelValue,maxSize)+" ("+sLabelID+")</option>"; } else{ sOptions+= " "+sTitle+">"+checkString(sLabelValue,maxSize)+"</option>"; } } } } if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String optionUid = sLabelType+"."+new SimpleDateFormat("mmssSSS").format(new java.util.Date()); sOptions+="<option style='display: none' id='"+optionUid+"'>test</option>"; sOptions+="<script>"; sOptions+="myselect=document.getElementById('"+optionUid+"').parentElement;"; sOptions+="myselect.style='border:2px solid black; border-style: dotted';"; sOptions+="myselect.onclick=function(){window.open('"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1','popup','toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no');return false;};"; sOptions+="</script>"; } return sOptions; } public static String writeSelectWithStyle(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted, String sStyle){ String sOptions = ""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } sOptions+= "<option style='"+sStyle+"' value='"+sLabelID+"'"; if(sLabelID.toLowerCase().equals(sSelected.toLowerCase())){ sOptions+= " selected"; } if(showLabelID){ sOptions+= ">"+sLabelValue+" ("+sLabelID+")</option>"; } else{ sOptions+= ">"+sLabelValue+"</option>"; } } } } if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String optionUid = sLabelType+"."+new SimpleDateFormat("mmssSSS").format(new java.util.Date()); sOptions+="<option style='display: none' id='"+optionUid+"'>test</option>"; sOptions+="<script>"; sOptions+="myselect=document.getElementById('"+optionUid+"').parentElement;"; sOptions+="myselect.style='border:2px solid black; border-style: dotted';"; sOptions+="myselect.onclick=function(){window.open('"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1','popup','toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no');return false;};"; sOptions+="</script>"; } return sOptions; } public static String writeSelectUpperCase(String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted){ return writeSelectUpperCase(null, sLabelType, sSelected, sWebLanguage, showLabelID, sorted); } //--- WRITE SELECT ---------------------------------------------------------------------------- public static String writeSelectUpperCase(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted){ String sOptions = ""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value.toUpperCase(),label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value.toUpperCase()); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } sOptions+= "<option value='"+sLabelID+"'"; if(sLabelID.toLowerCase().equals(sSelected.toLowerCase())){ sOptions+= " selected"; } if(showLabelID){ sOptions+= ">"+sLabelID+" - "+sLabelValue+"</option>"; } else{ sOptions+= ">"+sLabelValue+"</option>"; } } } } if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String optionUid = sLabelType+"."+new SimpleDateFormat("mmssSSS").format(new java.util.Date()); sOptions+="<option style='display: none' id='"+optionUid+"'>test</option>"; sOptions+="<script>"; sOptions+="myselect=document.getElementById('"+optionUid+"').parentElement;"; sOptions+="myselect.style='border:2px solid black; border-style: dotted';"; sOptions+="myselect.onclick=function(){window.open('"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1','popup','toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no');return false;};"; sOptions+="</script>"; } return sOptions; } public static String writeSelectExclude(String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted, String sExclude){ return writeSelectExclude(null, sLabelType, sSelected, sWebLanguage, showLabelID, sorted, sExclude); } //--- WRITE SELECT EXCLUDE -------------------------------------------------------------------- public static String writeSelectExclude(HttpServletRequest request,String sLabelType, String sSelected, String sWebLanguage, boolean showLabelID, boolean sorted, String sExclude){ String sOptions = ""; Label label; Iterator it; Hashtable labelTypes = (Hashtable)MedwanQuery.getInstance().getLabels().get(sWebLanguage.toLowerCase()); if(labelTypes!=null){ Hashtable labelIds = (Hashtable)labelTypes.get(sLabelType.toLowerCase()); if(labelIds!=null){ Enumeration idsEnum = labelIds.elements(); Hashtable hSelected = new Hashtable(); if(sorted){ // sorted on value while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.value,label.id); } } else{ // sorted on id while(idsEnum.hasMoreElements()){ label = (Label)idsEnum.nextElement(); hSelected.put(label.id,label.value); } } // sort on keys : // when sorted (on value), key = labelValue // when !sorted (sorted on id), key = labelID Vector keys = new Vector(hSelected.keySet()); Collections.sort(keys); it = keys.iterator(); // to html String sLabelValue, sLabelID; while(it.hasNext()){ if(sorted){ sLabelValue = (String)it.next(); sLabelID = (String)hSelected.get(sLabelValue); } else{ sLabelID = (String)it.next(); sLabelValue = (String)hSelected.get(sLabelID); } if(sExclude.indexOf(sLabelID)<0){ sOptions+= "<option value='"+sLabelID+"'"; if(sLabelID.toLowerCase().equals(sSelected.toLowerCase())){ sOptions+= " selected"; } if(showLabelID){ sOptions+= ">"+sLabelID+" - "+sLabelValue+"</option>"; } else{ sOptions+= ">"+sLabelValue+"</option>"; } } } } } if(request!=null && checkString((String)request.getSession().getAttribute("editmode")).equalsIgnoreCase("1")){ String optionUid = sLabelType+"."+new SimpleDateFormat("mmssSSS").format(new java.util.Date()); sOptions+="<option style='display: none' id='"+optionUid+"'>test</option>"; sOptions+="<script>"; sOptions+="myselect=document.getElementById('"+optionUid+"').parentElement;"; sOptions+="myselect.style='border:2px solid black; border-style: dotted';"; sOptions+="myselect.onclick=function(){window.open('"+request.getRequestURI().replaceAll(request.getServletPath(),"")+"/popup.jsp?Page=system/manageTranslations.jsp&FindLabelType="+sLabelType+"&find=1','popup','toolbar=no,status=yes,scrollbars=yes,resizable=yes,width=800,height=500,menubar=no');return false;};"; sOptions+="</script>"; } return sOptions; } //--- SAVE UNKNOWN LABEL ---------------------------------------------------------------------- public static void saveUnknownLabel(String sLabelType, String sLabelID, String sLabelLang){ PreparedStatement ps = null; ResultSet rs = null; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ String sSelect = "SELECT OC_LABEL_TYPE FROM OC_UNKNOWNLABELS"+ " WHERE OC_LABEL_TYPE = ? AND OC_LABEL_ID = ? AND OC_LABEL_LANGUAGE = ?"+ " AND OC_LABEL_UPDATEUSERID IS NULL"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sLabelType.toLowerCase()); ps.setString(2,sLabelID.toLowerCase()); ps.setString(3,sLabelLang.toLowerCase()); rs = ps.executeQuery(); boolean bFound = false; if(rs.next()) bFound = true; if(rs!=null) rs.close(); if(ps!=null) ps.close(); if(!bFound){ sSelect = "INSERT INTO OC_UNKNOWNLABELS (OC_LABEL_TYPE, OC_LABEL_ID, OC_LABEL_LANGUAGE,"+ " OC_LABEL_VALUE, OC_LABEL_UNKNOWNDATETIME)"+ " VALUES (?,?,?,?)"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,sLabelType.toLowerCase()); ps.setString(2,sLabelID.toLowerCase()); ps.setString(3,sLabelLang.toLowerCase()); ps.setTimestamp(4,getSQLTime()); // NOW ps.execute(); if(ps!=null) ps.close(); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(Exception e){ e.printStackTrace(); } } } //--- CHECK STRING ---------------------------------------------------------------------------- public static String checkString(String sString){ // om geen 'null' weer te geven if((sString==null)||(sString.toLowerCase().equals("null"))){ return ""; } else{ sString = sString.trim(); } return sString; } public static String checkString(StringBuffer sString){ // om geen 'null' weer te geven String s=""; if(sString!=null && !sString.toString().equalsIgnoreCase("null")){ s = sString.toString().trim(); } return s; } //--- CHECK STRING ---------------------------------------------------------------------------- public static String checkString(String sString, int maxSize){ // om geen 'null' weer te geven if((sString==null)||(sString.toLowerCase().equals("null"))){ return ""; } else{ sString = sString.trim(); if(sString.length()>maxSize){ sString=sString.substring(0,maxSize-3)+"..."; } } return sString; } public static String checkString(String sString, String defaultValue){ // om geen 'null' weer te geven if((sString==null)||(sString.toLowerCase().equals("null"))||sString.length()==0){ return defaultValue; } else{ sString = sString.trim(); } return sString; } public static String checkString(String sString, String defaultValue, int maxSize){ // om geen 'null' weer te geven if((sString==null)||(sString.toLowerCase().equals("null"))){ return defaultValue; } else{ sString = sString.trim(); if(sString.length()>maxSize-3){ sString=sString.substring(0,maxSize-3)+"..."; } } return sString; } //--- GET ACTIVE PRIVATE ---------------------------------------------------------------------- public static AdminPrivateContact getActivePrivate(AdminPerson person){ AdminPrivateContact apcActive = null; AdminPrivateContact apc; for(int i=0; i<person.privateContacts.size(); i++){ apc = ((AdminPrivateContact)(person.privateContacts.elementAt(i))); if(apc.end==null || apc.end.trim().equals("")){ if(apcActive==null || ScreenHelper.parseDate(apc.begin).after(ScreenHelper.parseDate(apcActive.begin))){ apcActive=apc; } } } return apcActive; } //--- REPLACE --------------------------------------------------------------------------------- public static String replace(String sValue, String sSearch, String sReplace){ String sResult = "", sLeft = sValue; int iIndex = sLeft.indexOf(sSearch); if(iIndex > -1){ while(iIndex > -1){ sResult+= sLeft.substring(0,iIndex)+sReplace; sLeft = sLeft.substring(iIndex+1,sLeft.length()); iIndex = sLeft.indexOf(sSearch); } sResult+= sLeft; } else{ sResult = sValue; } return sResult; } //--- GET TS ---------------------------------------------------------------------------------- public static String getTs(){ return new java.util.Date().getTime()+""; } //--- GET DATE -------------------------------------------------------------------------------- public static String getDate(){ return stdDateFormat.format(new java.util.Date()); } //--- GET DATE -------------------------------------------------------------------------------- public static java.util.Date getDate(java.util.Date date) throws Exception{ return ScreenHelper.parseDate(stdDateFormat.format(date)); } //--- FORMAT DATE ----------------------------------------------------------------------------- public static String formatDate(java.util.Date dDate){ String sDate = ""; if(dDate!=null){ sDate = stdDateFormat.format(dDate); } return sDate; } public static String formatDate(java.util.Date dDate, SimpleDateFormat dateFormat){ String sDate = ""; if(dDate!=null){ sDate = dateFormat.format(dDate); } return sDate; } //--- WRITE TABLE FOOTER ---------------------------------------------------------------------- public static String writeTblFooter(){ return "</table></td></tr></td></tr></table>"; } //--- WRITE TABLE HEADER ---------------------------------------------------------------------- public static String writeTblHeader(String sHeader, String sCONTEXTDIR){ return "<table border='0' cellspacing='0' cellpadding='0' class='menu' width='100%'>"+ "<tr class='admin'><td width='100%'>&nbsp;&nbsp;"+sHeader+"&nbsp;&nbsp;</td></tr>"+ "<tr>"+ "<td>"+ "<table width='100%' cellspacing='0'>"; } //--- WRITE TABLE CHILD ----------------------------------------------------------------------- public static String writeTblChild(String sPath, String sHeader, String sCONTEXTDIR){ return writeTblChild(sPath,sHeader,sCONTEXTDIR,-1); } public static String writeTblChild(String sPath, String sHeader, String sCONTEXTDIR, int rowIdx){ return writeTblChild(sPath,sHeader,sCONTEXTDIR,rowIdx,false); } public static String writeTblChild(String sPath, String sHeader, String sCONTEXTDIR, int rowIdx, boolean smallRows){ return "<tr"+(rowIdx>-1?(rowIdx%2==0?" class='list1'":" class='list'"):"")+(smallRows?" style='height:17px'":"")+">"+ "<td class='arrow'><img src='"+sCONTEXTDIR+"/_img/themes/default/pijl.gif'></td>"+ "<td width='99%' nowrap>"+ "<button class='buttoninvisible' accesskey='"+getAccessKey(sHeader)+"' onclick='window.location.href=\""+sCONTEXTDIR+"/"+sPath+"\"'></button><a href='"+sCONTEXTDIR+"/"+sPath+"' onMouseOver=\"window.status='';return true;\">"+sHeader+"</a>&nbsp;"+ "</td>"+ "</tr>"; } //--- WRITE TABLE CHILD NO BUTTON ------------------------------------------------------------- public static String writeTblChildNoButton(String sPath, String sHeader, String sCONTEXTDIR){ return "<tr>"+ "<td class='arrow'><img src='"+sCONTEXTDIR+"/_img/themes/default/pijl.gif'></td>"+ "<td width='99%' nowrap>"+ "<a href='"+sCONTEXTDIR+"/"+sPath+"' onMouseOver=\"window.status='';return true;\">"+sHeader+"</a>&nbsp;"+ "</td>"+ "</tr>"; } //--- WRITE TABLE CHILD WITH CODE ------------------------------------------------------------- public static String writeTblChildWithCode(String sCommand, String sHeader, String sCONTEXTDIR){ return writeTblChildWithCode(sCommand,sHeader,sCONTEXTDIR,-1); } public static String writeTblChildWithCode(String sCommand, String sHeader, String sCONTEXTDIR, int rowIdx){ return writeTblChildWithCode(sCommand,sHeader,sCONTEXTDIR,rowIdx,false); } public static String writeTblChildWithCode(String sCommand, String sHeader, String sCONTEXTDIR, int rowIdx, boolean smallRows){ return "<tr"+(rowIdx>-1?(rowIdx%2==0?" class='list1'":" class='list'"):"")+(smallRows?" style='height:17px'":"")+">"+ "<td class='arrow'><img src='"+sCONTEXTDIR+"/_img/themes/default/pijl.gif'></td>"+ "<td width='99%' nowrap>"+ "<button class='buttoninvisible' accesskey='"+getAccessKey(sHeader)+"' onclick='"+sCommand+"'></button>"+ "<a href='"+sCommand+"' onMouseOver=\"window.status='';return true;\">"+sHeader+"</a>&nbsp;"+ "</td>"+ "</tr>"; } //--- WRITE TABLE CHILD WITH CODE NO BUTTON --------------------------------------------------- public static String writeTblChildWithCodeNoButton(String sCommand, String sHeader, String sCONTEXTDIR){ return writeTblChildWithCodeNoButton(sCommand,sHeader,sCONTEXTDIR,-1); } public static String writeTblChildWithCodeNoButton(String sCommand, String sHeader, String sCONTEXTDIR, int rowIdx){ return writeTblChildWithCodeNoButton(sCommand,sHeader,sCONTEXTDIR,rowIdx,false); } public static String writeTblChildWithCodeNoButton(String sCommand, String sHeader, String sCONTEXTDIR, int rowIdx, boolean smallRows){ return "<tr"+(rowIdx>-1?(rowIdx%2==0?" class='list1'":" class='list'"):"")+(smallRows?" style='height:17px'":"")+">"+ "<td class='arrow'><img src='"+sCONTEXTDIR+"/_img/themes/default/pijl.gif'></td>"+ "<td width='99%' nowrap>"+ "<a href='"+sCommand+"' onMouseOver=\"window.status='';return true;\">"+sHeader+"</a>&nbsp;"+ "</td>"+ "</tr>"; } //--- GET ACCESS KEY -------------------------------------------------------------------------- public static String getAccessKey(String label){ label=label.toLowerCase(); if(label.indexOf("<u>")>-1 && label.indexOf("</u>")>-1){ return label.substring(label.indexOf("<u>")+3,label.indexOf("</u>")); } return ""; } //--- SET RIGHT CLICK ------------------------------------------------------------------------- public static String setRightClick(String itemType){ return setRightClick(itemType, ""); } public static String setRightClick(String itemType, String onChange){ return "onclick='this.className=\"selected\"' "+ //"onchange='"+onChange+"this.className=\"selected\";setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onkeydown='"+onChange+"this.className=\"selected\";setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onmouseover=\"if(document.getElementById('clipboard')) document.getElementById('clipboard').innerHTML='"+itemType+"';this.style.cursor='help';setPopup('be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"',this.value);activeItem=true;setItemsMenu(true);\" "+ "onmouseout=\"this.style.cursor='default';activeItem=false;\" "; } public static String setRightClick(HttpSession session,String itemType){ return setRightClick(session,itemType, ""); } public static String setRightClick(HttpSession session,String itemType, String onChange){ return "onclick='this.className=\"selected\"' "+ //"onchange='"+onChange+"this.className=\"selected\";setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onkeydown='"+onChange+"this.className=\"selected\";setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onmouseover=\"if(document.getElementById('clipboard')) document.getElementById('clipboard').innerHTML='"+itemType+"';this.style.cursor='help';setPopup('be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"',this.value);activeItem=true;setItemsMenu(true);\" "+ "onmouseout=\"this.style.cursor='default';activeItem=false;\" "+ (checkString((String)session.getAttribute("editmode")).equals("1")?"title='"+itemType+"' ":""); } public static String setRightClickNoClass(HttpSession session,String itemType){ return setRightClickNoClass(session,itemType, ""); } public static String setRightClickNoClass(HttpSession session,String itemType, String onChange){ return "onkeydown='setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onmouseover=\"if(document.getElementById('clipboard')) document.getElementById('clipboard').innerHTML='"+itemType+"';this.style.cursor='help';setPopup('be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"',this.value);activeItem=true;setItemsMenu(true);\" "+ "onmouseout=\"this.style.cursor='default';activeItem=false;\" "+ (checkString((String)session.getAttribute("editmode")).equals("1")?"title='"+itemType+"' ":""); } public static String setRightClickCenter(HttpSession session,String itemType){ return setRightClickCenter(session,itemType, ""); } public static String setRightClickCenter(HttpSession session,String itemType, String onChange){ return "onclick='this.className=\"selectedcenter\"' "+ //"onchange='"+onChange+"this.className=\"selectedcenter\";setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onkeydown='"+onChange+"this.className=\"selectedcenter\";setPopup(\"be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"\",this.value)' "+ "onmouseover=\"if(document.getElementById('clipboard')) document.getElementById('clipboard').innerHTML='"+itemType+"';this.style.cursor='help';setPopup('be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"',this.value);activeItem=true;setItemsMenu(true);\" "+ "onmouseout=\"this.style.cursor='default';activeItem=false;\" "+ (checkString((String)session.getAttribute("editmode")).equals("1")?"title='"+itemType+"' ":""); } //--- SET RIGHT CLICK MINI -------------------------------------------------------------------- public static String setRightClickMini(String itemType){ return "onmouseover=\"if(document.getElementById('clipboard')) document.getElementById('clipboard').innerHTML='"+itemType+"';this.style.cursor='help';setPopup('be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"',this.value);activeItem=true;setItemsMenu(true);\" "+ "onmouseout=\"this.style.cursor='default';activeItem=false;document.oncontextmenu=function(){return true};\" "; } public static String setRightClickMini(HttpSession session,String itemType){ return "onmouseover=\"if(document.getElementById('clipboard')) document.getElementById('clipboard').innerHTML='"+itemType+"';this.style.cursor='help';setPopup('be.mxs.common.model.vo.healthrecord.IConstants."+itemType+"',this.value);activeItem=true;setItemsMenu(true);\" "+ "onmouseout=\"this.style.cursor='default';activeItem=false;document.oncontextmenu=function(){return true};\" "+ (checkString((String)session.getAttribute("editmode")).equals("1")?"title='"+itemType+"' ":""); } //--- GET DEFAULTS ---------------------------------------------------------------------------- public static String getDefaults(HttpServletRequest request) throws SessionContainerFactoryException { // defaults String defaults = ((SessionContainerWO)SessionContainerFactory.getInstance().getSessionContainerWO( request , SessionContainerWO.class.getName())).getItemDefaultsHTML(); defaults += "<script>function loadDefaults(){" +"for(n=0;n<document.all.length;n++){" +"if(document.getElementsByName('DefaultValue_'+document.all[n].name).length>0){" +"if(document.all[n].type=='text'){document.all[n].value=document.getElementsByName('DefaultValue_'+document.all[n].name)[0].value;document.all[n].className='modified'}" +"if(document.all[n].type=='textarea'){document.all[n].value=document.getElementsByName('DefaultValue_'+document.all[n].name)[0].value;document.all[n].className='modified'}" +"if(document.all[n].type=='radio' && document.all[n].value==document.getElementsByName('DefaultValue_'+document.all[n].name)[0].value){document.all[n].checked=true;document.all[n].className='modified'}" +"if(document.all[n].type=='checkbox' && document.all[n].value==document.getElementsByName('DefaultValue_'+document.all[n].name)[0].value){document.all[n].checked=true;document.all[n].className='modified'}" +"if(document.all[n].type=='select-one'){for(m=0;m<document.all[n].options.length;m++){if(document.all[n].options[m].value==document.getElementsByName('DefaultValue_'+document.all[n].name)[0].value){document.all[n].selectedIndex=m;document.all[n].className='modified'}}}" +"}" +"}" +"document.getElementById('ie5menu').style.visibility = 'hidden';}</script>"; // previous defaults += ((SessionContainerWO)SessionContainerFactory.getInstance().getSessionContainerWO( request , SessionContainerWO.class.getName())).getItemPreviousHTML(); String loadPreviousScript="<script>"+ "function loadPrevious(){"+ "for(n=0;n<document.all.length;n++){"+ "if(document.getElementsByName('PreviousDivValue_'+document.all[n].name).length>0){"+ "var divcontent=document.getElementsByName('PreviousDivValue_'+document.all[n].name)[0].value;"+ "document.getElementById(document.getElementsByName('PreviousDivValue_'+document.all[n].name)[0].id.substring(3)).className='modified';"+ "document.getElementById(document.getElementsByName('PreviousDivValue_'+document.all[n].name)[0].id.substring(3)).innerHTML=divcontent;"+ "}"+ "if(document.getElementsByName('PreviousValue_'+document.all[n].name).length>0){"+ "if(document.all[n].type=='text'){"+ "document.all[n].value=document.getElementsByName('PreviousValue_'+document.all[n].name)[0].value;"+ "document.all[n].className='modified';"+ "}"+ "else if(document.all[n].type=='hidden'){"+ "document.all[n].value=document.getElementsByName('PreviousValue_'+document.all[n].name)[0].value;"+ "valuesArray=document.all[n].value.split(';');"+ "for(q=0;q<valuesArray.length;q++){"+ "refElement = document.getElementById(document.getElementsByName('PreviousValue_'+document.all[n].name)[0].id.substring(3)+'.'+valuesArray[q]);"+ "if(refElement && (refElement.type=='checkbox' || refElement.type=='radio') && refElement.checked==false){"+ "refElement.checked=true;"+ "refElement.className='modified';"+ "}"+ "}"+ "refElement=document.getElementById('img_'+document.getElementsByName('PreviousValue_'+document.all[n].name)[0].id.substring(3));"+ "if(refElement && refElement.onplay){"+ "window.setTimeout('refElement.onplay();',200);"+ "}"+ "}"+ "else if(document.all[n].type=='textarea'){"+ "document.all[n].value=document.getElementsByName('PreviousValue_'+document.all[n].name)[0].value;"+ "document.all[n].className='modified';"+ "}"+ "else if(document.all[n].type=='radio' && document.all[n].value==document.getElementsByName('PreviousValue_'+document.all[n].name)[0].value){"+ "document.all[n].checked=true;"+ "document.all[n].className='modified';"+ "}"+ "else if(document.all[n].type=='checkbox' && document.all[n].value==document.getElementsByName('PreviousValue_'+document.all[n].name)[0].value){"+ "document.all[n].checked=true;"+ "document.all[n].className='modified';"+ "}"+ "else if(document.all[n].type=='select-one'){"+ "for(m=0;m<document.all[n].options.length;m++){"+ "if(document.all[n].options[m].value==document.getElementsByName('PreviousValue_'+document.all[n].name)[0].value){"+ "document.all[n].selectedIndex=m;document.all[n].className='modified';"+ "}"+ "}"+ "}"+ "}"+ "}"+ "document.getElementById('ie5menu').style.visibility = 'hidden';"+ "}"+ "</script>"; defaults += MedwanQuery.getInstance().getConfigString("scriptLoadPrevious",loadPreviousScript); // previous context defaults += ((SessionContainerWO)SessionContainerFactory.getInstance().getSessionContainerWO( request , SessionContainerWO.class.getName())).getItemPreviousContextHTML(); defaults += "<script>function loadPreviousContext(){" +"for(n=0;n<document.all.length;n++){" +"if(document.getElementsByName('PreviousContextValue_'+document.all[n].name).length>0){" +"if(document.all[n].type=='text'){document.all[n].value=document.getElementsByName('PreviousContextValue_'+document.all[n].name)[0].value;document.all[n].className='modified'}" +"if(document.all[n].type=='textarea'){document.all[n].value=document.getElementsByName('PreviousContextValue_'+document.all[n].name)[0].value;document.all[n].className='modified'}" +"if(document.all[n].type=='radio' && document.all[n].value==document.getElementsByName('PreviousContextValue_'+document.all[n].name)[0].value){document.all[n].checked=true;document.all[n].className='modified'}" +"if(document.all[n].type=='checkbox' && document.all[n].value==document.getElementsByName('PreviousContextValue_'+document.all[n].name)[0].value){document.all[n].checked=true;document.all[n].className='modified'}" +"if(document.all[n].type=='select-one'){for(m=0;m<document.all[n].options.length;m++){if(document.all[n].options[m].value==document.getElementsByName('PreviousContextValue_'+document.all[n].name)[0].value){document.all[n].selectedIndex=m;document.all[n].className='modified'}}}" +"}" +"}" +"document.getElementById('ie5menu').style.visibility = 'hidden';}</script>"; return defaults; } //--- FORMAT SQL DATE ------------------------------------------------------------------------- public static String formatSQLDate(Date dDate, String sFormat){ String sDate = ""; if(dDate!=null){ sDate = new SimpleDateFormat(sFormat).format(dDate); } return sDate; } public static String formatSQLDate(java.util.Date dDate, String sFormat){ String sDate = ""; if(dDate!=null){ sDate = new SimpleDateFormat(sFormat).format(dDate); } return sDate; } //--- GET SQL STRING -------------------------------------------------------------------------- public static String setSQLString(String sValue){ if(sValue!=null && sValue.trim().length()>249){ sValue = sValue.substring(0,249); } return sValue; } //--- GET SQL TIME ---------------------------------------------------------------------------- public static String getSQLTime(Time tTime){ String sTime = ""; if(tTime!=null){ sTime = tTime.toString(); sTime = sTime.substring(0,sTime.lastIndexOf(":")); } return sTime; } //--- GET SQL TIME ---------------------------------------------------------------------------- public static java.sql.Timestamp getSQLTime(){ return new java.sql.Timestamp(new java.util.Date().getTime()); // now } public static java.sql.Timestamp getSQLTimestamp(String sTime){ return new java.sql.Timestamp(parseDate(sTime).getTime()); // now } public static java.sql.Timestamp getSQLTimestamp(java.util.Date date){ return new java.sql.Timestamp(date.getTime()); // now } //--- GET SQL TIME STAMP ---------------------------------------------------------------------- public static String getSQLTimeStamp(java.sql.Timestamp timeStamp){ String ts = ""; if(timeStamp!=null){ ts = fullDateFormat.format(new Date(timeStamp.getTime())); } return ts; } //--- GET SQL DATE ---------------------------------------------------------------------------- public static String getSQLDate(java.sql.Date dDate){ String sDate = ""; if(dDate!=null){ sDate = formatDate(dDate); } return sDate; } //--- GET SQL DATE ---------------------------------------------------------------------------- public static String getSQLDate(java.util.Date dDate){ String sDate = ""; if(dDate!=null){ sDate = formatDate(dDate); } return sDate; } //--- GET SQL DATE ---------------------------------------------------------------------------- public static String getSQLDate(java.util.Date dDate, java.util.Date defaultDate){ String sDate = getSQLDate(defaultDate); if(dDate!=null){ sDate = formatDate(dDate); } return sDate; } //--- GET SQL DATE ---------------------------------------------------------------------------- public static java.sql.Date getSQLDate(String sDate){ try{ if(sDate==null || sDate.trim().length()==0 || sDate.trim().length()<5 || sDate.equals("&nbsp;")){ return null; } else{ sDate = sDate.replaceAll("-","/"); return new java.sql.Date(ScreenHelper.parseDate(sDate).getTime()); } } catch(Exception e){ return null; } } //--- GET DATE ADD ---------------------------------------------------------------------------- public static String getDateAdd(String sDate, String sAdd){ try{ if(sDate==null || sDate.trim().length()==0 || sDate.trim().length()<5 || sDate.equals("&nbsp;")){ return null; } else{ sDate = sDate.replaceAll("-","/"); java.util.Date d = ScreenHelper.parseDate(sDate); return ScreenHelper.stdDateFormat.format(new java.util.Date(d.getTime()+Long.parseLong(sAdd)*24*60*60000)); } } catch(Exception e){ return null; } } //--- WRITE JS BUTTONS ------------------------------------------------------------------------ public static String writeJSButtons(String sMyForm, String sMyButton, String sCONTEXTDIR){ return "<script>var myForm = document.getElementById('"+sMyForm+"'); var myButton = document.getElementById('"+sMyButton+"');</script>"+ "<script src='"+sCONTEXTDIR+"/_common/_script/buttons.js'></script>"; } //--- WRITE SAVE BUTTON ----------------------------------------------------------------------- public static String writeSaveButton(String sLanguage){ return writeSaveButton("doSubmit();",sLanguage,-1); } public static String writeSaveButton(String sLanguage, int height){ return writeSaveButton("doSubmit();",sLanguage,height); } public static String writeSaveButton(String sFunction, String sLanguage){ return writeSaveButton(sFunction,sLanguage,-1); } public static String writeSaveButton(String sFunction, String sLanguage, int height){ return "<input class='button' type='button' name='saveButton' id='saveButton' "+(height>0?"style='height:"+height+"px'":"")+" value='"+getTranNoLink("web","save",sLanguage)+"' onclick='"+sFunction+"'/>"; } //--- WRITE SEARCH BUTTON --------------------------------------------------------------------- public static String writeSearchButton(String sLanguage){ return writeSearchButton("doSearch();",sLanguage); } public static String writeSearchButton(String sFunction, String sLanguage){ return "<input class='button' type='button' name='searchButton' id='searchButton' value='"+getTranNoLink("web","search",sLanguage)+"' onclick='"+sFunction+"'/>"; } //--- WRITE BACK BUTTON ----------------------------------------------------------------------- public static String writeBackButton(String sLanguage){ return writeBackButton("doBack();",sLanguage); } public static String writeBackButton(String sFunction, String sLanguage){ return "<input class='button' type='button' name='backButton' id='backButton' value='"+getTranNoLink("web","back",sLanguage)+"' onclick='doBack();'/>"; } //--- WRITE PRINT BUTTON ---------------------------------------------------------------------- public static String writePrintButton(String sLanguage){ return writePrintButton("doPrint();",sLanguage); } public static String writePrintButton(String sFunction, String sLanguage){ return "<input class='button' type='button' name='printButton' id='printButton' value='"+getTranNoLink("web","print",sLanguage)+"' onclick='doPrint();'/>"; } //--- WRITE RESET BUTTON ---------------------------------------------------------------------- public static String writeResetButton(String sLanguage){ return writeResetButton("transactionForm.reset()",sLanguage); } public static String writeResetButton(String sFunction, String sLanguage){ // sFunction can be formName too if(sFunction.toLowerCase().endsWith("form")){ sFunction+= ".reset();"; } return "<input class='button' type='button' name='resetButton' id='resetButton' value='"+getTranNoLink("web","reset",sLanguage)+"' onclick='"+sFunction+"'/>"; } //--- WRITE CLOSE BUTTON ---------------------------------------------------------------------- public static String writeCloseButton(String sLanguage){ return writeCloseButton("window.close();",sLanguage); } public static String writeCloseButton(String sFunction, String sLanguage){ return "<input class='button' type='button' name='closeButton' id='closeButton' value='"+getTranNoLink("web","close",sLanguage)+"' onclick='"+sFunction+"'/>"; } //--- CLOSE QUIETLY --------------------------------------------------------------------------- public static void closeQuietly(Connection connection, Statement statement, ResultSet resultSet){ if(resultSet!=null) try{ resultSet.close(); } catch (SQLException logOrIgnore){logOrIgnore.printStackTrace();} if(statement!=null) try{ statement.close(); } catch (SQLException logOrIgnore){logOrIgnore.printStackTrace();} if(connection!=null) try{ connection.close(); } catch (SQLException logOrIgnore){logOrIgnore.printStackTrace();} } //--- SET INCLUDE PAGE ------------------------------------------------------------------------ public static void setIncludePage(String sPage, PageContext pageContext){ // ? or & if(sPage.indexOf("?")<0){ if(sPage.indexOf("&")>-1){ sPage=sPage.substring(0,sPage.indexOf("&"))+"?"+sPage.substring(sPage.indexOf("&")+1); if(sPage.indexOf("ts=")<0){ sPage+= "&ts="+new java.util.Date().getTime(); } } else{ sPage+= "?ts="+new java.util.Date().getTime(); } } else if(sPage.indexOf("ts=")<0){ sPage+= "&ts="+new java.util.Date().getTime(); } try{ if(!SH.isAcceptableUploadFileExtension(sPage.substring(0,sPage.indexOf("?")))) { pageContext.include(sPage); } } catch(Exception e){ e.printStackTrace(); } } //--- WRITE TIME FIELD ------------------------------------------------------------------------ public static String writeTimeField(String sName, String sValue){ return "<input id='"+sName+"' type='text' class='text' name='"+sName+"' value='"+sValue+"' onblur='checkTime(this)' size='5'>"; } public static String writeTimeField(String sName, String sValue, String code){ return "<input id='"+sName+"' type='text' class='text' name='"+sName+"' value='"+sValue+"' onblur='checkTime(this);"+checkString(code)+"' size='5' >"; } //--- GET SQL TIME STAMP ---------------------------------------------------------------------- public static void getSQLTimestamp(PreparedStatement ps, int iIndex, String sDate, String sTime){ try{ if(sDate==null || sDate.trim().length()==0){ ps.setNull(iIndex,Types.TIMESTAMP); } else{ if(sTime==null || sTime.trim().length()==0){ ps.setDate(iIndex,getSQLDate(sDate)); } else{ ps.setTimestamp(iIndex,new Timestamp(fullDateFormat.parse(sDate+" "+sTime).getTime())); } } } catch(SQLException e){ e.printStackTrace(); } catch(ParseException e){ e.printStackTrace(); } } public static void getSQLTimestamp(PreparedStatement ps, int iIndex, java.util.Date date){ try{ if(date==null){ ps.setNull(iIndex,Types.TIMESTAMP); } else{ ps.setTimestamp(iIndex,new Timestamp(date.getTime())); } } catch(SQLException e){ e.printStackTrace(); } } //--- GET COOKIE ------------------------------------------------------------------------------ public static String getCookie(String cookiename, HttpServletRequest request){ Cookie cookies[] = request.getCookies(); if(cookies!=null){ for(int i=0; i<cookies.length; i++){ if(cookies[i].getName().equals(cookiename)){ return cookies[i].getValue(); } } } return null; } //--- SET COOKIE ------------------------------------------------------------------------------ public static void setCookie(String cookiename, String value, HttpServletResponse response){ Cookie cookie = new Cookie(cookiename,value); cookie.setMaxAge(365); response.addCookie(cookie); } //--- CHECK DB STRING ------------------------------------------------------------------------- public static String checkDbString(String sString){ sString = checkString(sString); if(sString.trim().length()>0){ sString = sString.replaceAll("'","´"); } return sString; } //--- ALIGN BUTTONS START --------------------------------------------------------------------- public static String alignButtonsStart(){ return "<p align='center'>"; } //--- ALIGN BUTTONS STOP ---------------------------------------------------------------------- public static String alignButtonsStop(){ return "</p>"; } //--- SET FORMBUTTONS START ------------------------------------------------------------------- public static String setFormButtonsStart(){ return "<tr>"+ "<td class='admin'/>"+ "<td class='admin2'>"; } //--- SET FORMBUTTONS STOP -------------------------------------------------------------------- public static String setFormButtonsStop(){ return "</td>"+ "</tr>"; } //--- SET SEARCHFORM BUTTONS START ------------------------------------------------------------ public static String setSearchFormButtonsStart(){ return "<tr><td/><td>"; } //--- SET SEARCHFORM BUTTONS STOP ------------------------------------------------------------- public static String setSearchFormButtonsStop(){ return "</td></tr>"; } //--- GET FULL PERSON NAME (1) ---------------------------------------------------------------- public static String getFullPersonName(String personId){ Connection conn = MedwanQuery.getInstance().getAdminConnection(); String sName = getFullPersonName(personId,conn); ScreenHelper.closeQuietly(conn,null,null); return sName; } //--- GET FULL PERSON NAME (2) ---------------------------------------------------------------- public static String getFullPersonName(String personId, Connection dbConnection){ String sReturn = ""; if(checkString(personId).length() > 0){ PreparedStatement ps = null; ResultSet rs = null; try{ String sSelect = "SELECT lastname, firstname FROM Admin WHERE personid = ?"; ps = dbConnection.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(personId)); rs = ps.executeQuery(); if(rs.next()){ sReturn = checkString(rs.getString("lastname"))+" "+checkString(rs.getString("firstname")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null)rs.close(); if(ps!=null)ps.close(); } catch(Exception e){ e.printStackTrace(); } } } return sReturn; } //--- GET PRESTATIONGROUP OPTIONS ------------------------------------------------------------- public static String getPrestationGroupOptions(){ StringBuffer s = new StringBuffer(); Connection oc_conn = null; PreparedStatement ps = null; ResultSet rs = null; try{ String sSql = "select * from oc_prestation_groups order by oc_group_description"; oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); ps = oc_conn.prepareStatement(sSql); rs = ps.executeQuery(); while(rs.next()){ s.append("<option value='"+rs.getInt("oc_group_serverid")+"."+rs.getInt("oc_group_objectid")+"'>"+rs.getString("oc_group_description")+"</option>"); } } catch(Exception e){ e.printStackTrace(); } closeQuietly(oc_conn,ps,rs); return s.toString(); } //--- GET FULL USER NAME (1) ------------------------------------------------------------------ // no connection specified public static String getFullUserName(String userId){ String sName = ""; try{ Connection conn = MedwanQuery.getInstance().getAdminConnection(); sName = getFullUserName(userId,conn); closeQuietly(conn,null,null); } catch(Exception e){ Debug.printStackTrace(e); } return sName; } //--- GET FULL USER NAME (2) ------------------------------------------------------------------ // connection specified public static String getFullUserName(String userId, Connection conn){ String fullName = ""; if(userId!=null && userId.length() > 0){ PreparedStatement ps = null; ResultSet rs = null; String sSelect = "SELECT lastname,firstname FROM Users u, Admin a"+ " WHERE u.userid = ?"+ " AND u.personid = a.personid"; try{ ps = conn.prepareStatement(sSelect); ps.setInt(1,Integer.parseInt(userId)); rs = ps.executeQuery(); if(rs.next()){ fullName = checkString(rs.getString("lastname"))+" "+checkString(rs.getString("firstname")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); } catch(Exception e){ e.printStackTrace(); } } } return fullName; } //--- GET ACTIVE DIVISION --------------------------------------------------------------------- public static Service getActiveDivision(AdminPerson patient){ return getActiveDivision(patient.personid); } public static Service getActiveDivision(String personId){ Service patientDivision = null; PreparedStatement ps = null; ResultSet rs = null; Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ String sSelect = "SELECT b.OC_ENCOUNTER_SERVICEUID FROM OC_ENCOUNTERS a,OC_ENCOUNTER_SERVICES b"+ " WHERE "+ " a.OC_ENCOUNTER_PATIENTUID = ? AND"+ " a.OC_ENCOUNTER_SERVERID=b.OC_ENCOUNTER_SERVERID AND"+ " a.OC_ENCOUNTER_OBJECTID=b.OC_ENCOUNTER_OBJECTID AND"+ " a.OC_ENCOUNTER_ENDDATE IS NULL AND"+ " b.OC_ENCOUNTER_SERVICEENDDATE IS NULL"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,personId); rs = ps.executeQuery(); // get data from DB if(rs.next()){ patientDivision = Service.getService(rs.getString("OC_ENCOUNTER_SERVICEUID")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException se){ se.printStackTrace(); } } return patientDivision; } //--- IS PATIENT HOSPITALIZED ----------------------------------------------------------------- public static boolean isPatientHospitalized(AdminPerson patient){ Service activeDivision = getActiveDivision(patient); return (activeDivision!=null); } public static boolean isPatientHospitalized(String personId){ Service activeDivision = getActiveDivision(personId); return (activeDivision!=null); } //--- TOKENIZE VECTOR ------------------------------------------------------------------------- public static String tokenizeVector(Vector vector, String token, String aanhalingsteken){ String values = ""; // run thru vector for(int i=0; i<vector.size(); i++){ values+= aanhalingsteken+vector.get(i)+aanhalingsteken+token; } // remove last token if any if(values.endsWith(token)){ values = values.substring(0,values.length()-token.length()); } if(values.length()==0) values = aanhalingsteken+aanhalingsteken; return values; } //--- CONTAINS LOWERCASE ---------------------------------------------------------------------- public static boolean containsLowercase(String text){ for(int i=0; i<text.length(); i++){ if(Character.isLowerCase(text.charAt(i))){ return true; } } return false; } //--- CONTAINS UPPERCASE ---------------------------------------------------------------------- public static boolean containsUppercase(String text){ for(int i=0; i<text.length(); i++){ if(Character.isUpperCase(text.charAt(i))){ return true; } } return false; } //--- CONTAINS LETTER ------------------------------------------------------------------------- public static boolean containsLetter(String text){ if(containsLowercase(text) || containsUppercase(text)){ return true; } return false; } //--- CONTAINS NUMBER ------------------------------------------------------------------------- public static boolean containsNumber(String text){ for(int i=0; i<text.length(); i++){ if(Character.isDigit(text.charAt(i))){ return true; } } return false; } //--- CONTAINS ALFANUMERICS ------------------------------------------------------------------- public static boolean containsAlfanumerics(String text){ for(int i=0; i<text.length(); i++){ if(!Character.isDigit(text.charAt(i)) && !Character.isLetter(text.charAt(i))){ return true; } } return false; } //--- GET CONFIG STRING ----------------------------------------------------------------------- public static String getConfigString(String key){ Connection conn = MedwanQuery.getInstance().getConfigConnection(); String sValue = getConfigStringDB(key,conn); try{ conn.close(); } catch(SQLException e){ e.printStackTrace(); } return sValue; } //--- GET CONFIG STRING ----------------------------------------------------------------------- public static String getConfigString(String key, String defaultValue){ return MedwanQuery.getInstance().getConfigString(key, defaultValue); } //--- GET CONFIG STRING DB -------------------------------------------------------------------- public static String getConfigStringDB(String key, Connection ConfigdbConnection){ String cs = ""; Statement st = null; ResultSet rs = null; try{ st = ConfigdbConnection.createStatement(); String sQuery = "SELECT oc_value FROM OC_Config" + " WHERE oc_key LIKE '"+key+"' AND deletetime IS NULL"+ " ORDER BY oc_key"; rs = st.executeQuery(sQuery); while(rs.next()){ cs+= rs.getString("oc_value"); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(st!=null) st.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } return checkString(cs); } //--- GET CONFIG PARAM ------------------------------------------------------------------------ public static String getConfigParam(String key, String param){ return getConfigParamDB(key,param); } public static String getConfigParam(String key, String[] params){ return getConfigParamDB(key,params); } //--- GET CONFIG PARAM DB --------------------------------------------------------------------- public static String getConfigParamDB(String key, String param){ return getConfigString(key).replaceAll("<param>",param); } public static String getConfigParamDB(String key, String[] params){ String result = getConfigString(key); for(int i=0; i<params.length; i++){ result = result.replaceAll("<param"+(i+1)+">",params[i]); } return result; } //--- GET ALL SERVICE CODES ------------------------------------------------------------------- public static Vector getAllServiceCodes(){ Vector serviceCodes = new Vector(); PreparedStatement ps = null; ResultSet rs = null; String sSelect; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ sSelect = "SELECT DISTINCT serviceid FROM Services"; ps = ad_conn.prepareStatement(sSelect); rs = ps.executeQuery(); while(rs.next()){ serviceCodes.add(rs.getString("serviceid")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } return serviceCodes; } //--- GET EXAMINATIONS FOR SERVICE ------------------------------------------------------------ public static Vector getExaminationsForService(String serviceId, String language){ Vector exams = (Vector)MedwanQuery.getInstance().getServiceexaminations().get(serviceId+"."+language); if(exams==null){ exams = new Vector(); Service service = Service.getService(serviceId); if(service!=null && service.comment.indexOf("NOEXAMS")<0){ PreparedStatement ps = null; ResultSet rs = null; String sSelect, examIds = ""; //*** get examination ids of examinations linked to the service *** Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT distinct examinationid FROM ServiceExaminations WHERE serviceid = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,serviceId); rs = ps.executeQuery(); while(rs.next()){ examIds+= rs.getString("examinationid")+","; } // remove last comma if(examIds.indexOf(",") > -1){ examIds = examIds.substring(0,examIds.lastIndexOf(",")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } //*** get examination objects *** if(examIds.length() > 0){ oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT * FROM Examinations WHERE id IN ("+examIds+") ORDER BY priority"; ps = oc_conn.prepareStatement(sSelect); rs = ps.executeQuery(); while(rs.next()){ exams.add(new ExaminationVO(new Integer(rs.getInt("id")),rs.getString("messageKey"), new Integer(rs.getInt("priority")),rs.getBytes("data"), rs.getString("transactionType"),"","",language)); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } } } MedwanQuery.getInstance().getServiceexaminations().put(serviceId+"."+language,exams); } return exams; } //--- GET EXAMINATIONS FOR SERVICE ------------------------------------------------------------ public static Vector getExaminationsForServiceIncludingParents(String serviceId, String language){ Vector exams = (Vector)MedwanQuery.getInstance().getServiceexaminationsincludingparent().get(serviceId+"."+language); if(exams==null){ exams = new Vector(); PreparedStatement ps = null; ResultSet rs = null; String sSelect, examIds = "", allserviceids = "'"+serviceId+"'"; Vector serviceIds = Service.getParentIds(serviceId); for(int n=0; n<serviceIds.size(); n++){ String sv = (String)serviceIds.elementAt(n); Service service = Service.getService(sv); if(service!=null && checkString(service.comment).indexOf("NOEXAMS")<0){ allserviceids+= ",'"+sv+"'"; } } //*** get examination ids of examinations linked to the service *** Connection oc_conn = MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT distinct examinationid FROM ServiceExaminations WHERE serviceid in ("+allserviceids+")"; ps = oc_conn.prepareStatement(sSelect); rs = ps.executeQuery(); while(rs.next()){ examIds+= rs.getString("examinationid")+","; } // remove last comma if(examIds.indexOf(",") > -1){ examIds = examIds.substring(0,examIds.lastIndexOf(",")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } //*** get examination objects *** if(examIds.length() > 0){ oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT * FROM Examinations WHERE id IN ("+examIds+") ORDER BY priority"; ps = oc_conn.prepareStatement(sSelect); rs = ps.executeQuery(); while(rs.next()){ exams.add(new ExaminationVO(new Integer(rs.getInt("id")),rs.getString("messageKey"), new Integer(rs.getInt("priority")),rs.getBytes("data"), rs.getString("transactionType"),"","",language)); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } } MedwanQuery.getInstance().getServiceexaminationsincludingparent().put(serviceId+"."+language,exams); } return exams; } //--- GET OTHER EXAMINATIONS FOR SERVICE ------------------------------------------------------ public static Vector getOtherExaminationsForService(String serviceId, String language){ Vector otherExams = new Vector(), linkedExamIds = new Vector(); PreparedStatement ps = null; ResultSet rs = null; String sSelect, otherExamIds = ""; //*** get ids of examinations linked to the specified service *** Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ sSelect = "SELECT examinationid FROM ServiceExaminations WHERE serviceid = ?"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,serviceId); rs = ps.executeQuery(); while(rs.next()){ linkedExamIds.add(rs.getString("examinationid")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } //*** get ids of all examinations minus the ids of the linked examinations *** try{ sSelect = "SELECT id FROM Examinations"; ps = oc_conn.prepareStatement(sSelect); String examId; rs = ps.executeQuery(); while(rs.next()){ examId = rs.getString("id"); if(!linkedExamIds.contains(examId)){ otherExamIds+= examId+","; } } // remove last comma if(otherExamIds.indexOf(",") > -1){ otherExamIds = otherExamIds.substring(0,otherExamIds.lastIndexOf(",")); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } //*** get examination objects *** if(otherExamIds.length() > 0){ try{ sSelect = "SELECT * FROM Examinations WHERE id IN ("+otherExamIds+") ORDER BY priority"; ps = oc_conn.prepareStatement(sSelect); rs = ps.executeQuery(); while(rs.next()){ otherExams.add(new ExaminationVO(new Integer(rs.getInt("id")),rs.getString("messageKey"), new Integer(rs.getInt("priority")),rs.getBytes("data"), rs.getString("transactionType"),"","",language)); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } } return otherExams; } //--- WRITE DATE TIME FIELD ------------------------------------------------------------------- public static String writeDateTimeField(String sName, String sForm, java.util.Date dValue, String sWebLanguage, String sCONTEXTDIR){ return "<input type='text' maxlength='10' class='text' name='"+sName+"' id='"+sName+"' value='"+getSQLDate(dValue)+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";}'>" +"&nbsp;<img name='popcal' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+getTranNoLink("Web","Select",sWebLanguage)+"' onclick='gfPop1.fPopCalendar(document.getElementsByName(\""+sName+"\")[0]);return false;'>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("Web","PutToday",sWebLanguage)+"' onclick=\"getToday(document.getElementsByName('"+sName+"')[0]);getTime(document.getElementsByName('"+sName+"Time')[0])\">" +"&nbsp;"+writeTimeField(sName+"Time", formatSQLDate(dValue,"HH:mm")) +"&nbsp;"+getTran(null,"web.occup","medwan.common.hour",sWebLanguage); } //--- WRITE DATE TIME FIELD ------------------------------------------------------------------- public static String writeDateTimeField(String sName, String sForm, java.util.Date dValue, String sWebLanguage, String sCONTEXTDIR,String code){ return "<input type='text' maxlength='10' class='text' name='"+sName+"' id='"+sName+"' value='"+getSQLDate(dValue)+"' size='12' onblur='if(!checkDate(this)){dateError(this);this.value=\"\";};"+checkString(code)+"'>" +"&nbsp;<img name='popcal' class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_agenda.png' alt='"+getTranNoLink("Web","Select",sWebLanguage)+"' onclick='gfPop1.fPopCalendar(document.getElementsByName(\""+sName+"\")[0]);return false;'>" +"&nbsp;<img class='link' src='"+sCONTEXTDIR+"/_img/icons/icon_compose.png' alt='"+getTranNoLink("Web","PutToday",sWebLanguage)+"' onclick=\"getToday(document.getElementsByName('"+sName+"')[0]);getTime(document.getElementsByName('"+sName+"Time')[0])\">" +"&nbsp;"+writeTimeField(sName+"Time", formatSQLDate(dValue,"HH:mm"),code) +"&nbsp;"+getTran(null,"web.occup","medwan.common.hour",sWebLanguage); } //--- GET SQL TIME ---------------------------------------------------------------------------- public static java.util.Date getSQLTime(String sTime){ java.util.Date date = null; if(sTime.length()>0){ try{ date = new SimpleDateFormat().parse(sTime); } catch(Exception e){ date = null; } } return date; } //--- GET SQL TIME ---------------------------------------------------------------------------- public static java.util.Date getSQLTime(String sTime, String sFormat){ java.util.Date date = null; if(sTime.length()>0){ try{ date = new SimpleDateFormat(sFormat).parse(sTime); } catch(Exception e){ date = null; } } return date; } //--- GET PRODUCT UNIT TYPES ------------------------------------------------------------------ public static Vector getProductUnitTypes(String sLang){ Vector unitTypes = new Vector(); PreparedStatement ps = null; ResultSet rs = null; // LOWER Connection co_conn = MedwanQuery.getInstance().getConfigConnection(); String lcaseLabelType = getConfigParam("lowerCompare","OC_LABEL_TYPE",co_conn); String lcaseLabelLang = getConfigParam("lowerCompare","OC_LABEL_LANGUAGE",co_conn); Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection(); try{ String sSelect = "SELECT OC_LABEL_ID FROM OC_LABELS"+ " WHERE "+lcaseLabelType+"=? AND "+lcaseLabelLang+"=?"; ps = oc_conn.prepareStatement(sSelect); ps.setString(1,"product.unit"); ps.setString(2,sLang.toLowerCase()); rs = ps.executeQuery(); while(rs.next()){ unitTypes.add(checkString(rs.getString("OC_LABEL_ID"))); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); oc_conn.close(); co_conn.close(); } catch(SQLException se){ se.printStackTrace(); } } return unitTypes; } //--- CONVERT TO ALFABETICAL CODE ------------------------------------------------------------- public static String convertToAlfabeticalCode(String numberString){ String[] alfabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m", "n","o","p","q","r","s","t","u","v","w","x","y","z"}; String letters = ""; int number = Integer.parseInt(numberString); while(number>0){ number--; letters=alfabet[(number % alfabet.length)]+letters; number=number-(number % alfabet.length); number=number/alfabet.length; } return letters; } //--- CONVERT TO ALFABETICAL CODE ------------------------------------------------------------- public static String convertToAlfabeticalCode(int n){ String[] alfabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m", "n","o","p","q","r","s","t","u","v","w","x","y","z"}; String letters = ""; int number = n; while(number>0){ number--; letters=alfabet[(number % alfabet.length)]+letters; number=number-(number % alfabet.length); number=number/alfabet.length; } return letters; } //--- CONVERT TO ALFABETICAL CODE ------------------------------------------------------------- public static String convertToAlfabeticalCode(long n){ String[] alfabet = {"a","b","c","d","e","f","g","h","i","j","k","l","m", "n","o","p","q","r","s","t","u","v","w","x","y","z"}; String letters = ""; long number = n; while(number>0){ number--; letters=alfabet[((int)(number % alfabet.length))]+letters; number=number-(number % alfabet.length); number=number/alfabet.length; } return letters; } public static String convertToUUID(int n) { return convertToAlfabeticalCode(n).toUpperCase()+"-"+(97-n%97); } public static String convertToUUID(long n) { return convertToAlfabeticalCode(n).toUpperCase()+"-"+(97-n%97); } public static String convertToUUID(String n) { if(n==null || n.length()==0) { return ""; } try { int i = Integer.parseInt(n); } catch(Exception e) { return ""; } return convertToAlfabeticalCode(n).toUpperCase()+"-"+(97-Integer.parseInt(n)%97); } public static int convertFromUUID(String s) { int number=-1; try { if(s.split("-").length==2) { number = convertFromAlfabeticalCode(s.split("-")[0]); if((97-number%97)!=Integer.parseInt(s.split("-")[1])) { return -1; } } } catch(Exception e) { e.printStackTrace(); } return number; } //--- CONVERT FROM ALFABETICAL CODE ------------------------------------------------------------- public static int convertFromAlfabeticalCode(String s){ String numberString=s.toLowerCase(); String alfabet = "abcdefghijklmnopqrstuvwxyz"; int value = 0; int counter = 0; for(int i=0; i<numberString.length(); i++){ int number = alfabet.indexOf(numberString.substring(i,i+1))+1; for(int k=numberString.length()-i-1; k>0; k--){ number*= alfabet.length(); } value+= number; } return value; } //--- IS USER A DOCTOR ------------------------------------------------------------------------ public static boolean isUserADoctor(User user){ return isUserADoctor(Integer.parseInt(user.personid)); } public static boolean isUserADoctor(UserVO user){ return isUserADoctor(user.getPersonVO().personId.intValue()); } public static boolean isUserADoctor(int personId){ boolean userIsADoctor = false; ResultSet rs = null; PreparedStatement ps = null; String sSelect = "SELECT p.value"+ " FROM UserParameters p, Admin a, Users u"+ " WHERE "+getConfigParam("lowerCompare","parameter")+" = 'organisationid'"+ " AND value LIKE '9__'"+ " AND a.personid = ?"+ " AND u.userid = p.userid"+ " AND a.personid = u.personid"; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ ps = ad_conn.prepareStatement(sSelect); ps.setInt(1,personId); rs = ps.executeQuery(); if(rs.next()){ // person who did the examination has a doctor code userIsADoctor = true; } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(SQLException se){ se.printStackTrace(); } } return userIsADoctor; } //--- CONTEXT FOOTER -------------------------------------------------------------------------- public static String contextFooter(HttpServletRequest request){ String result = "</div>"; try{ SessionContainerWO sessionContainerWO = (SessionContainerWO) SessionContainerFactory.getInstance().getSessionContainerWO(request, SessionContainerWO.class.getName()); if(sessionContainerWO.getCurrentTransactionVO().getTransactionId().intValue() > 0 || checkString(request.getParameter("be.mxs.healthrecord.transaction_id")).equalsIgnoreCase("currentTransaction") || MedwanQuery.getInstance().getConfigString("doNotAskForContext").equalsIgnoreCase("on")){ result += "<script>show('content-details');hide('confirm');</script>"; result+=getDefaults(request); } } catch(Exception e){ // nothing } return result; } //--- GET LAST ITEM --------------------------------------------------------------------------- public static ItemVO getLastItem(HttpServletRequest request, String sType){ try{ SessionContainerWO sessionContainerWO = (SessionContainerWO) SessionContainerFactory.getInstance().getSessionContainerWO(request, SessionContainerWO.class.getName()); if(sessionContainerWO.getHealthRecordVO()!=null && sessionContainerWO.getCurrentTransactionVO()!=null){ ItemVO actualItem = sessionContainerWO.getCurrentTransactionVO().getItem(sType); if(actualItem==null || actualItem.getItemId().intValue() < 0){ ItemVO lastItem = MedwanQuery.getInstance().getLastItemVO(sessionContainerWO.getHealthRecordVO().getHealthRecordId().toString(), sType); if(lastItem==null){ if(sessionContainerWO.getCurrentTransactionVO().getItem(sType)!=null){ return sessionContainerWO.getCurrentTransactionVO().getItem(sType); } } else{ return lastItem; } } else{ return actualItem; } } } catch (SessionContainerFactoryException e){ e.printStackTrace(); } // no last item found, so return a blank item return new ItemVO(null,"","",null,null); } //--- CHECK SPECIAL CHARACTERS ---------------------------------------------------------------- // this function is used by DBSynchroniser and AdminPerson public static String checkSpecialCharacters(String sTest){ sTest = sTest.toLowerCase(); sTest = sTest.replaceAll("'",""); sTest = sTest.replaceAll(" ",""); sTest = sTest.replaceAll("-",""); sTest = sTest.replaceAll("é","e"); sTest = sTest.replaceAll("è","e"); sTest = sTest.replaceAll("ï","i"); sTest = sTest.replaceAll("é","e"); sTest = sTest.replaceAll("è","e"); sTest = sTest.replaceAll("ë","e"); sTest = sTest.replaceAll("ï","i"); sTest = sTest.replaceAll("ö","o"); sTest = sTest.replaceAll("ä","a"); sTest = sTest.replaceAll("á","a"); sTest = sTest.replaceAll("à","a"); return sTest; } //--- SET SQL DATE ---------------------------------------------------------------------------- public static void setSQLDate(PreparedStatement ps, int iIndex, String sDate){ try{ if(sDate==null || sDate.trim().length()==0){ ps.setNull(iIndex,Types.DATE); } else{ ps.setDate(iIndex,ScreenHelper.getSQLDate(sDate)); } } catch (SQLException e){ e.printStackTrace(); } } //--- PAD LEFT -------------------------------------------------------------------------------- public static String padLeft(String s, String padCharacter, int size){ int i = s.length(); for(int n = 0; n<size-i; n++){ s = padCharacter+s; } return s; } //--- PAD RIGHT ------------------------------------------------------------------------------- public static String padRight(String s, String padCharacter, int size){ int i = s.length(); for(int n = 0; n<size-i; n++){ s = s+padCharacter; } return s; } //--- GET SERVICE CONTEXTS -------------------------------------------------------------------- public static Hashtable getServiceContexts(){ Hashtable serviceContexts = new Hashtable(); PreparedStatement ps = null; ResultSet rs = null; String sSelect; Connection ad_conn = MedwanQuery.getInstance().getAdminConnection(); try{ sSelect = "SELECT DISTINCT serviceid,defaultcontext FROM Services"; ps = ad_conn.prepareStatement(sSelect); rs = ps.executeQuery(); while(rs.next()){ serviceContexts.put(rs.getString("serviceid")+"",rs.getString("defaultcontext")+""); } } catch(Exception e){ e.printStackTrace(); } finally{ try{ if(rs!=null) rs.close(); if(ps!=null) ps.close(); ad_conn.close(); } catch(SQLException sqle){ sqle.printStackTrace(); } } return serviceContexts; } public static String base64Decompress(byte[] input){ String s = ""; ByteArrayOutputStream stream = new ByteArrayOutputStream(); Inflater decompresser = new Inflater(true); InflaterOutputStream inflaterOutputStream = new InflaterOutputStream(stream, decompresser); try { inflaterOutputStream.write(input); inflaterOutputStream.close(); s=new String(stream.toByteArray()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return s; } public static byte[] base64Compress(String s){ byte[] out = null; ByteArrayOutputStream stream = new ByteArrayOutputStream(); Deflater compresser = new Deflater(Deflater.BEST_COMPRESSION, true); DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compresser); try { deflaterOutputStream.write(s.getBytes()); deflaterOutputStream.close(); out=stream.toByteArray(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return out; } public static String removeLeadingZeros(String s){ for(int n=0;n<s.length();n++){ if(!s.substring(n).startsWith("0")){ return s.substring(n); } } return""; } public static String writeAutocompleteLabelField(String sName, int nSize, String sLabelType, String sSelectFunction){ StringBuffer s = new StringBuffer(); s.append("<input type='hidden' name='"+sName+"id' id='"+sName+"id' value=''>\n"); s.append("<input type='text' class='text' name='"+sName+"' id='"+sName+"' size='"+nSize+"' value=''>\n"); s.append("<div id='autocomplete_"+sName+"' class='autocomple'></div>\n"); s.append("<script>\n"); s.append(" new Ajax.Autocompleter('"+sName+"','autocomplete_"+sName+"','util/getAutoLabels.jsp?labeltype="+sLabelType+"',{\n"); s.append(" minChars:1,\n"); s.append(" method:'post',"); s.append(" afterUpdateElement:afterAutoComplete,\n"); s.append(" callback:composeCallbackURL\n"); s.append(" });\n"); s.append(" function afterAutoComplete(field,item){\n"); s.append(" var name= item.innerHTML.substring(0,item.innerHTML.indexOf('<span'));\n"); s.append(" var id = item.innerHTML.substring(item.innerHTML.substring(item.innerHTML.indexOf('<span')));\n"); s.append(" id=id.substring(id.indexOf('>')+1);\n"); s.append(" id=id.substring(0,id.indexOf('-idcache'));\n"); s.append(" document.getElementById('"+sName+"id').value = id;\n"); s.append(" document.getElementById('"+sName+"').value=name;\n"); s.append(" "+sSelectFunction+";\n"); s.append(" }\n"); s.append(" function composeCallbackURL(field,item){\n"); s.append(" var url = '';\n"); s.append(" if(field.id=='"+sName+"'){\n"); s.append(" url = 'findcode='+field.value;\n"); s.append(" }\n"); s.append(" return url;\n"); s.append(" }\n"); s.append("</script>"); return s.toString(); } //--- IS LIKE --------------------------------------------------------------------------------- // SQL's LIKE-function with '_' representing any single char and '%' representing any group of chars public static boolean isLike(String sExpression, String sText){ String regex = ""; int len = sExpression.length(); if(len > 0){ StringBuffer sb = new StringBuffer(); for(int i=0; i<len; i++){ char c = sExpression.charAt(i); if("[](){}.*+?$^|#\\".indexOf(c)!=-1){ sb.append("\\"); } sb.append(c); } regex = sb.toString(); } regex = regex.replace("_",".") .replace("%",".*?"); Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE | Pattern.DOTALL); return p.matcher(sText).matches(); } }
package algorithms.graph; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; public class EdgeWeightedGraphImpl implements EdgeWeightedGraph { //vertices count is fixed once inited private Collection<Integer> vertices; //edges can be added after inited private int edgesCount; private LinkedList<Edge>[] adjacentList; public void init(int verticesCount) { // Collection<Integer> list = new ArrayList<>(); for (int i = 0; i < verticesCount; i++) { list.add(i); } this.vertices = list; // edgesCount = 0; adjacentList = new LinkedList[verticesCount]; for (int i = 0; i < verticesCount; i++) { adjacentList[i] = new LinkedList<>(); } } @Override public void addEdge(Edge edge) { edgesCount++; Integer one = edge.either(); Integer theOther = edge.theOther(one); adjacentList[one].add(edge); adjacentList[theOther].add(edge); } @Override public Collection<Edge> adjacent(int vertex) { return adjacentList[vertex]; } @Override public int verticesCount() { return this.vertices.size(); } @Override public Collection<Integer> getVertices() { return this.vertices; } @Override public int edgesCount() { return edgesCount; } @Override public Collection<Edge> getEdges() { Collection<Edge> allEdges = new HashSet<>(); for (Integer vertex : vertices) { LinkedList<Edge> adjacentEdges = adjacentList[vertex]; allEdges.addAll(adjacentEdges); } return allEdges; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.tests; import java.util.List; import org.mockito.Mockito; import org.mockito.internal.stubbing.InvocationContainerImpl; import org.mockito.internal.util.MockUtil; import org.mockito.invocation.Invocation; import static org.assertj.core.api.Assertions.assertThat; /** * General test utilities for use with {@link Mockito}. * * @author Phillip Webb */ public abstract class MockitoUtils { /** * Verify the same invocations have been applied to two mocks. This is generally not * the preferred way test with mockito and should be avoided if possible. * @param expected the mock containing expected invocations * @param actual the mock containing actual invocations * @param argumentAdapters adapters that can be used to change argument values before they are compared */ public static <T> void verifySameInvocations(T expected, T actual, InvocationArgumentsAdapter... argumentAdapters) { List<Invocation> expectedInvocations = ((InvocationContainerImpl) MockUtil.getMockHandler(expected).getInvocationContainer()).getInvocations(); List<Invocation> actualInvocations = ((InvocationContainerImpl) MockUtil.getMockHandler(actual).getInvocationContainer()).getInvocations(); verifySameInvocations(expectedInvocations, actualInvocations, argumentAdapters); } private static void verifySameInvocations(List<Invocation> expectedInvocations, List<Invocation> actualInvocations, InvocationArgumentsAdapter... argumentAdapters) { assertThat(expectedInvocations).hasSameSizeAs(actualInvocations); for (int i = 0; i < expectedInvocations.size(); i++) { verifySameInvocation(expectedInvocations.get(i), actualInvocations.get(i), argumentAdapters); } } private static void verifySameInvocation(Invocation expectedInvocation, Invocation actualInvocation, InvocationArgumentsAdapter... argumentAdapters) { assertThat(expectedInvocation.getMethod()).isEqualTo(actualInvocation.getMethod()); Object[] expectedArguments = getInvocationArguments(expectedInvocation, argumentAdapters); Object[] actualArguments = getInvocationArguments(actualInvocation, argumentAdapters); assertThat(expectedArguments).isEqualTo(actualArguments); } private static Object[] getInvocationArguments(Invocation invocation, InvocationArgumentsAdapter... argumentAdapters) { Object[] arguments = invocation.getArguments(); for (InvocationArgumentsAdapter adapter : argumentAdapters) { arguments = adapter.adaptArguments(arguments); } return arguments; } /** * Adapter strategy that can be used to change invocation arguments. */ public interface InvocationArgumentsAdapter { /** * Change the arguments if required. * @param arguments the source arguments * @return updated or original arguments (never {@code null}) */ Object[] adaptArguments(Object[] arguments); } }
package analytics.analysis.algorithms.apriori; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import analytics.database.DBBasicOperations; import analytics.utils.AprioriHelper; import analytics.utils.DataChanges; public class Associations { private int data[][]; //private final String dataFileName = "input.in"; private List<Integer> sortedCodes = null; private HashMap<Integer, String> products = null; private HashMap<String, Double> results = null; public Associations() {} public void buildData() { DBBasicOperations db = DBBasicOperations.getInstance(); db.openConnection(); HashMap<Integer, List<Integer>> transactions = db.getTransactions(); HashMap<Integer, String> products = db.getProducts(); db.closeConnection(); List<Integer> codes = new ArrayList<Integer>(products.keySet()); Collections.sort(codes); List<Integer> transactionKeys = new ArrayList<Integer>(transactions.keySet()); Collections.sort(transactionKeys); this.sortedCodes = codes; this.data = new int[transactions.size()][]; this.products = products; int rows = 0; for(int transactionCode : transactionKeys) { int[] row = AprioriHelper.getDataRow(transactions.get(transactionCode), codes); this.data[rows++] = row; } //DataChanges.writeDataToFile(this.dataFileName, this.data); } /** * @return a HashMap that has as key a string containing comma-separated columns' indexes * and as values the support values */ public HashMap<String, Double> runAlgorithm(double support) { HashMap<String, Double> pairs = new HashMap<String, Double>(); List<String> belowSupp = new ArrayList<String>(); int columnsNo = this.data[0].length; for(int dimension = 1; dimension < columnsNo; dimension++) { List<String> combinations = AprioriHelper.getAllFilteredCombinations(columnsNo, dimension, belowSupp); if(combinations.isEmpty()) { break; } for(int i = 0; i < combinations.size(); i++) { String combination = combinations.get(i); String[] columns = combination.split(","); int[] cols = DataChanges.getIntFromString(columns); double supp = AprioriHelper.getColumnsSupport(this.data, cols); if(supp < support) { //NOTE: this is not needed anymore as only one entry will be removed //combinations = AprioriHelper.removeColumnsCombination(combinations, combination, belowSupp); //i--; belowSupp.add(combination); } else { if (!pairs.containsKey(combination)) { pairs.put(combination, supp); } else { throw new RuntimeException("Try to add duplicate key in support dictionary!"); } } } } if (this.results == null) this.results = pairs; return pairs; } public List<List<String>> getResults(HashMap<String, Double> rawResult) { List<List<String>> products = new ArrayList<List<String>>(); DBBasicOperations db = DBBasicOperations.getInstance(); db.openConnection(); for(String columns : rawResult.keySet()) { Integer[] cols = DataChanges.getIntFromString(columns); List<String> prodNames = db.getNamesForProducts( AprioriHelper.getCodesAtIndexes(cols, this.sortedCodes)); prodNames.add(rawResult.get(columns).toString()); products.add(prodNames); } db.closeConnection(); return products; } public double getSupportForProducts(List<String> selectedProducts) { return AprioriHelper.getSupportForProducts(selectedProducts, this.products, this.sortedCodes, this.data); } /** * conf(X->Y) = supp(X U Y) / supp(X) * @param baseProducts X * @param determinedProducts Y * @return the confidence */ public double getConfidenceWithNames(List<String> baseProducts, List<String> determinedProducts) { return AprioriHelper.getConfidenceWithNames(baseProducts, determinedProducts, this.products, this.sortedCodes, this.data); } private double getConfidenceWithIndexes(List<Integer> baseProducts, List<Integer> determinedProductsIndexes) { return AprioriHelper.getConfidenceWithIndexes( baseProducts, determinedProductsIndexes, this.data); } /** * conf(X->Y) = supp(X U Y) / supp(X) * @param baseProducts X * @param confidence confidence coefficient. If 0, all combinations above 0 will be returned * @return Y */ public HashMap<String, Double> getDeterminedProducts(List<String> baseProducts, double confidence) { HashMap<String, Double> confidenceCoefficient = new HashMap<String, Double>(); List<String> zeroSupp = new ArrayList<String>(); int columnsNo = this.data[0].length; List<Integer> codes = AprioriHelper.getIndexForCodes( AprioriHelper.getCodesForProducts(this.products, baseProducts), this.sortedCodes); for(int dimension = 1; dimension < columnsNo - codes.size() + 1; dimension++) { List<String> columnCombinations = AprioriHelper.getAllCustomCombinations( columnsNo, dimension, codes, zeroSupp); if(columnCombinations.isEmpty()) { break; } for(int i = 0; i < columnCombinations.size(); i++) { String combination = columnCombinations.get(i); String colsComb = combination; for(int code : codes) { colsComb += ("," + code); } String[] columns = colsComb.split(","); int[] cols = DataChanges.getIntFromString(columns); double supp = AprioriHelper.getColumnsSupport(this.data, cols); double conf = this.getConfidenceWithIndexes(codes, DataChanges.getListFromArray(cols)); if(supp != 0 && confidence < conf) { if(!confidenceCoefficient.containsKey(combination)) { confidenceCoefficient.put(combination, conf); } else { throw new RuntimeException("Try to add duplicate key in support dictionary!"); } } else { zeroSupp.add(combination); } } } return confidenceCoefficient; } //public static void main(String[] args) { //Associations alg = new Associations(); //alg.buildData(); //double supp = 0.05; //HashMap<String, Double> res = alg.runAlgorithm(supp); //List<List<String>> products = alg.getResults(res); //AprioriHelper.displaySupportResults(products, supp); //List<String> prods = new ArrayList<String>(); //prods.add("CAPPUCCINO 180 ML"); //System.out.println(alg.getSupportForProducts(prods)); //List<String> baseProducts = new ArrayList<String>(); //baseProducts.add("ESPRESSO 30 ML"); ///List<String> determinedProducts = new ArrayList<String>(); //determinedProducts.add("CAPPUCCINO 180 ML"); //System.out.println(alg.getConfidenceWithNames(baseProducts, determinedProducts)); //List<String> prods = new ArrayList<String>(); //prods.add("CAPPUCCINO 180 ML"); //double conf = 0.1; //List<List<String>> result = alg.getResults(alg.getDeterminedProducts(prods, conf)); //AprioriHelper.displayConfidenceResults(result, prods, conf); //} }
package com.cheese.radio.util.wx; import android.content.Context; import com.umeng.commonsdk.UMConfigure; import com.umeng.socialize.PlatformConfig; public class wxUtil { /** * 在登录 分享 支付时 进行绑定 * @param context 。。 * @param wechat_AppID 微信的appId * @param wechat_AppSecret 微信的秘钥 */ public static void initAppId(Context context,String wechat_AppID, String wechat_AppSecret){ // String wechat_AppID = getResources().getString(R.string.umeng_wechat_AppID); // String wechat_AppSecret = getResources().getString(R.string.wechat_AppSecret); PlatformConfig.setWeixin(wechat_AppID, wechat_AppSecret); UMConfigure.setLogEnabled(true); UMConfigure.init(context, "", "Umeng", UMConfigure.DEVICE_TYPE_PHONE, ""); } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.event; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.PayloadApplicationEvent; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.ResolvableType; import org.springframework.stereotype.Component; import static org.assertj.core.api.Assertions.assertThat; /** * @author Juergen Hoeller */ class PayloadApplicationEventTests { @Test void payloadApplicationEventWithNoTypeUsesInstance() { NumberHolder<Integer> payload = new NumberHolder<>(42); PayloadApplicationEvent<NumberHolder<Integer>> event = new PayloadApplicationEvent<>(this, payload); assertThat(event.getResolvableType()).satisfies(eventType -> { assertThat(eventType.toClass()).isEqualTo(PayloadApplicationEvent.class); assertThat(eventType.getGenerics()) .hasSize(1) .allSatisfy(bodyType -> { assertThat(bodyType.toClass()).isEqualTo(NumberHolder.class); assertThat(bodyType.hasUnresolvableGenerics()).isTrue(); }); }); } @Test void payloadApplicationEventWithType() { NumberHolder<Integer> payload = new NumberHolder<>(42); ResolvableType payloadType = ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class); PayloadApplicationEvent<NumberHolder<Integer>> event = new PayloadApplicationEvent<>(this, payload, payloadType); assertThat(event.getResolvableType()).satisfies(eventType -> { assertThat(eventType.toClass()).isEqualTo(PayloadApplicationEvent.class); assertThat(eventType.getGenerics()) .hasSize(1) .allSatisfy(bodyType -> { assertThat(bodyType.toClass()).isEqualTo(NumberHolder.class); assertThat(bodyType.hasUnresolvableGenerics()).isFalse(); assertThat(bodyType.getGenerics()[0].toClass()).isEqualTo(Integer.class); }); }); } @Test @SuppressWarnings("resource") void testEventClassWithPayloadType() { ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(NumberHolderListener.class); PayloadApplicationEvent<NumberHolder<Integer>> event = new PayloadApplicationEvent<>(this, new NumberHolder<>(42), ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class)); ac.publishEvent(event); assertThat(ac.getBean(NumberHolderListener.class).events.contains(event.getPayload())).isTrue(); ac.close(); } @Test @SuppressWarnings("resource") void testEventClassWithPayloadTypeOnParentContext() { ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(NumberHolderListener.class); ConfigurableApplicationContext ac = new GenericApplicationContext(parent); ac.refresh(); PayloadApplicationEvent<NumberHolder<Integer>> event = new PayloadApplicationEvent<>(this, new NumberHolder<>(42), ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class)); ac.publishEvent(event); assertThat(parent.getBean(NumberHolderListener.class).events.contains(event.getPayload())).isTrue(); ac.close(); parent.close(); } @Test @SuppressWarnings("resource") void testPayloadObjectWithPayloadType() { final Object payload = new NumberHolder<>(42); AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(NumberHolderListener.class) { @Override protected void finishRefresh() throws BeansException { super.finishRefresh(); // This is not recommended: use publishEvent(new PayloadApplicationEvent(...)) instead publishEvent(payload, ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class)); } }; assertThat(ac.getBean(NumberHolderListener.class).events.contains(payload)).isTrue(); ac.close(); } @Test @SuppressWarnings("resource") void testPayloadObjectWithPayloadTypeOnParentContext() { final Object payload = new NumberHolder<>(42); ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(NumberHolderListener.class); ConfigurableApplicationContext ac = new GenericApplicationContext(parent) { @Override protected void finishRefresh() throws BeansException { super.finishRefresh(); // This is not recommended: use publishEvent(new PayloadApplicationEvent(...)) instead publishEvent(payload, ResolvableType.forClassWithGenerics(NumberHolder.class, Integer.class)); } }; ac.refresh(); assertThat(parent.getBean(NumberHolderListener.class).events.contains(payload)).isTrue(); ac.close(); parent.close(); } @Test @SuppressWarnings("resource") void testEventClassWithInterface() { ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(AuditableListener.class); AuditablePayloadEvent<String> event = new AuditablePayloadEvent<>(this, "xyz"); ac.publishEvent(event); assertThat(ac.getBean(AuditableListener.class).events.contains(event)).isTrue(); ac.close(); } @Test @SuppressWarnings("resource") void testEventClassWithInterfaceOnParentContext() { ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(AuditableListener.class); ConfigurableApplicationContext ac = new GenericApplicationContext(parent); ac.refresh(); AuditablePayloadEvent<String> event = new AuditablePayloadEvent<>(this, "xyz"); ac.publishEvent(event); assertThat(parent.getBean(AuditableListener.class).events.contains(event)).isTrue(); ac.close(); parent.close(); } @Test @SuppressWarnings("resource") void testProgrammaticEventListener() { List<Auditable> events = new ArrayList<>(); ApplicationListener<AuditablePayloadEvent<String>> listener = events::add; ApplicationListener<AuditablePayloadEvent<Integer>> mismatch = (event -> event.getPayload()); ConfigurableApplicationContext ac = new GenericApplicationContext(); ac.addApplicationListener(listener); ac.addApplicationListener(mismatch); ac.refresh(); AuditablePayloadEvent<String> event = new AuditablePayloadEvent<>(this, "xyz"); ac.publishEvent(event); assertThat(events.contains(event)).isTrue(); ac.close(); } @Test @SuppressWarnings("resource") void testProgrammaticEventListenerOnParentContext() { List<Auditable> events = new ArrayList<>(); ApplicationListener<AuditablePayloadEvent<String>> listener = events::add; ApplicationListener<AuditablePayloadEvent<Integer>> mismatch = (event -> event.getPayload()); ConfigurableApplicationContext parent = new GenericApplicationContext(); parent.addApplicationListener(listener); parent.addApplicationListener(mismatch); parent.refresh(); ConfigurableApplicationContext ac = new GenericApplicationContext(parent); ac.refresh(); AuditablePayloadEvent<String> event = new AuditablePayloadEvent<>(this, "xyz"); ac.publishEvent(event); assertThat(events.contains(event)).isTrue(); ac.close(); parent.close(); } @Test @SuppressWarnings("resource") void testProgrammaticPayloadListener() { List<String> events = new ArrayList<>(); ApplicationListener<PayloadApplicationEvent<String>> listener = ApplicationListener.forPayload(events::add); ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(Integer::intValue); ConfigurableApplicationContext ac = new GenericApplicationContext(); ac.addApplicationListener(listener); ac.addApplicationListener(mismatch); ac.refresh(); String payload = "xyz"; ac.publishEvent(payload); assertThat(events.contains(payload)).isTrue(); ac.close(); } @Test @SuppressWarnings("resource") void testProgrammaticPayloadListenerOnParentContext() { List<String> events = new ArrayList<>(); ApplicationListener<PayloadApplicationEvent<String>> listener = ApplicationListener.forPayload(events::add); ApplicationListener<PayloadApplicationEvent<Integer>> mismatch = ApplicationListener.forPayload(Integer::intValue); ConfigurableApplicationContext parent = new GenericApplicationContext(); parent.addApplicationListener(listener); parent.addApplicationListener(mismatch); parent.refresh(); ConfigurableApplicationContext ac = new GenericApplicationContext(parent); ac.refresh(); String payload = "xyz"; ac.publishEvent(payload); assertThat(events.contains(payload)).isTrue(); ac.close(); parent.close(); } @Test @SuppressWarnings("resource") void testPlainPayloadListener() { ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(PlainPayloadListener.class); String payload = "xyz"; ac.publishEvent(payload); assertThat(ac.getBean(PlainPayloadListener.class).events.contains(payload)).isTrue(); ac.close(); } @Test @SuppressWarnings("resource") void testPlainPayloadListenerOnParentContext() { ConfigurableApplicationContext parent = new AnnotationConfigApplicationContext(PlainPayloadListener.class); ConfigurableApplicationContext ac = new GenericApplicationContext(parent); ac.refresh(); String payload = "xyz"; ac.publishEvent(payload); assertThat(parent.getBean(PlainPayloadListener.class).events.contains(payload)).isTrue(); ac.close(); parent.close(); } static class NumberHolder<T extends Number> { public NumberHolder(T number) { } } @Component public static class NumberHolderListener { public final List<NumberHolder<Integer>> events = new ArrayList<>(); @EventListener public void onEvent(NumberHolder<Integer> event) { events.add(event); } } public interface Auditable { } @SuppressWarnings("serial") public static class AuditablePayloadEvent<T> extends PayloadApplicationEvent<T> implements Auditable { public AuditablePayloadEvent(Object source, T payload) { super(source, payload); } } @Component public static class AuditableListener { public final List<Auditable> events = new ArrayList<>(); @EventListener public void onEvent(Auditable event) { events.add(event); } } @Component public static class PlainPayloadListener { public final List<String> events = new ArrayList<>(); @EventListener public void onEvent(String event) { events.add(event); } } }
package tictactoe; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.SplitPane; import javafx.scene.effect.DropShadow; import javafx.scene.effect.InnerShadow; import javafx.scene.effect.Lighting; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.shape.Rectangle; import javafx.scene.text.Font; import javafx.stage.Stage; public class xo_homeBase extends BorderPane { protected final SplitPane splitPane; protected final AnchorPane anchorPane; protected final Rectangle rectangle; protected final Button id_single; protected final Lighting lighting; protected final Label label; protected final Label label0; protected final Label label1; protected final DropShadow dropShadow; protected final Button id_multi; protected final Lighting lighting0; protected final Button id_playOnline; protected final Lighting lighting1; protected final Button id_about; protected final Button matches; protected final Lighting lighting2; protected final AnchorPane anchorPane0; protected final InnerShadow innerShadow; public xo_homeBase(Stage s) { splitPane = new SplitPane(); anchorPane = new AnchorPane(); rectangle = new Rectangle(); id_single = new Button(); lighting = new Lighting(); label = new Label(); label0 = new Label(); label1 = new Label(); dropShadow = new DropShadow(); id_multi = new Button(); lighting0 = new Lighting(); id_playOnline = new Button(); lighting1 = new Lighting(); id_about = new Button(); matches = new Button(); lighting2 = new Lighting(); anchorPane0 = new AnchorPane(); innerShadow = new InnerShadow(); setMaxHeight(USE_PREF_SIZE); setMaxWidth(USE_PREF_SIZE); setMinHeight(USE_PREF_SIZE); setMinWidth(USE_PREF_SIZE); setPrefHeight(484.0); setPrefWidth(479.0); BorderPane.setAlignment(splitPane, javafx.geometry.Pos.CENTER); splitPane.setDividerPositions(0.992462311557789); splitPane.setOrientation(javafx.geometry.Orientation.VERTICAL); splitPane.setPrefHeight(200.0); splitPane.setPrefWidth(160.0); anchorPane.setMinHeight(0.0); anchorPane.setMinWidth(0.0); anchorPane.setPrefHeight(537.0); anchorPane.setPrefWidth(598.0); rectangle.setArcHeight(5.0); rectangle.setArcWidth(5.0); rectangle.setHeight(573.0); rectangle.setLayoutX(14.0); rectangle.setLayoutY(-101.0); rectangle.setStroke(javafx.scene.paint.Color.BLACK); rectangle.setStrokeType(javafx.scene.shape.StrokeType.INSIDE); rectangle.setWidth(463.0); id_single.setLayoutX(178.0); id_single.setLayoutY(152.0); id_single.setMnemonicParsing(false); id_single.setPrefHeight(42.0); id_single.setPrefWidth(135.0); id_single.setText("Single Player"); id_single.setTextFill(javafx.scene.paint.Color.valueOf("#1e1f1f")); id_single.setFont(new Font("System Italic", 19.0)); lighting.setDiffuseConstant(1.71); lighting.setSpecularConstant(2.0); lighting.setSpecularExponent(40.0); lighting.setSurfaceScale(0.0); id_single.setEffect(lighting); label.setLayoutX(138.0); label.setLayoutY(43.0); label.setPrefHeight(75.0); label.setPrefWidth(86.0); label.setText("X"); label.setTextFill(javafx.scene.paint.Color.valueOf("#ef0000")); label.setFont(new Font(71.0)); label0.setLayoutX(170.0); label0.setLayoutY(44.0); label0.setText("O"); label0.setTextFill(javafx.scene.paint.Color.valueOf("#00ff5e")); label0.setFont(new Font(70.0)); label1.setLayoutX(224.0); label1.setLayoutY(64.0); label1.setPrefHeight(50.0); label1.setPrefWidth(140.0); label1.setText("Game"); label1.setTextFill(javafx.scene.paint.Color.valueOf("#0088ff")); label1.setFont(new Font(50.0)); dropShadow.setColor(javafx.scene.paint.Color.valueOf("#08a1fc")); dropShadow.setHeight(83.02); dropShadow.setRadius(29.15); dropShadow.setSpread(0.18); dropShadow.setWidth(35.58); label1.setEffect(dropShadow); id_multi.setLayoutX(178.0); id_multi.setLayoutY(214.0); id_multi.setMnemonicParsing(false); id_multi.setPrefHeight(42.0); id_multi.setPrefWidth(135.0); id_multi.setText("Multi Player"); id_multi.setTextFill(javafx.scene.paint.Color.valueOf("#1e1f1f")); id_multi.setFont(new Font("System Italic", 19.0)); lighting0.setDiffuseConstant(1.71); lighting0.setSpecularConstant(2.0); lighting0.setSpecularExponent(40.0); lighting0.setSurfaceScale(0.0); id_multi.setEffect(lighting0); id_playOnline.setLayoutX(178.0); id_playOnline.setLayoutY(275.0); id_playOnline.setMnemonicParsing(false); id_playOnline.setPrefHeight(42.0); id_playOnline.setPrefWidth(135.0); id_playOnline.setText("Online"); id_playOnline.setTextFill(javafx.scene.paint.Color.valueOf("#1e1f1f")); id_playOnline.setFont(new Font("System Italic", 19.0)); lighting1.setDiffuseConstant(1.71); lighting1.setSpecularConstant(2.0); lighting1.setSpecularExponent(40.0); lighting1.setSurfaceScale(0.0); id_playOnline.setEffect(lighting1); id_about.setLayoutX(178.0); id_about.setLayoutY(393.0); id_about.setMnemonicParsing(false); id_about.setPrefHeight(42.0); id_about.setPrefWidth(135.0); id_about.setText("About"); id_about.setTextFill(javafx.scene.paint.Color.valueOf("#1e1f1f")); id_about.setFont(new Font("System Italic", 19.0)); lighting2.setDiffuseConstant(1.71); lighting2.setSpecularConstant(2.0); lighting2.setSpecularExponent(40.0); lighting2.setSurfaceScale(0.0); id_about.setEffect(lighting2); matches.setLayoutX(178.0); matches.setLayoutY(334.0); matches.setMnemonicParsing(false); matches.setPrefHeight(42.0); matches.setPrefWidth(135.0); matches.setText("Matches"); matches.setTextFill(javafx.scene.paint.Color.valueOf("#1e1f1f")); matches.setFont(new Font("System Italic", 19.0)); anchorPane0.setMinHeight(0.0); anchorPane0.setMinWidth(0.0); anchorPane0.setPrefHeight(100.0); anchorPane0.setPrefWidth(160.0); setCenter(splitPane); innerShadow.setChoke(0.64); innerShadow.setColor(javafx.scene.paint.Color.valueOf("#008cff")); innerShadow.setHeight(100.07); innerShadow.setRadius(74.43); innerShadow.setWidth(199.65); setEffect(innerShadow); anchorPane.getChildren().add(rectangle); anchorPane.getChildren().add(id_single); anchorPane.getChildren().add(label); anchorPane.getChildren().add(label0); anchorPane.getChildren().add(label1); anchorPane.getChildren().add(id_multi); anchorPane.getChildren().add(id_playOnline); anchorPane.getChildren().add(id_about); anchorPane.getChildren().add(matches); splitPane.getItems().add(anchorPane); splitPane.getItems().add(anchorPane0); id_single.setOnAction((Action) -> { Parent root = new single_PlayerBase(s); Scene scene = new Scene(root); s.setScene(scene); }); id_multi.setOnAction((Action) -> { Parent root = new multi_PlayerBase(s); Scene scene = new Scene(root); s.setScene(scene); }); id_multi.setOnAction((Action) -> { Parent root = new multi_PlayerBase(s); Scene scene = new Scene(root); s.setScene(scene); }); id_about.setOnAction((Action) -> { Parent root = new aboutBase(s); Scene scene = new Scene(root); s.setScene(scene); }); id_playOnline.setOnAction((Action) -> { Parent root = new loginOrRegBase(s); Scene scene = new Scene(root); s.setScene(scene); }); matches.setOnAction((Action) -> { Parent root = new recordsBase(s); Scene scene = new Scene(root); s.setScene(scene); }); } }
package com.batch.script; import com.batch.script.processes.BatchScriptProcess; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @Slf4j @SpringBootApplication public class ScriptApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(ScriptApplication.class, args); try { BatchScriptProcess batchProcess = (BatchScriptProcess) context.getBean(args[0]); batchProcess.process(); } catch (Exception e) { log.error("Exception",e); } } }
public boolean isPalindrome(ListNode head) { if (head==null || head.next==null) return true; //use fast and slow two pointers to find out middle point ListNode fast = head; ListNode slow = head; while(fast.next!=null && fast.next.next!=null){ fast = fast.next.next; slow = slow.next; } ListNode oldList = head; ListNode midPoint = slow.next; slow.next = null; ListNode newList = reverseLinkedList(midPoint); //check next node's value is equal to reverse list node's value while(newList!=null){ if (newList.val != oldList.val){ return false; } newList = newList.next; oldList = oldList.next; } return true; } public ListNode reverseLinkedList(ListNode head){ if (head == null || head.next == null) return head; ListNode dummy = new ListNode(0); dummy.next = head; ListNode prev = head; ListNode cur = head.next; head.next = null; while(cur.next!= null){ //extract cur.next because it will be changed later ListNode temp = cur.next; cur.next = prev; prev = cur; cur = temp; } cur.next = prev; dummy.next = cur; return dummy.next; }
package multithreading; public class SyncDemo2 { public static void main(String args[]) { Table tab = new Table(); MyThread1 t1 = new MyThread1(tab); MyThread2 t2 = new MyThread2(tab); t1.start(); t2.start(); } }
package com.online.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.online.dao.EmployeeDAO; import com.online.model.Employee; @WebServlet("/updateEmployee") public class UpdateEmployee extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EmployeeDAO eDao= new EmployeeDAO(); Employee employee= new Employee(); int result=0; employee.seteNo(Integer.parseInt(request.getParameter("eNo"))); employee.seteName(request.getParameter("eName")); employee.seteGender(request.getParameter("eGender")); employee.seteDesignation(request.getParameter("eDesignation")); employee.seteSalary(Double.parseDouble(request.getParameter("eSalary"))); employee.setePassword(request.getParameter("ePassword")); result=eDao.updateEmployee(employee); if(result>0) response.sendRedirect("GetEmployeeRecords"); } }
package com.limegroup.gnutella.gui.options.panes; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import org.gudy.azureus2.core3.config.COConfigurationManager; import com.limegroup.gnutella.gui.BoxPanel; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.settings.ConnectionSettings; /** Allows the user to pick a custom interface/address to bind to. */ public class NetworkInterfacePaneItem extends AbstractPaneItem { public final static String TITLE = I18n.tr("Network Interface"); public final static String LABEL = I18n.tr("You can tell FrostWire to bind outgoing connections to an IP address from a specific network interface. Listening sockets will still listen on all available interfaces. This is useful on multi-homed hosts. If you later disable this interface, FrostWire will revert to binding to an arbitrary address."); private static final String ADDRESS = "limewire.networkinterfacepane.address"; private final ButtonGroup GROUP = new ButtonGroup(); private final JCheckBox CUSTOM; private List<JRadioButton> activeButtons = new ArrayList<JRadioButton>(); public NetworkInterfacePaneItem() { super(TITLE, LABEL); CUSTOM = new JCheckBox(I18n.tr("Use a specific network interface.")); CUSTOM.setSelected(ConnectionSettings.CUSTOM_NETWORK_INTERFACE.getValue()); CUSTOM.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { updateButtons(CUSTOM.isSelected()); } }); add(CUSTOM); try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.NORTHWEST; gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = GridBagConstraints.REMAINDER; // Add the available interfaces / addresses while(interfaces.hasMoreElements()) { NetworkInterface ni = interfaces.nextElement(); JLabel label = new JLabel(ni.getDisplayName()); gbc.insets = new Insets(5, 0, 2, 0); panel.add(label, gbc); Enumeration<InetAddress> addresses = ni.getInetAddresses(); gbc.insets = new Insets(0, 6, 0, 0); while(addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); JRadioButton button = new JRadioButton(address.getHostAddress()); GROUP.add(button); if(address.isAnyLocalAddress() || address.isLinkLocalAddress() || address.isLoopbackAddress()) { button.setEnabled(false); } else { activeButtons.add(button); } if(ConnectionSettings.CUSTOM_INETADRESS.getValue().equals(address.getHostAddress())) button.setSelected(true); button.putClientProperty(ADDRESS, address); panel.add(button, gbc); } } initializeSelection(); gbc.weightx = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(0, 0, 0, 0); gbc.gridheight = GridBagConstraints.REMAINDER; panel.add(Box.createGlue(), gbc); //GUIUtils.restrictSize(panel, SizePolicy.RESTRICT_HEIGHT); JScrollPane pane = new JScrollPane(panel); pane.setBorder(BorderFactory.createEmptyBorder()); add(pane); // initialize updateButtons(CUSTOM.isSelected()); } catch(SocketException se) { CUSTOM.setSelected(false); JPanel labelPanel = new BoxPanel(BoxPanel.X_AXIS); labelPanel.add(new JLabel(I18n.tr("FrostWire was unable to determine which network interfaces are available on this machine. Outgoing connections will bind to any arbitrary interface."))); labelPanel.add(Box.createHorizontalGlue()); JPanel outerPanel = new BoxPanel(); outerPanel.add(labelPanel); outerPanel.add(Box.createVerticalGlue()); add(outerPanel); } } protected void updateButtons(boolean enable) { for (JRadioButton button : activeButtons) { button.setEnabled(enable); } } private void initializeSelection() { // Make sure one item is selected always. Enumeration<AbstractButton> buttons = GROUP.getElements(); while(buttons.hasMoreElements()) { AbstractButton bt = buttons.nextElement(); if(bt.isSelected()) return; } // Select the first one if nothing's selected. buttons = GROUP.getElements(); while(buttons.hasMoreElements()) { AbstractButton bt = buttons.nextElement(); if(bt.isEnabled()) { bt.setSelected(true); return; } } } /** * Applies the options currently set in this <tt>PaneItem</tt>. * * @throws IOException if the options could not be fully applied */ public boolean applyOptions() throws IOException { ConnectionSettings.CUSTOM_NETWORK_INTERFACE.setValue(CUSTOM.isSelected()); Enumeration<AbstractButton> buttons = GROUP.getElements(); while(buttons.hasMoreElements()) { AbstractButton bt = buttons.nextElement(); if(bt.isSelected()) { InetAddress addr = (InetAddress)bt.getClientProperty(ADDRESS); ConnectionSettings.CUSTOM_INETADRESS.setValue(addr.getHostAddress()); } } if (ConnectionSettings.CUSTOM_NETWORK_INTERFACE.getValue()) { COConfigurationManager.setParameter("Bind IP", ConnectionSettings.CUSTOM_INETADRESS.getValue()); } else { COConfigurationManager.setParameter("Bind IP", ""); } COConfigurationManager.save(); return false; } public boolean isDirty() { if(!ConnectionSettings.CUSTOM_NETWORK_INTERFACE.getValue()) return CUSTOM.isSelected(); String expect = ConnectionSettings.CUSTOM_INETADRESS.getValue(); Enumeration<AbstractButton> buttons = GROUP.getElements(); while(buttons.hasMoreElements()) { AbstractButton bt = buttons.nextElement(); if(bt.isSelected()) { InetAddress addr = (InetAddress)bt.getClientProperty(ADDRESS); if(addr.getHostAddress().equals(expect)) return false; } } return true; } /** * Sets the options for the fields in this <tt>PaneItem</tt> when the * window is shown. */ public void initOptions() { } }
package model.access; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.Query; import controller.MainController; import model.Project; public class MySQLRatingQuestionIdLoader implements IRatingQuestionIdLoader { @SuppressWarnings("unchecked") public List<Integer> loadByGenderCountVoted(Project project, String gender, int countVoted) throws Exception { EntityManager em = null; List<Integer> ratingQuestionIds = null; try { em = MainController.getEntityManagerFactory().createEntityManager(); Query query = em.createQuery("" + "SELECT Q.id " + "FROM RatingQuestion Q " + "WHERE Q.project = :project " + "AND Q.countVoted = :countVoted " + "AND Q.gender = :gender " ); query.setParameter("countVoted", countVoted); query.setParameter("gender", gender); query.setParameter("project", project); ratingQuestionIds = query.getResultList(); } finally { em.close(); } return ratingQuestionIds; } }
package nyc.c4q.android.ui; public class RealAuthenticationManager implements AuthenticationManager { public boolean validateLogin(String email, String password) { // #31 TODO - implement authentication logic // valid credentials are email: "c4q", password: "c4q" return false; } }
class Car{ private int speed; public void setSpeed(int s) {speed=s;} public void setSpeed(double s) {speed=(int)s;} public int getSpeed() {return speed;} } public class practice2 { public static void main(String args[]) { Car c = new Car(); Car cc = new Car(); c.setSpeed(1.2); cc.setSpeed(1); System.out.println(c.getSpeed()); System.out.println(cc.getSpeed()); } }
package mb.tianxundai.com.toptoken.aty.Use; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import io.realm.Realm; import io.realm.RealmResults; import mb.tianxundai.com.toptoken.MainActivity; import mb.tianxundai.com.toptoken.R; import mb.tianxundai.com.toptoken.aty.login.ImportWalletAty; import mb.tianxundai.com.toptoken.base.BaseAty; import mb.tianxundai.com.toptoken.bean.UserBean; import mb.tianxundai.com.toptoken.interfaces.DarkStatusBarTheme; import mb.tianxundai.com.toptoken.interfaces.Layout; import mb.tianxundai.com.toptoken.realm.UserInfo; import mb.tianxundai.com.toptoken.uitl.Config; import mb.tianxundai.com.toptoken.uitl.JumpParameter; import mb.tianxundai.com.toptoken.uitl.PreferencesUtils; @Layout(R.layout.aty_change_user) @DarkStatusBarTheme(true) //开启顶部状态栏图标、文字暗色模式 public class ChangeUserAty extends BaseAty { @BindView(R.id.iv_back) ImageView ivBack; @BindView(R.id.rv) RecyclerView rv; private UserAdapter adapter; private Realm mRealm; RealmResults<UserInfo> userList; private List<UserBean> mList; @Override public void initViews() { ButterKnife.bind(this); mList = new ArrayList<>(); mRealm = Realm.getDefaultInstance(); } @Override protected void onDestroy() { super.onDestroy(); mRealm.close(); } @Override public void initDatas(JumpParameter jumpParameter) { userList = mRealm.where(UserInfo.class).findAll(); String userWalletId = PreferencesUtils.getString(me, "userWalletId"); UserBean userBean = null; for (int i = 0; i < userList.size(); i++) { userBean = new UserBean(); userBean.setName(userList.get(i).getUserName()); if (userList.get(i).getUserWalletId().equals(userWalletId)) { userBean.setState(true); } else { userBean.setState(false); } mList.add(userBean); } if (adapter == null) { initAdapter(); } else { adapter.notifyDataSetChanged(); } } @Override public void setEvents() { } void initAdapter() { adapter = new UserAdapter(R.layout.item_user_info, mList); rv.setLayoutManager(new LinearLayoutManager(me, LinearLayoutManager.VERTICAL, false)); rv.setAdapter(adapter); adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { // PreferencesUtils.putString(ChangeUserAty.this, "userWalletId", userList.get(position).getUserWalletId()); // PreferencesUtils.putString(ChangeUserAty.this, "zhujici", userList.get(position).getZhujici()); // Config.setLoginState(true); // AppManager.getInstance().killAllActivity(); // jump(MainActivity.class); jump(ImportWalletAty.class,new JumpParameter().put("shou","shou")); } }); } @OnClick({R.id.iv_back}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_back: finish(); break; } } } class UserAdapter extends BaseQuickAdapter<UserBean, BaseViewHolder> { public UserAdapter(int layoutResId, @Nullable List<UserBean> data) { super(layoutResId, data); } @Override protected void convert(BaseViewHolder helper, UserBean item) { if (item.isState()) { helper.setVisible(R.id.image_select1, true); } else { helper.setVisible(R.id.image_select1, false); } if (item.getName() != null) { helper.setText(R.id.tv_name, item.getName()); } else { helper.setText(R.id.tv_name, "测试账号"); } } }
package me.chanjar.weixin.cp.bean; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; import lombok.Data; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.common.util.ToStringUtils; import me.chanjar.weixin.common.util.xml.XStreamCDataConverter; import me.chanjar.weixin.cp.config.WxCpConfigStorage; import me.chanjar.weixin.cp.util.crypto.WxCpCryptUtil; import me.chanjar.weixin.cp.util.xml.XStreamTransformer; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * <pre> * 微信推送过来的消息,也是同步回复给用户的消息,xml格式 * 相关字段的解释看微信开发者文档: * http://mp.weixin.qq.com/wiki/index.php?title=接收普通消息 * http://mp.weixin.qq.com/wiki/index.php?title=接收事件推送 * http://mp.weixin.qq.com/wiki/index.php?title=接收语音识别结果 * </pre> * * @author Daniel Qian */ @XStreamAlias("xml") @Data public class WxCpXmlMessage implements Serializable { private static final long serialVersionUID = -1042994982179476410L; /////////////////////// // 以下都是微信推送过来的消息的xml的element所对应的属性 /////////////////////// @XStreamAlias("AgentID") private Integer agentId; @XStreamAlias("ToUserName") @XStreamConverter(value = XStreamCDataConverter.class) private String toUserName; @XStreamAlias("FromUserName") @XStreamConverter(value = XStreamCDataConverter.class) private String fromUserName; @XStreamAlias("CreateTime") private Long createTime; @XStreamAlias("MsgType") @XStreamConverter(value = XStreamCDataConverter.class) private String msgType; @XStreamAlias("Content") @XStreamConverter(value = XStreamCDataConverter.class) private String content; @XStreamAlias("MsgId") private Long msgId; @XStreamAlias("PicUrl") @XStreamConverter(value = XStreamCDataConverter.class) private String picUrl; @XStreamAlias("MediaId") @XStreamConverter(value = XStreamCDataConverter.class) private String mediaId; @XStreamAlias("Format") @XStreamConverter(value = XStreamCDataConverter.class) private String format; @XStreamAlias("ThumbMediaId") @XStreamConverter(value = XStreamCDataConverter.class) private String thumbMediaId; @XStreamAlias("Location_X") private Double locationX; @XStreamAlias("Location_Y") private Double locationY; @XStreamAlias("Scale") private Double scale; @XStreamAlias("Label") @XStreamConverter(value = XStreamCDataConverter.class) private String label; @XStreamAlias("Title") @XStreamConverter(value = XStreamCDataConverter.class) private String title; @XStreamAlias("Description") @XStreamConverter(value = XStreamCDataConverter.class) private String description; @XStreamAlias("Url") @XStreamConverter(value = XStreamCDataConverter.class) private String url; @XStreamAlias("Event") @XStreamConverter(value = XStreamCDataConverter.class) private String event; @XStreamAlias("EventKey") @XStreamConverter(value = XStreamCDataConverter.class) private String eventKey; @XStreamAlias("Ticket") @XStreamConverter(value = XStreamCDataConverter.class) private String ticket; @XStreamAlias("Latitude") private Double latitude; @XStreamAlias("Longitude") private Double longitude; @XStreamAlias("Precision") private Double precision; @XStreamAlias("Recognition") @XStreamConverter(value = XStreamCDataConverter.class) private String recognition; /////////////////////////////////////// // 群发消息返回的结果 /////////////////////////////////////// /** * 群发的结果. */ @XStreamAlias("Status") @XStreamConverter(value = XStreamCDataConverter.class) private String status; /** * group_id下粉丝数;或者openid_list中的粉丝数. */ @XStreamAlias("TotalCount") private Integer totalCount; /** * 过滤. * (过滤是指特定地区、性别的过滤、用户设置拒收的过滤,用户接收已超4条的过滤)后,准备发送的粉丝数,原则上,filterCount = sentCount + errorCount */ @XStreamAlias("FilterCount") private Integer filterCount; /** * 发送成功的粉丝数. */ @XStreamAlias("SentCount") private Integer sentCount; /** * 发送失败的粉丝数. */ @XStreamAlias("ErrorCount") private Integer errorCount; @XStreamAlias("ScanCodeInfo") private ScanCodeInfo scanCodeInfo = new ScanCodeInfo(); @XStreamAlias("SendPicsInfo") private SendPicsInfo sendPicsInfo = new SendPicsInfo(); @XStreamAlias("SendLocationInfo") private SendLocationInfo sendLocationInfo = new SendLocationInfo(); protected static WxCpXmlMessage fromXml(String xml) { //修改微信变态的消息内容格式,方便解析 xml = xml.replace("</PicList><PicList>", ""); return XStreamTransformer.fromXml(WxCpXmlMessage.class, xml); } protected static WxCpXmlMessage fromXml(InputStream is) { return XStreamTransformer.fromXml(WxCpXmlMessage.class, is); } /** * 从加密字符串转换. */ public static WxCpXmlMessage fromEncryptedXml( String encryptedXml, WxCpConfigStorage wxCpConfigStorage, String timestamp, String nonce, String msgSignature) { WxCpCryptUtil cryptUtil = new WxCpCryptUtil(wxCpConfigStorage); String plainText = cryptUtil.decrypt(msgSignature, timestamp, nonce, encryptedXml); return fromXml(plainText); } public static WxCpXmlMessage fromEncryptedXml( InputStream is, WxCpConfigStorage wxCpConfigStorage, String timestamp, String nonce, String msgSignature) { try { return fromEncryptedXml(IOUtils.toString(is, "UTF-8"), wxCpConfigStorage, timestamp, nonce, msgSignature); } catch (IOException e) { throw new RuntimeException(e); } } /** * <pre> * 当接受用户消息时,可能会获得以下值: * {@link WxConsts.XmlMsgType#TEXT} * {@link WxConsts.XmlMsgType#IMAGE} * {@link WxConsts.XmlMsgType#VOICE} * {@link WxConsts.XmlMsgType#VIDEO} * {@link WxConsts.XmlMsgType#LOCATION} * {@link WxConsts.XmlMsgType#LINK} * {@link WxConsts.XmlMsgType#EVENT} * </pre> */ public String getMsgType() { return this.msgType; } /** * <pre> * 当发送消息的时候使用: * {@link WxConsts.XmlMsgType#TEXT} * {@link WxConsts.XmlMsgType#IMAGE} * {@link WxConsts.XmlMsgType#VOICE} * {@link WxConsts.XmlMsgType#VIDEO} * {@link WxConsts.XmlMsgType#NEWS} * </pre> */ public void setMsgType(String msgType) { this.msgType = msgType; } @Override public String toString() { return ToStringUtils.toSimpleString(this); } @Data @XStreamAlias("ScanCodeInfo") public static class ScanCodeInfo { /** * 扫描类型,一般是qrcode. */ @XStreamAlias("ScanType") @XStreamConverter(value = XStreamCDataConverter.class) private String scanType; /** * 扫描结果,即二维码对应的字符串信息. */ @XStreamAlias("ScanResult") @XStreamConverter(value = XStreamCDataConverter.class) private String scanResult; } @Data @XStreamAlias("SendPicsInfo") public static class SendPicsInfo { @XStreamAlias("PicList") protected final List<Item> picList = new ArrayList<>(); @XStreamAlias("Count") private Long count; @XStreamAlias("item") @Data public static class Item { @XStreamAlias("PicMd5Sum") @XStreamConverter(value = XStreamCDataConverter.class) private String picMd5Sum; } } @Data @XStreamAlias("SendLocationInfo") public static class SendLocationInfo { @XStreamAlias("Location_X") @XStreamConverter(value = XStreamCDataConverter.class) private String locationX; @XStreamAlias("Location_Y") @XStreamConverter(value = XStreamCDataConverter.class) private String locationY; @XStreamAlias("Scale") @XStreamConverter(value = XStreamCDataConverter.class) private String scale; @XStreamAlias("Label") @XStreamConverter(value = XStreamCDataConverter.class) private String label; @XStreamAlias("Poiname") @XStreamConverter(value = XStreamCDataConverter.class) private String poiName; } }
//метод получает неизвестное количество стринг элементов помещает все кроме повторяющихся в аррейлист и выводит отсортированный массив package Array; import java.util.ArrayList; import java.util.Collections; public class array_28 { public static void abc(String ... a){ ArrayList <String> list = new ArrayList<>(); for (String st: a){ if(!list.contains(st)){ list.add(st); } } System.out.println(list); Collections.sort(list); System.out.println(list); } public static void main(String[] args) { abc("g", "a", "o", "m", "e", "a"); } }
package panafana.example.panaf.wouldyourather; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import com.google.firebase.analytics.FirebaseAnalytics; public class SubmitQuestion extends AppCompatActivity { Context ctx = this; String result1; private FirebaseAnalytics mFirebaseAnalytics; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_submit_question); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mFirebaseAnalytics = FirebaseAnalytics.getInstance(this); final EditText qst = findViewById(R.id.question); final EditText qst2 = findViewById(R.id.question2); Button submit = findViewById(R.id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(!(qst.getText().toString().equals(""))&&!(qst2.getText().toString().equals(""))){ String finalqst = qst.getText().toString() +" @ "+ qst2.getText().toString(); SendQuestion s = new SendQuestion(finalqst); s.execute(); } } }); } public class SendQuestion extends AsyncTask<Void, Void, String> { final String mquestion; SendQuestion(String question) { mquestion = question; } @Override protected String doInBackground(Void... params) { String reg_url = "http://83.212.84.230/submitquestion.php"; try { URL url = new URL(reg_url); Uri.Builder builder = new Uri.Builder() .appendQueryParameter("question", mquestion); String query = builder.build().getEncodedQuery(); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conn.connect(); InputStream IS = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(IS)); StringBuilder result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } // Pass data to onPostExecute method String r = (result.toString()); IS.close(); result1=r; Log.d("Response", r); //httpURLConnection.connect(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); return "Connection Error"; } if (result1.contains("Success")) { return "Success"; } else { return "Error"; } } @Override protected void onPostExecute(final String success) { if (success.equals("Success")) { Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "submit question"); mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.POST_SCORE, bundle); finish(); } else { Toast.makeText(ctx, "Error", Toast.LENGTH_LONG).show(); } } } }
/* * This Java source file was generated by the Gradle 'init' task. */ // 애플리케이션 메인클래스 // 애플리케이션을 실행할때 이 클래스를 실행한다. package com.eomcs.lms; import java.util.Scanner; import java.sql.Date; public class App2 { static Scanner scan; public static void main(String[] args) { scan = new Scanner(System.in); int[] no = new int[100]; String[] name = new String[100]; String[] email = new String[100]; String[] password = new String[100]; String[] image = new String[100]; String[] phone = new String[100]; Date[] joinDate = new Date[100]; int i = 0; for (i = 0; i < no.length; i++) { no[i] = getIntValue("번호?"); name[i] = getStringValue("이름?"); email[i] = getStringValue("이메일?"); password[i] = getStringValue("암호?"); image[i] = getStringValue("사진?"); phone[i] = getStringValue("전화?"); joinDate[i] = getDateValue("가입일?"); System.out.println("계속입력하시겠습니까? (y/n)"); String response = scan.nextLine(); if (response.equals("n")) { break; } } for (int i2 = 0; i2 <= i; i2++) { System.out.printf("%s,%s,%s,%s,%s,%s,%s\n", no[i2], name[i2], email[i2], password[i2], image[i2], phone[i2], joinDate[i2]); } System.out.println(); } private static Date getDateValue(String message) { while (true) { try { System.out.print(message); return Date.valueOf(scan.nextLine()); } catch (IllegalArgumentException e) { System.out.println("2019-07-05 형식으로 입력하세요"); } } } private static int getIntValue(String message) { while (true) { try { System.out.print(message); return Integer.parseInt(scan.nextLine()); } catch (NumberFormatException e) { System.out.println("숫자를 입력하세요"); } } } private static String getStringValue(String message) { while (true) { System.out.print(message); return scan.nextLine(); } } }
package by.client.android.railwayapp.ui.page.traintimetable.history; import javax.inject.Inject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.ViewById; import android.app.Dialog; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import by.client.android.railwayapp.AndroidApplication; import by.client.android.railwayapp.R; import by.client.android.railwayapp.model.SearchTrain; import by.client.android.railwayapp.support.database.room.SearchTrainCacheManager; import by.client.android.railwayapp.ui.utils.UiUtils; /** * Отображает историю запросов * * @author PRV */ @EFragment(R.layout.fragment_train_route_history) public class TrainRouteHistoryDialog extends DialogFragment { private static final String TAG = TrainRouteHistoryDialog.class.getSimpleName(); @Inject SearchTrainCacheManager searchTrainCacheManager; @ViewById(R.id.resultListView) ListView resultListView; @ViewById(R.id.clearHistory) TextView clearHistory; @ViewById(R.id.emptyView) TextView emptyView; private ChooseRouteDialogListener chooseRouteDialogListener; private RouteHistoryAdapter routeHistoryAdapter; public static TrainRouteHistoryDialog show(@NonNull FragmentManager fragmentManager, ChooseRouteDialogListener chooseRouteDialogListener) { TrainRouteHistoryDialog trainRouteHistoryDialog = new TrainRouteHistoryDialog_(); trainRouteHistoryDialog.setClickListener(chooseRouteDialogListener); trainRouteHistoryDialog.show(fragmentManager, TAG); return trainRouteHistoryDialog; } @AfterViews void onCreateView() { AndroidApplication.getApp().getApplicationComponent().inject(this); routeHistoryAdapter = new RouteHistoryAdapter(getActivity()); resultListView.setAdapter(routeHistoryAdapter); resultListView.setOnItemClickListener(new RouteItemClickListener()); searchTrainCacheManager.getAll(trains -> routeHistoryAdapter.setData(trains)); clearHistory.setOnClickListener(new ClearHistoryListener()); updateEmptyView(); } @Override public void onStart() { super.onStart(); UiUtils.setFullscreenDialog(getDialog()); } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = super.onCreateDialog(savedInstanceState); dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); return dialog; } private void updateEmptyView() { boolean isEmpty = routeHistoryAdapter.isEmpty(); UiUtils.setVisibility(isEmpty, emptyView); UiUtils.setVisibility(!isEmpty, clearHistory); } public void setClickListener(ChooseRouteDialogListener chooseRouteDialogListener) { this.chooseRouteDialogListener = chooseRouteDialogListener; } private class RouteItemClickListener implements AdapterView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { chooseRouteDialogListener.onSelectedStation(routeHistoryAdapter.getItem(position)); dismiss(); } } private class ClearHistoryListener implements View.OnClickListener { @Override public void onClick(View view) { } } /** * Callback выбора маршрута */ public interface ChooseRouteDialogListener { void onSelectedStation(SearchTrain searchTrain); } }
package com.example.suneel.musicapp.Adapters; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.suneel.musicapp.Fragments.Album; import com.example.suneel.musicapp.Fragments.Genres; import com.example.suneel.musicapp.R; import com.example.suneel.musicapp.Utils.ImageNicer; import com.example.suneel.musicapp.models.SongModel; import java.util.List; /** * Created by suneel on 12/4/18. */ public class AlbumAdapter extends RecyclerView.Adapter<AlbumAdapter.SongListHolder> { private Context context; private List<SongModel> songList; private Fragment mFragment; public AlbumAdapter(Context context, List<SongModel> songList, Album album) { this.context = context; this.songList = songList; this.mFragment = album; } @Override public AlbumAdapter.SongListHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.cardviewalbum, null); return new AlbumAdapter.SongListHolder(view); } @Override public void onBindViewHolder(AlbumAdapter.SongListHolder holder, final int position) { Glide.with(context).load(songList.get(position).getImage()).into(holder.gridImage); holder.gridArtist.setText(songList.get(position).getTitle()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mFragment != null && mFragment instanceof Album) ((Album) mFragment).setGenresList(songList.get(position).getTitle()); } }); } @Override public int getItemCount() { return songList.size(); } public class SongListHolder extends RecyclerView.ViewHolder { ImageView gridImage; TextView gridArtist; public SongListHolder(View itemView) { super(itemView); gridImage = (ImageView) itemView.findViewById(R.id.albumImage); gridArtist = (TextView) itemView.findViewById(R.id.albumartist); } } public void addSongs(List<SongModel> songs) { for (SongModel sm : songs) { songList.add(sm); } notifyDataSetChanged(); } }
package com.lounge.esports.webapps.website.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Web MVC configuration. * * @author afernandez */ @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/styles/**", "/build/**", "/app/**", "/templates/**") .addResourceLocations("classpath:/styles/", "classpath:/build/", "classpath:/app/", "classpath:/templates/"); } }
package com.adifier.domain; import org.springframework.data.jpa.repository.JpaRepository; public interface OdTicketRepository extends JpaRepository<OdTicket, Long> { }
package jpa; import genericcode.PrimitiveType; public enum JavaPrimitiveType { // primitiveTypes.put("long",new PrimitiveType(this.ormfo,"primitive_type__long")); // primitiveTypes.put("Long",new PrimitiveType(this.ormfo,"primitive_type__Long")); // primitiveTypes.put("short",new PrimitiveType(this.ormfo,"primitive_type__short")); // primitiveTypes.put("String",new PrimitiveType(this.ormfo,"primitive_type__String")); LONG{ public String toString(){ return "long"; } public String toIRI() { return "primitive_type__long"; } public String toDjango() { return "models.BigIntegerField"; } }, STRING{ public String toString(){ return "String"; } public String toIRI() { return "primitive_type__string"; } public String toDjango() { return "models.CharField"; } }, SHORT{ public String toString(){ return "short"; } public String toIRI() { return "primitive_type__short"; } public String toDjango() { return "models.SmallIntegerField"; } }, BYTE{ public String toString(){ return "byte"; } public String toIRI() { return "primitive_type__byte"; } public String toDjango() { return "models.integerField"; } }, CHAR{ public String toString(){ return "char"; } public String toIRI() { return "primitive_type__char"; } public String toDjango() { return "models.CharField"; } }, DOUBLE{ public String toString(){ return "double"; } public String toIRI() { return "primitive_type__double"; } public String toDjango() { return "models.FloatField"; } }, FLOAT{ public String toString(){ return "float"; } public String toIRI() { return "primitive_type__float"; } public String toDjango() { return "models.FloatField"; } }, INT{ public String toString(){ return "int"; } public String toIRI() { return "primitive_type__int"; } public String toDjango() { return "models.IntegerField"; } }, BOOL{ public String toString(){ return "boolean"; } public String toIRI() { return "primitive_type__boolean"; } public String toDjango() { return "models.BooleanField"; } }; public static JavaPrimitiveType getJavaPrimitiveType(String codeType) { switch(codeType) { case "boolean": return BOOL; case "long": return LONG; case "Long": return LONG; case "byte": return BYTE; case "int": return INT; case "float": return FLOAT; case "String": return STRING; case "short": return SHORT; case "double": return DOUBLE; case "char": return CHAR; default: System.out.println("[WARN] Erro ao identificar o tipo primitivo (" + codeType + ")..."); } return null; } public String toDjango() { return this.toDjango(); } public String toIRI() { return this.toIRI(); } }
package ir.shayandaneshvar.jottery.config; import ir.shayandaneshvar.jottery.models.Lottery; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class LotteryConfig { @Bean public Lottery lottery() { return new Lottery(); } }
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.reactive.function.server; import java.io.IOException; import java.nio.file.Files; import java.util.List; import java.util.Set; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.codec.HttpMessageWriter; import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpRequest; import org.springframework.web.testfixture.http.server.reactive.MockServerHttpResponse; import org.springframework.web.testfixture.server.MockServerWebExchange; import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma * @since 5.0 */ public class ResourceHandlerFunctionTests { private final Resource resource = new ClassPathResource("response.txt", getClass()); private final ResourceHandlerFunction handlerFunction = new ResourceHandlerFunction(this.resource); private ServerResponse.Context context; @BeforeEach public void createContext() { HandlerStrategies strategies = HandlerStrategies.withDefaults(); context = new ServerResponse.Context() { @Override public List<HttpMessageWriter<?>> messageWriters() { return strategies.messageWriters(); } @Override public List<ViewResolver> viewResolvers() { return strategies.viewResolvers(); } }; } @Test public void get() throws IOException { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("http://localhost")); MockServerHttpResponse mockResponse = exchange.getResponse(); ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults().messageReaders()); Mono<ServerResponse> responseMono = this.handlerFunction.handle(request); Mono<Void> result = responseMono.flatMap(response -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); boolean condition = response instanceof EntityResponse; assertThat(condition).isTrue(); @SuppressWarnings("unchecked") EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response; assertThat(entityResponse.entity()).isEqualTo(this.resource); return response.writeTo(exchange, context); }); StepVerifier.create(result) .expectComplete() .verify(); byte[] expectedBytes = Files.readAllBytes(this.resource.getFile().toPath()); StepVerifier.create(mockResponse.getBody()) .consumeNextWith(dataBuffer -> { byte[] resultBytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(resultBytes); assertThat(resultBytes).isEqualTo(expectedBytes); }) .expectComplete() .verify(); assertThat(mockResponse.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(mockResponse.getHeaders().getContentLength()).isEqualTo(this.resource.contentLength()); } @Test public void head() throws IOException { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.head("http://localhost")); MockServerHttpResponse mockResponse = exchange.getResponse(); ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults().messageReaders()); Mono<ServerResponse> responseMono = this.handlerFunction.handle(request); Mono<Void> result = responseMono.flatMap(response -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); boolean condition = response instanceof EntityResponse; assertThat(condition).isTrue(); @SuppressWarnings("unchecked") EntityResponse<Resource> entityResponse = (EntityResponse<Resource>) response; assertThat(entityResponse.entity().getFilename()).isEqualTo(this.resource.getFilename()); return response.writeTo(exchange, context); }); StepVerifier.create(result).expectComplete().verify(); StepVerifier.create(mockResponse.getBody()).expectComplete().verify(); assertThat(mockResponse.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN); assertThat(mockResponse.getHeaders().getContentLength()).isEqualTo(this.resource.contentLength()); } @Test public void options() { MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options("http://localhost")); MockServerHttpResponse mockResponse = exchange.getResponse(); ServerRequest request = new DefaultServerRequest(exchange, HandlerStrategies.withDefaults().messageReaders()); Mono<ServerResponse> responseMono = this.handlerFunction.handle(request); Mono<Void> result = responseMono.flatMap(response -> { assertThat(response.statusCode()).isEqualTo(HttpStatus.OK); assertThat(response.headers().getAllow()).isEqualTo(Set.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS)); return response.writeTo(exchange, context); }); StepVerifier.create(result) .expectComplete() .verify(); assertThat(mockResponse.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(mockResponse.getHeaders().getAllow()).isEqualTo(Set.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS)); StepVerifier.create(mockResponse.getBody()).expectComplete().verify(); } }
package com.company.threads; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ThreadExtendImpl extends Thread { int count = 0; public void run(){ System.out.println("Thread starting"); try { while (count < 5) { Thread.sleep(500); System.out.println("In thread, count is " + count); count++; } } catch (InterruptedException e){ System.out.println("Thread interrupted"); } System.out.println("Thread terminating"); } public static class LockableObject{ Lock lock; int count; LockableObject(){ lock = new ReentrantLock(); } public synchronized void waitingGame(){ try{ Thread.sleep(3000); } catch(InterruptedException e){ System.out.println("Exception caught"); e.printStackTrace(); } } } }
package com.siicanada.article.service; import com.siicanada.article.exception.ArticleNotFoundException; import com.siicanada.article.exception.TagNotFoundException; import com.siicanada.article.model.ArticleModel; import com.siicanada.article.repository.ArticleRepository; import com.siicanada.article.repository.TagRepository; import com.siicanada.article.repository.entity.ArticleEntity; import com.siicanada.article.repository.entity.TagEntity; import com.siicanada.article.service.mapping.ArticleMapper; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * Implementation Business Logic Layer interface. */ @Component public class ArticleServiceImpl implements ArticleService { @Autowired private ArticleRepository articleRepository; @Autowired private TagRepository tagRepository; @Autowired private ArticleMapper articleMapper; /** * {@inheritDoc} */ @Override public List<ArticleModel> getArticles() { List<ArticleEntity> articleEntities = articleRepository.findAll(); return articleEntities.stream() .map(articleEntity -> articleMapper.entityToModel(articleEntity)).collect( Collectors.toList()); } /** * {@inheritDoc} */ @Override public ArticleModel getArticleById(Integer id) { ArticleEntity articleEntity = articleRepository.findById(id) .orElseThrow(() -> new ArticleNotFoundException("Cannot find article id=" + id)); return articleMapper.entityToModel(articleEntity); } /** * {@inheritDoc} */ @Override public List<ArticleModel> getArticlesByTagDescription(String description) { TagEntity tagEntity = tagRepository.getByDescription(description); if (tagEntity == null) { throw new TagNotFoundException("Cannot find tag by description=" + description); } return tagEntity.getArticles().stream() .map(articleEntity -> articleMapper.entityToModel(articleEntity)).collect( Collectors.toList()); } }
package com.nopcommerce.demo.pages; import com.nopcommerce.demo.utility.Utility; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; public class TopMenuPage extends Utility { //1. create class "TopMenuTest" // 1.1 create method with name "selectMenu" it has one parameter name "menu" of type string // 1.2 This method should click on the menu whatever name is passed as parameter. By computerLink = By.linkText("Computers"); By verifyComputerPage = By.partialLinkText("Compute"); By electronicsLink = By.linkText("Electronics"); By verifyElectronicsPage = By.partialLinkText("Electroni"); By apparelLink = By.linkText("Apparel"); By verifyApparelPage = By.partialLinkText("Appar"); By digitalDownloadsLink = By.linkText("Digital downloads"); By verifyDigitalDowanloadPage = By.partialLinkText("Digital downloa"); By booksLink = By.linkText("Books"); By verifyBooksPage =By.partialLinkText("Books"); By jewelryLink = By.linkText("Jewelry"); By verifyJewelryPage = By.partialLinkText("Jewel"); By giftcardsLink = By.linkText("Gift Cards"); By verifyGiftsCards =By.partialLinkText("Gift Car"); public void selectMenu(String menu) throws InterruptedException { Thread.sleep(1000); if (menu == "Computers") { clickOnElement(computerLink); } else if (menu == "Electronics") { clickOnElement(electronicsLink); } else if (menu == "Apparel") { clickOnElement(apparelLink); } else if (menu == "Digital downloads") { clickOnElement(digitalDownloadsLink); } else if (menu == "Books") { clickOnElement(booksLink); } else if (menu == "Jewelry") { clickOnElement(jewelryLink); } else if (menu == "Gift Cards") { clickOnElement(giftcardsLink); } } public String verifyComputerPages(){ return getTextFromElement(verifyComputerPage); } public String verifyElectronicspages(){ return getTextFromElement(verifyElectronicsPage); } public String verifyAppearlPages(){ return getTextFromElement(verifyApparelPage); } public String verifydigitalDowanload(){ return getTextFromElement(verifyDigitalDowanloadPage); } public String verifyBooksPages(){ return getTextFromElement(verifyBooksPage); } public String verifyJewlrypages(){ return getTextFromElement(verifyJewelryPage); } public String verifyGiftcardspages(){ return getTextFromElement(verifyGiftsCards); } }
package org.bots.services; import lombok.AllArgsConstructor; import org.bots.model.datebase.Client; import org.bots.model.datebase.Subscription; import org.bots.repository.SubscriptionRepository; import org.springframework.stereotype.Service; import java.util.Optional; import java.util.stream.Collectors; @Service @AllArgsConstructor public class SubscriptionService { private final SubscriptionRepository subscriptionRepository; private void subscribe(Client client, Integer movieId){ Subscription subscription; Optional<Subscription> result = subscriptionRepository.findById(movieId); if(result.isPresent()){ subscription = result.get(); }else{ subscription = new Subscription(); subscription.setMovieId(movieId); subscription.getSubscribers().add(client); } subscriptionRepository.save(subscription); } public void unsubscribe(Client client, Integer movieId){ Optional<Subscription> result = subscriptionRepository.findById(movieId); if(result.isPresent()){ Subscription subscription = result.get(); subscription.setSubscribers(subscription.getSubscribers().stream().filter(cl -> !(cl.getChatId().equals(client.getChatId()) && cl.getType().equals(client.getType()) && cl.getClientId().equals(client.getClientId()))) .collect(Collectors.toList())); if(subscription.getSubscribers().isEmpty()) subscriptionRepository.delete(subscription); else subscriptionRepository.save(subscription); } } public boolean isSubscribed(Client client, Integer movieId){ return subscriptionRepository.existsByMovieIdAndSubscribers(movieId, client); } public void changeSubscriptinState(Client client, Integer movieId){ if(isSubscribed(client, movieId)){ unsubscribe(client,movieId); }else{ subscribe(client, movieId); } } }
import com.sun.org.apache.regexp.internal.RE; import com.sun.xml.internal.bind.WhiteSpaceProcessor; public class Komplex { double re; double im; public Komplex(double r, double i) { this.re = r; this.im = i; } public static void main (String[] args) { Komplex a = new Komplex(6,8); Komplex b = new Komplex(5, 2); Komplex c = a.add(b); Komplex d = a. multiplay(b); } } private Komplex add(Komplex b) { return new Komplex(this.re+b.re, this.im+b.im); private Komplex multiplay(Komplex b) { return Komplex( re this.re-b.re, im this im*b.im ); //a.add(b)= ( Komplex a add Komplex b + im); } }
package com.bruce.builder.improve; public class CommonHouse extends HouseBuilder { @Override public void buildBasic() { System.out.println("普通房子打地基"); } @Override public void buildWall() { System.out.println("普通房子打墙"); } @Override public void buildRoof() { System.out.println("普通房子盖房顶"); } }
package src.modulo2.exercicios; import java.awt.event.*; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import com.sun.opengl.util.*; public class Exercicio04 implements GLEventListener, MouseListener, MouseMotionListener, KeyListener { private GL gl; private GLU glu; private GLintPoint[] listaVertices; private int indiceLista; private int prevMouseX, prevMouseY; private float diffX, diffY; private boolean mouseRButtonDown = false; private boolean flg_criarVertice = false; private int ultimoPonto; public static void main(String[] args) { Frame frame = new Frame("Exercicio 04 - Mouse e Teclado"); GLCanvas canvas = new GLCanvas(); canvas.addGLEventListener(new Exercicio04()); frame.add(canvas); frame.setSize(640, 480); final Animator animator = new Animator(canvas); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Run this on another thread than the AWT event queue to // make sure the call to Animator.stop() completes before // exiting new Thread(new Runnable() { public void run() { animator.stop(); System.exit(0); } }).start(); } }); // Center frame frame.setLocationRelativeTo(null); frame.setVisible(true); animator.start(); } public void init(GLAutoDrawable drawable) { // Interface para as funcoes OpenGL gl = drawable.getGL(); glu = new GLU(); listaVertices = new GLintPoint[]{}; indiceLista = 0; ultimoPonto = 0; //Informacoes da placa gráfica System.err.println("INIT GL IS: " + gl.getClass().getName()); System.err.println("GL_VENDOR: " + gl.glGetString(GL.GL_VENDOR)); System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER)); System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION)); // Enable VSync gl.setSwapInterval(1); // Setup the drawing area and shading mode gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); //Cor de fundo branco gl.glColor3f(0.0f, 0.0f, 0.0f); //Cor do desenho gl.glPointSize(4.0f); //um ponto eh 4 x 4 pixels gl.glLineWidth(2.0f); gl.glShadeModel(GL.GL_FLAT); drawable.addMouseListener(this); drawable.addMouseMotionListener(this); drawable.addKeyListener(this); } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { gl = drawable.getGL(); glu = new GLU(); if (height <= 0) { // avoid a divide by zero error! height = 1; } final float h = (float) width / (float) height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluOrtho2D(0.0f, 640.0f, 480.0f, 0.0f); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); } public void display(GLAutoDrawable drawable) { gl = drawable.getGL(); // Clear the drawing area gl.glClear(GL.GL_COLOR_BUFFER_BIT); // Reset the current matrix to the "identity" gl.glLoadIdentity(); desenharVerticesLista(drawable); gl.glEnd(); // Flush all drawing operations to the graphics card gl.glFlush(); } public void desenharVerticesLista(GLAutoDrawable drawable){ gl = drawable.getGL(); // Clear the drawing area gl.glClear(GL.GL_COLOR_BUFFER_BIT); if(listaVertices.length > 0){ for (int i = 0; i < listaVertices.length; i++) { gl.glBegin(i); gl.glVertex2i(listaVertices[i].getX(), listaVertices[i].getY()); } gl.glEnd(); } // Flush all drawing operations to the graphics card gl.glFlush(); } public void desenharPontos(){ gl.glClear(GL.GL_COLOR_BUFFER_BIT); // clear the screen gl.glBegin(GL.GL_POINTS); for (int i = 0; i <= ultimoPonto; i++) { gl.glVertex2i(listaVertices[i].getX(), listaVertices[i].getY()); } gl.glEnd(); gl.glFlush(); } public void desenharLinhas(){ gl.glBegin(GL.GL_LINE_STRIP); gl.glEnd(); } /** * Limpa a tela * @param drawable */ public void limparTela(){ gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); listaVertices = new GLintPoint[]{}; } public void criaNovoPonto(int x, int y){ GLintPoint[] listaAntiga = listaVertices; if(listaVertices.length > 0){ listaVertices = new GLintPoint[listaAntiga.length + 1]; for (int i = 0; i < listaVertices.length - 1; i++) { listaVertices[i] = new GLintPoint(listaAntiga[i].getX(), listaAntiga[i].getY()); } listaVertices[listaAntiga.length] = new GLintPoint(x,y); }else{ listaVertices = new GLintPoint[]{new GLintPoint(x,y)}; } } public void ligarVertices(){ if(listaVertices.length >= 2){ gl.glBegin(GL.GL_LINE_STRIP); for (int i = 0; i < listaVertices.length; i++) { gl.glVertex2i(listaVertices[i].getX(), listaVertices[i].getY()); } gl.glEnd(); } } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } public void mouseClicked(MouseEvent e) { if(flg_criarVertice){ System.out.println("Criar vertice"); criaNovoPonto(prevMouseX, prevMouseY); ultimoPonto++; } // ligarVertices(); //throw new UnsupportedOperationException("Not supported yet."); } public void mousePressed(MouseEvent e) { prevMouseX = e.getX(); prevMouseY = e.getY(); if ((e.getModifiers() & e.BUTTON3_MASK) != 0) { mouseRButtonDown = true; } System.out.println("Mouse: X - " + prevMouseX + " | Y - " + prevMouseY); } public void mouseReleased(MouseEvent e) { if ((e.getModifiers() & e.BUTTON3_MASK) != 0) { mouseRButtonDown = false; } } public void mouseEntered(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseExited(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void mouseDragged(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (mouseRButtonDown) { diffX = (float) (x - prevMouseX); diffY = (float) (y - prevMouseY); } else { prevMouseX = x; prevMouseY = y; } } public void mouseMoved(MouseEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } public void keyTyped(KeyEvent e) { // new UnsupportedOperationException("Not supported yet."); } @SuppressWarnings("static-access") public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case 84: //T System.exit(1); break; case 27: //ESC System.exit(1); break; case 67: //C - cria um novo vertice if(flg_criarVertice){ flg_criarVertice = false; }else{ flg_criarVertice = true; } break; case 65: //A System.out.println("February"); break; case 77: //M System.out.println("February"); break; case 76: //L System.out.println("February"); break; case 82: //R System.out.println("Limpar tela"); limparTela(); break; default: System.out.println("Invalid month."); break; } System.out.println(String.format("Tecla: %s - Código Unicode: %d", e.getKeyText(e.getKeyCode()), e.getKeyCode())); } public void keyReleased(KeyEvent e) { //throw new UnsupportedOperationException("Not supported yet."); } }
package main.feed; import main.feed.DBwork.DBFeedMessage; import main.feed.DBwork.FeedDataStore; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; @RestController public class ParserController { @RequestMapping(value = "/getNews", method = RequestMethod.POST) public List<DBFeedMessage> parse(@RequestParam(value = "input", defaultValue = "") String input) throws Exception { try { return FeedDataStore.getInstance().getFeedByKeword(input.trim()); } catch (NoSuchElementException e) { return new ArrayList<>(); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package nove; import java.util.Scanner; import javax.swing.JOptionPane; /** * * @author João Pedro Gambirasio da Rosa */ public class Nove { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner ler = new Scanner(System.in); int positivo, val, cont; cont = 0; positivo = 0; while (cont != 10) { val = Integer.parseInt(JOptionPane.showInputDialog("Informe o valor:")); cont += 1; if (val >= 0) { positivo += 1; } } JOptionPane.showMessageDialog(null, "Quantidade de positivos:\n" + positivo); } }
package com.infohold.elh.base.web.rest; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.infohold.bdrp.Constants; import com.infohold.bdrp.org.model.Org; import com.infohold.core.dao.Page; import com.infohold.core.manager.GenericManager; import com.infohold.core.utils.JSONUtils; import com.infohold.core.utils.StringUtils; import com.infohold.core.web.MediaTypes; import com.infohold.core.web.rest.BaseRestController; import com.infohold.core.web.utils.Result; import com.infohold.core.web.utils.ResultUtils; import com.infohold.elh.base.model.Doctor; import com.infohold.elh.base.model.DoctorDuty; /** * 医生管理 * * @author Administrator * */ @RestController @RequestMapping("/elh/doctor") public class DoctorRestController extends BaseRestController { @Autowired private GenericManager<Doctor, String> doctorManager; @Autowired private GenericManager<DoctorDuty, String> doctorDutyManager; /******************************************************机构端方法*************************************************************************/ /** * ELH_HOSP_009 查询医生列表 HMP1.3 1 * * @param start * @param pageSize * @param data * @return */ @RequestMapping(value = "/list/{start}/{pageSize}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forList(@PathVariable(value = "start") int start, @PathVariable(value = "pageSize") int pageSize, @RequestParam(value = "data", defaultValue = "") String data) { log.info("查询列表数据,输入查询条件为:【" + data + "】"); Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); Doctor doctor = JSONUtils.deserialize(data, Doctor.class); StringBuilder sb = new StringBuilder(" from Doctor where hospitalId = ? "); List<String> cdList = new ArrayList<String>(); cdList.add(orgId); if (doctor!=null && StringUtils.isNoneBlank(doctor.getHospitalId())) { sb.append(" and hospitalId = ?"); cdList.add(doctor.getHospitalId()); } if (doctor!=null && StringUtils.isNoneBlank(doctor.getDepartmentId())) { sb.append(" and departmentId = ?"); cdList.add(doctor.getDepartmentId()); } if (doctor!=null && StringUtils.isNoneBlank(doctor.getIsExpert())) { sb.append(" and isExpert = ?"); cdList.add(doctor.getIsExpert()); } sb.append(" order by sortno"); Page page = new Page(); page.setStart(start); page.setPageSize(pageSize); page.setQuery(sb.toString()); page.setValues(cdList.toArray()); this.doctorManager.findPage(page); return ResultUtils.renderSuccessResult(page); } /** * ELH_HOSP_010 查询医院医生信息 HMP1.3 1 * * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forInfo(@PathVariable("id") String id) { Doctor doctor = this.doctorManager.get(id); /*Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); if(!orgId.equals(doctor.getHospitalId())){ return ResultUtils.renderFailureResult("无权修改其他医院医生"); }*/ return ResultUtils.renderSuccessResult(doctor); } /** * ELH_HOSP_011 维护医院医生信息 HMP1.3 1 * * @param data * @return */ @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forCreate(@RequestBody String data) { Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); Doctor doctor = JSONUtils.deserialize(data, Doctor.class); doctor.setHospitalId(orgId); doctor = this.doctorManager.save(doctor); return ResultUtils.renderSuccessResult(doctor); } /** * ELH_HOSP_011 维护医院医生信息 HMP1.3 1 * * @param id * @param data * @return */ @SuppressWarnings("rawtypes") @RequestMapping(value = "/{id}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8) public Result forUpdate(@PathVariable("id") String id, @RequestBody String data) { Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); Doctor doctor = this.doctorManager.get(id); if(!orgId.equals(doctor.getHospitalId())){ return ResultUtils.renderFailureResult("无权修改其他医院医生"); } Map doctorMap = JSONUtils.deserialize(data, Map.class); if (null != doctorMap.get("idHlht")) { doctor.setIdHlht(doctorMap.get("idHlht").toString()); // 院方ID } if (null != doctorMap.get("name")) { doctor.setName(doctorMap.get("name").toString()); // 姓名 } if (null != doctorMap.get("gender")) { doctor.setGender(doctorMap.get("gender").toString()); // 性别 } if (null != doctorMap.get("jobNum")) { doctor.setJobNum(doctorMap.get("jobNum").toString()); // 工号 } if (null != doctorMap.get("certNum")) { doctor.setCertNum(doctorMap.get("certNum").toString()); // 资格证书号 } if (null != doctorMap.get("degrees")) { doctor.setDegrees(doctorMap.get("degrees").toString()); // 学历 } if (null != doctorMap.get("major")) { doctor.setMajor(doctorMap.get("major").toString()); // 专业 } if (null != doctorMap.get("jobTitle")) { doctor.setJobTitle(doctorMap.get("jobTitle").toString()); // 职称 } if (null != doctorMap.get("speciality")) { doctor.setSpeciality(doctorMap.get("speciality").toString()); // 特长 } if (null != doctorMap.get("entryTime")) { String strDate = doctorMap.get("entryTime").toString(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "); Date date; try { date = sdf.parse(strDate); doctor.setEntryTime(date); // 入职时间 } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (null != doctorMap.get("departmentId")) { doctor.setDepartmentId(doctorMap.get("departmentId").toString()); // 部门ID } if (null != doctorMap.get("deptName")) { doctor.setDeptName(doctorMap.get("deptName").toString()); // 部门名称 } if (null != doctorMap.get("hospitalId")) { doctor.setHospitalId(doctorMap.get("hospitalId").toString()); // 医院ID } if (null != doctorMap.get("hosName")) { doctor.setHosName(doctorMap.get("hosName").toString()); // 医院名称 } if (null != doctorMap.get("portrait")) { doctor.setPortrait(doctorMap.get("portrait").toString()); // 照片 } if (null != doctorMap.get("clinic")) { doctor.setClinic(doctorMap.get("clinic").toString()); // 诊治代码 } if (null != doctorMap.get("clinicDesc")) { doctor.setClinicDesc(doctorMap.get("clinicDesc").toString()); // 诊治描述 } if (null != doctorMap.get("isExpert")) { doctor.setIsExpert(doctorMap.get("isExpert").toString()); // 是否专家 } if (null != doctorMap.get("birthday")) { doctor.setBirthday(doctorMap.get("birthday").toString()); // 出生日期 } if (null != doctorMap.get("entryDate")) { doctor.setEntryDate(doctorMap.get("entryDate").toString()); // 从医日期 } /*if (null != doctorMap.get("sortno")) { String str = doctorMap.get("sortno").toString(); try { int a = Integer.parseInt(str); doctor.setSortno(a);// 排序码 } catch (NumberFormatException e) { e.printStackTrace(); } }*/ Doctor savedDoctor = this.doctorManager.save(doctor); return ResultUtils.renderSuccessResult(savedDoctor); } /** * ELH_HOSP_012 删除医生 HMP1.3 1 * * @param id * @return */ @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forDelete(@PathVariable("id") String id) { Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); Doctor doctor = this.doctorManager.get(id); if(!orgId.equals(doctor.getHospitalId())){ return ResultUtils.renderFailureResult("无权修改其他医院医生"); } Doctor doctorMoved = this.doctorManager.delete(id); return ResultUtils.renderSuccessResult(doctorMoved); } /** * ELH_HOSP_007 设置特色科室special * @param id * @param data * @return */ @RequestMapping(value = "/expert/set/{id}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8) public Result forSetExpert(@PathVariable("id") String id) { Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); Doctor doctor = this.doctorManager.get(id); if(!orgId.equals(doctor.getHospitalId())){ return ResultUtils.renderFailureResult("科室不属于当前机构"); } doctor.setIsExpert("1"); Doctor doctorUped = this.doctorManager.save(doctor); return ResultUtils.renderSuccessResult(doctorUped); } /** * ELH_HOSP_007 设置特色科室special * @param id * @param data * @return */ @RequestMapping(value = "/expert/move/{id}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8) public Result forMoveExpert(@PathVariable("id") String id) { Org loginOrg = (Org)this.getSession().getAttribute(Constants.ORG_KEY); if(null==loginOrg || "".equals(loginOrg)){ return ResultUtils.renderFailureResult("未找到当前登录机构"); } String orgId = loginOrg.getId(); Doctor doctor = this.doctorManager.get(id); if(!orgId.equals(doctor.getHospitalId())){ return ResultUtils.renderFailureResult("科室不属于当前机构"); } doctor.setIsExpert("0"); Doctor doctorUped = this.doctorManager.save(doctor); return ResultUtils.renderSuccessResult(doctorUped); } /** * ELH_HOSP_013 按医生查询常规出诊信息 时间及挂号费 1 * * @param start * @param pageSize * @param data * @return *//* @RequestMapping(value = "/duty/{id}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forDutyInfo(@PathVariable("id") String id) { DoctorDuty DoctorDuty = this.doctorDutyManager.get(id); return ResultUtils.renderSuccessResult(DoctorDuty); } *//** * ELH_HOSP_014 维护医生常规出诊信息 1 * * @param data * @return *//* @RequestMapping(value = "/duty/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forDutyCreate(@RequestBody String data) { DoctorDuty doctorDuty = JSONUtils.deserialize(data, DoctorDuty.class); Map doctorDutyMap = JSONUtils.deserialize(data, Map.class); if (null != doctorDutyMap.get("doctor")) { doctorDuty.setDoctor(doctorDuty.get("doctor").toString()); // 医生 } if (null != doctorDutyMap.get("name")) { doctorDuty.setName(doctorDuty.get("name").toString()); // 医生姓名 } doctorDuty = this.doctorDutyManager.save(doctorDuty); return ResultUtils.renderSuccessResult(doctorDuty); } *//** * ELH_HOSP_014 维护医生常规出诊信息 1 * * @param id * @param data * @return *//* @RequestMapping(value = "/duty/{id}", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8) public Result forDutyUpdate(@PathVariable("id") String id, @RequestBody String data) { DoctorDuty DoctorDuty = this.doctorDutyManager.get(id); DoctorDuty savedDoctorDuty = this.doctorDutyManager.save(DoctorDuty); return ResultUtils.renderSuccessResult(savedDoctorDuty); } *//** * ELH_HOSP_015 删除医生常规出诊信息 1 * * @param id * @return *//* @RequestMapping(value = "/duty/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forDutyDelete(@PathVariable("id") String id) { DoctorDuty DoctorDuty = this.doctorDutyManager.delete(id); return ResultUtils.renderSuccessResult(DoctorDuty); } *//** * @param start * @param pageSize * @param data * @return *//* @RequestMapping(value = "/duty/list/{start}/{pageSize}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forDutyList(@PathVariable(value = "start") int start, @PathVariable(value = "pageSize") int pageSize, @RequestParam(value = "data", defaultValue = "") String data) { Page page = new Page(); page.setStart(start); page.setPageSize(pageSize); page.setQuery("from DoctorDuty "); this.doctorDutyManager.findPage(page); return ResultUtils.renderSuccessResult(page); }*/ /******************************************************机构端方法end*************************************************************************/ /******************************************************app端方法*************************************************************************/ /** * ELH_HOSP_009 查询医生列表 HMP1.3 1 * * @param start * @param pageSize * @param data * @return */ @RequestMapping(value = "/app/list/{start}/{pageSize}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forAppList(@PathVariable(value = "start") int start, @PathVariable(value = "pageSize") int pageSize, @RequestParam(value = "data", defaultValue = "") String data) { log.info("查询列表数据,输入查询条件为:【" + data + "】"); Doctor doctor = JSONUtils.deserialize(data, Doctor.class); StringBuilder sb = new StringBuilder(" from Doctor where 1=1"); List<String> cdList = new ArrayList<String>(); if (doctor!=null && StringUtils.isNoneBlank(doctor.getHospitalId())) { sb.append(" and hospitalId = ?"); cdList.add(doctor.getHospitalId()); } if (doctor!=null && StringUtils.isNoneBlank(doctor.getDepartmentId())) { sb.append(" and departmentId = ?"); cdList.add(doctor.getDepartmentId()); } if (doctor!=null && StringUtils.isNoneBlank(doctor.getIsExpert())) { sb.append(" and isExpert = ?"); cdList.add(doctor.getIsExpert()); } sb.append(" order by sortno"); Page page = new Page(); page.setStart(start); page.setPageSize(pageSize); page.setQuery(sb.toString()); page.setValues(cdList.toArray()); this.doctorManager.findPage(page); return ResultUtils.renderSuccessResult(page); } /******************************************************app端方法end*************************************************************************/ /******************************************************运营端方法*************************************************************************/ /******************************************************运营端方法end*************************************************************************/ }
package controllers; import helpers.MessageDialog; import helpers.SceneChanger; import javafx.concurrent.Service; import javafx.concurrent.Task; import java.util.List; import java.util.Map; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.stage.Stage; import models.Course; import models.CurrentMoodle; import models.Errors; import models.Moodle; import suppliers.CourseSupplier; import suppliers.LoginSupplier; import suppliers.MoodleCourseSupplier; import suppliers.MoodleLoginSupplier; public class LoadingInfoController { public Button nextSceneButton; // Parameters from the previous scene private String name; private boolean getNameAutomatically; private String url; private String username; private String password; // Currently only Moodle is supported, so it's directly defined as MoodleLoginSupplier() private LoginSupplier loginSupplier = new MoodleLoginSupplier(); private LoginService loginService = new LoginService(); private CourseSupplier courseSupplier = new MoodleCourseSupplier(); private CourseService courseService = new CourseService(); private CourseInfoService courseInfoService = new CourseInfoService(); // FXML elements public Label loginLabel; public ProgressBar loginProgress; public Label coursesLabel; public ProgressBar coursesProgress; public Label coursesInfoLabel; public ProgressBar coursesInfoProgress; public LoadingInfoController(String name, boolean getNameAutomatically, String url, String username, String password) { this.name = name; this.getNameAutomatically = getNameAutomatically; this.url = url; this.username = username; this.password = password; // Starts the LoginService Task loginService.restart(); } // Login in a separate thread private class LoginService extends Service<Map<String, String>> { @Override protected Task<Map<String, String>> createTask() { return new Task<Map<String, String>>() { @Override protected Map<String, String> call() throws Exception { return loginSupplier.login(url, username, password); } @Override protected void succeeded() { // The task succeeded, setup the Moodle correctly Map<String, String> response = getValue(); Moodle currentMoodle = new Moodle( getNameAutomatically ? response.get("sitename") : name, url, username, response.get("token"), Integer.parseInt(response.get("userid")) ); CurrentMoodle.newMoodle(currentMoodle); // Indicate the completion of the task in the UI loginLabel.setText(loginLabel.getText() + " ✅"); loginProgress.setProgress(1.00); coursesProgress.setProgress(ProgressBar.INDETERMINATE_PROGRESS); // Move to the next step courseService.restart(); } @Override protected void failed() { Throwable error = getException(); // Display error switch (error.getMessage()) { case "\"enablewsdescription\"": MessageDialog.errorDialog(Errors.INCOMPATIBLE_MOODLE); break; case "\"missingparam\"": MessageDialog.errorDialog(Errors.MISSING_PARAMS); break; case "\"invalidlogin\"": MessageDialog.errorDialog(Errors.INVALID_CREDENTIALS); break; default: MessageDialog.errorDialog("Moodle returned this error: " + error); break; } returnToPreviousScene(); } }; } } // Get all courses without files, modules or folders private class CourseService extends Service<List<Course>> { @Override protected Task<List<Course>> createTask() { return new Task<List<Course>>() { @Override protected List<Course> call() throws Exception { return courseSupplier.getAllCourses(); } @Override protected void succeeded() { // All courses were successfully obtained CurrentMoodle.getMoodle().setCourses(getValue()); // Indicate the completion of the task in the UI coursesLabel.setText(coursesLabel.getText() + " ✅"); coursesProgress.setProgress(1.00); // Move to the next step courseInfoService.restart(); } @Override protected void failed() { MessageDialog.errorDialog(Errors.COURSES_ERROR); returnToPreviousScene(); } }; } } // Fill the courses private class CourseInfoService extends Service<Void> { @Override protected Task<Void> createTask() { return new Task<Void>() { @Override protected Void call() throws Exception { // Since the progress bar needs to be updated, the loop logic is done here Moodle currentMoodle = CurrentMoodle.getMoodle(); double step = 1 / (double) currentMoodle.getCourses().size(); double currentProgress = 0.0; for (Course c : currentMoodle.getCourses()) { courseSupplier.getCourseInfo(c); currentProgress += step; System.out.println(currentProgress); coursesInfoProgress.setProgress(currentProgress); } return null; } @Override protected void succeeded() { // All courses were successfully filled // Indicate the completion of the task in the UI coursesInfoLabel.setText(coursesInfoLabel.getText() + " ✅"); nextSceneButton.setDisable(false); } @Override protected void failed() { // The error message can be re-used MessageDialog.errorDialog(Errors.COURSES_ERROR); returnToPreviousScene(); } }; } } public void nextScene() { SceneChanger sc = new SceneChanger((Stage) loginLabel.getScene().getWindow()); sc.changeScene("MoodleActions/ChooseCourses.fxml"); } private void returnToPreviousScene() { SceneChanger sc = new SceneChanger((Stage) loginLabel.getScene().getWindow()); MoodleInfoController nextSceneController = new MoodleInfoController(name, getNameAutomatically, url, username, password); sc.changeSceneWithFactory("MoodleActions/MoodleInfo.fxml", nextSceneController); } }
package quiz.runner.ashish; public class QuizRunner { private QuizRunner() { } public static void main(String[] args) { Quiz1Solution.main(args); Quiz2Solution.main(args); } }
package ru.job4j.search; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; /** * Класс PriorityQueue реализует сущность Очередь с приоритетом. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2018-11-29 * @since 2018-11-29 */ public class PriorityQueue { /** * Очередь. */ private final LinkedList<Task> tasks = new LinkedList<>(); /** * Добавляет задачу в очередь. * @param task добавляемая задача. */ public void put(Task task) { if (this.tasks.size() == 0) { this.tasks.add(task); } else { List<Task> list = this.tasks.stream().filter(x -> x.getPriority() > task.getPriority()).limit(1).collect(Collectors.toList()); if (list.size() == 0) { this.tasks.add(task); } else { this.tasks.add(this.tasks.indexOf(list.get(0)), task); } } } /** * Получает задачу с максимальным приоритетом. * @return задача с максимальным приоритетом. */ public Task take() { return this.tasks.poll(); } }
package com.driveanddeliver.model; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; /** * * @author Amandeep Singh Dhammu * */ @Entity @Table(name = "user") public class User { @Id @Column(name = "user_id") @GeneratedValue private int id; @Column(name = "name") private String name; @Column(name = "userName") private String username; @Column(name = "type_of_user") private String typeOfUser; @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(mappedBy = "user", cascade = CascadeType.ALL) private List<Address> addresses; @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(mappedBy = "user" , cascade = CascadeType.ALL) private List<Trip> trips; @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(mappedBy = "user" , cascade = CascadeType.ALL) private List<MyPackage> packages; @ManyToMany @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles; @Column(name="password") private String password; @Transient private String passwordConfirm; public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } public List<Trip> getTrips() { return trips; } public void setTrips(List<Trip> trips) { this.trips = trips; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTypeOfUser() { return typeOfUser; } public void setTypeOfUser(String typeOfUser) { this.typeOfUser = typeOfUser; } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } public List<MyPackage> getPackages() { return packages; } public void setPackages(List<MyPackage> packages) { this.packages = packages; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPasswordConfirm() { return passwordConfirm; } public void setPasswordConfirm(String passwordConfirm) { this.passwordConfirm = passwordConfirm; } }
package com.zhongyp.spring.demo.annotation; import org.springframework.stereotype.Controller; @Controller("login") public class LoginController { public void login(){ System.out.println("��Ҫ��¼��"); } }
package com.softeem.dao; import java.util.List; import com.softeem.bean.CustomerInfoBean; public interface ICustomerInfoDao { /** * 添加用户 * @param cusInfo * @return */ int addCustomInfo(CustomerInfoBean cusInfo); /** * 批量或单一删除客户 * @param cusIDs * @return */ int delCustomerInfo(String[] cusIDs); /** * 修改用户 * @param cusName * @return */ int updateCustomerInfo(CustomerInfoBean cusInfo); /** * 根据ID查询 * @param cusID * @return */ CustomerInfoBean queryCustomerByID(String cusID); /** * 根据用户名查询 * @param cusName * @return */ CustomerInfoBean queryCustomerByName(String cusName); /** * 查询所有用户 * @return */ List<CustomerInfoBean> queryAllCustomer(); }
package com.buildud.javacv; import com.buildud.tools.ScreenShotUtils; import org.bytedeco.javacpp.avcodec; import org.bytedeco.javacpp.avutil; import org.bytedeco.javacv.FFmpegFrameRecorder; import org.springframework.boot.CommandLineRunner; import java.io.OutputStream; public class BudScreenRecordFrameRecorder extends FFmpegFrameRecorder{ public BudScreenRecordFrameRecorder(OutputStream outputStream, int imageWidth, int imageHeight) { this(outputStream, imageWidth, imageHeight,25); } public BudScreenRecordFrameRecorder(OutputStream outputStream, int imageWidth, int imageHeight,int frameRate) { super(outputStream, imageWidth, imageHeight); setDefaultParams(frameRate); } public BudScreenRecordFrameRecorder(String outputStream, int imageWidth, int imageHeight,int frameRate) { super(outputStream, imageWidth, imageHeight); setDefaultParams(frameRate); } private void setDefaultParams(int frameRate){ this.setVideoCodec(avcodec.AV_CODEC_ID_H264); // 28 this.setFormat("h264"); this.setSampleRate(44100); this.setFrameRate(frameRate); this.setVideoQuality(0); this.setVideoOption("crf", "23"); // 2000 kb/s, 720P视频的合理比特率范围 this.setVideoBitrate(4*1024*1024); /** * 权衡quality(视频质量)和encode speed(编码速度) values(值): ultrafast(终极快),superfast(超级快), * veryfast(非常快), faster(很快), fast(快), medium(中等), slow(慢), slower(很慢), * veryslow(非常慢) * ultrafast(终极快)提供最少的压缩(低编码器CPU)和最大的视频流大小;而veryslow(非常慢)提供最佳的压缩(高编码器CPU)的同时降低视频流的大小 * 参考:https://trac.ffmpeg.org/wiki/Encode/H.264 官方原文参考:-preset ultrafast as the * name implies provides for the fastest possible encoding. If some tradeoff * between quality and encode speed, go for the speed. This might be needed if * you are going to be transcoding multiple streams on one machine. */ this.setVideoOption("preset", "ultrafast"); this.setPixelFormat(avutil.AV_PIX_FMT_YUV420P); // yuv420p } }
package c150; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @author 方康华 * @title BinaryTreeZigzagLevelOrderTraversal * @projectName leetcode * @description No.103 Medium * @date 2019/7/24 19:47 */ public class BinaryTreeZigzagLevelOrderTraversal { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); Queue<TreeNode> q = new LinkedList<>(); int depth = 0; if(root != null) q.add(root); while(q.size() > 0) { List<Integer> layer = new ArrayList<>(); int cnt = q.size(); for(int i = 0; i < cnt; i++){ TreeNode top = q.poll(); if(top.left != null) q.add(top.left); if(top.right != null) q.add(top.right); if(depth % 2 == 0) layer.add(top.val); else layer.add(0, top.val); } depth++; result.add(layer); } return result; } public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(9); root.right = new TreeNode(20); root.right.left = new TreeNode(15); root.right.right = new TreeNode(7); zigzagLevelOrder(null); } }
package business.model; public interface IUser { public String getLogin(); public String getPassword(); public Date getBirthDate(); public void setLogin(String login); public void setPassword(String password); public void setBirthDate(Date birthDate); }
package com.example.booksapi.persistence; import com.example.booksapi.domain.Book; import com.example.booksapi.domain.event.DomainEvent; import com.example.booksapi.publisher.EventPublisher; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; @RequiredArgsConstructor @Component public class EventSourcedBookRepository implements BookRepository { private final EventPublisher eventPublisher; private final Map<UUID, List<DomainEvent>> events = new ConcurrentHashMap<>(); @Override public void save(Book book) { List<DomainEvent> newChanges = book.getChanges(); List<DomainEvent> currentChanges = events.getOrDefault(book.getId(), new ArrayList<>()); currentChanges.addAll(newChanges); events.put(book.getId(), currentChanges); book.flushChanges(); newChanges.forEach(eventPublisher::sendEvent); } @Override public Book find(UUID id) { if (!events.containsKey(id)) { return null; } return Book.recreateFrom(id, events.get(id)); } public Book find(UUID id, Instant timestamp) { if (!events.containsKey(id)) { return null; } List<DomainEvent> domainEvents = events.get(id) .stream() .filter(event -> !event.occuredAt().isAfter(timestamp)) .collect(Collectors.toList()); return Book.recreateFrom(id, domainEvents); } }
/** * The MIT License (MIT) * Copyright (c) 2012-present 铭软科技(mingsoft.net) * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package net.mingsoft.cms.action.web; import cn.hutool.core.util.ObjectUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import net.mingsoft.base.entity.ResultData; import net.mingsoft.basic.bean.EUListBean; import net.mingsoft.basic.util.BasicUtil; import net.mingsoft.cms.bean.ContentBean; import net.mingsoft.cms.biz.IContentBiz; import net.mingsoft.cms.biz.IHistoryLogBiz; import net.mingsoft.cms.entity.ContentEntity; import net.mingsoft.cms.entity.HistoryLogEntity; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import springfox.documentation.annotations.ApiIgnore; import java.util.Date; import java.util.List; /** * 文章管理控制层 * @author 铭飞开发团队 * 创建日期:2019-11-28 15:12:32<br/> * 历史修订:<br/> */ @Api(tags={"前端-内容模块接口"}) @Controller("WebcmsContentAction") @RequestMapping("/cms/content") public class ContentAction extends net.mingsoft.cms.action.BaseAction{ /** * 注入文章业务层 */ @Autowired private IContentBiz contentBiz; @Autowired private IHistoryLogBiz historyLogBiz; /** * 查询文章列表接口 * @param content 文章 * @return */ @ApiOperation(value = "查询文章列表接口") @ApiImplicitParams({ @ApiImplicitParam(name = "contentTitle", value = "文章标题", required =false,paramType="query"), @ApiImplicitParam(name = "categoryId", value = "所属栏目", required =false,paramType="query"), @ApiImplicitParam(name = "contentType", value = "文章类型", required =false,paramType="query"), @ApiImplicitParam(name = "flag", value = "文章类型", required =false,paramType="query"), @ApiImplicitParam(name = "noflag", value = "排除文章类型", required =false,paramType="query"), @ApiImplicitParam(name = "contentDisplay", value = "是否显示", required =false,paramType="query"), @ApiImplicitParam(name = "contentAuthor", value = "文章作者", required =false,paramType="query"), @ApiImplicitParam(name = "contentSource", value = "文章来源", required =false,paramType="query"), @ApiImplicitParam(name = "contentDatetime", value = "发布时间", required =false,paramType="query"), }) @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) @ResponseBody public ResultData list(@ModelAttribute @ApiIgnore ContentBean content) { BasicUtil.startPage(); content.setSqlWhere(""); List contentList = contentBiz.query(content); return ResultData.build().success(new EUListBean(contentList,(int)BasicUtil.endPage(contentList).getTotal())); } /** * 获取文章列表接口 * @param content 文章 * @return */ @ApiOperation(value = "获取文章列表接口") @ApiImplicitParam(name = "id", value = "编号", required =true,paramType="query") @GetMapping("/get") @ResponseBody public ResultData get(@ModelAttribute @ApiIgnore ContentEntity content){ if(content.getId()==null) { return ResultData.build().error(); } content.setSqlWhere(""); ContentEntity _content = (ContentEntity)contentBiz.getById(content.getId());; return ResultData.build().success(_content); } /** * 查看文章点击数 * @param contentId 文章编号 * @return */ @ApiOperation(value = "查看文章点击数") @ApiImplicitParam(name = "contentId", value = "文章编号", required = true,paramType="path") @GetMapping(value = "/{contentId}/hit") @ResponseBody public String hit(@PathVariable @ApiIgnore String contentId) { if(StringUtils.isEmpty(contentId)){ return "document.write(0)"; } //获取ip String ip = BasicUtil.getIp(); //获取端口(移动/web..) boolean isMobileDevice = BasicUtil.isMobileDevice(); ContentEntity content = contentBiz.getById(contentId); if(content == null){ return "document.write(0)"; } //浏览数+1 if(ObjectUtil.isNotEmpty(content.getContentHit())){ content.setContentHit(content.getContentHit()+1); }else { content.setContentHit(1); } contentBiz.updateById(content); // cms_history 增加相应记录 HistoryLogEntity entity = new HistoryLogEntity(); entity.setHlIsMobile(isMobileDevice); entity.setHlIp(ip); entity.setContentId(content.getId()); entity.setCreateDate(new Date()); historyLogBiz.saveEntity(entity); return "document.write(" + content.getContentHit() + ")"; } }
public class Motor extends Pojazd { public void drift() { System.out.println("Drift!"); } }
package kr.co.hangsho.products.web.form; import org.springframework.web.multipart.MultipartFile; public class ProductForm { private String packagename; private String bigcategory; private String middlecategory; private String smallcategory; private int deliveryfee; private long productdescription; private int discountratio; private MultipartFile imagefile; public String getPackagename() { return packagename; } public void setPackagename(String packagename) { this.packagename = packagename; } public String getBigcategory() { return bigcategory; } public void setBigcategory(String bigcategory) { this.bigcategory = bigcategory; } public String getMiddlecategory() { return middlecategory; } public void setMiddlecategory(String middlecategory) { this.middlecategory = middlecategory; } public String getSmallcategory() { return smallcategory; } public void setSmallcategory(String smallcategory) { this.smallcategory = smallcategory; } public int getDeliveryfee() { return deliveryfee; } public void setDeliveryfee(int deliveryfee) { this.deliveryfee = deliveryfee; } public long getProductdescription() { return productdescription; } public void setProductdescription(long productdescription) { this.productdescription = productdescription; } public int getDiscountratio() { return discountratio; } public void setDiscountratio(int discountratio) { this.discountratio = discountratio; } public MultipartFile getImagefile() { return imagefile; } public void setImagefile(MultipartFile imagefile) { this.imagefile = imagefile; } @Override public String toString() { return "ProductForm [packageName=" + packagename + ", bigcategory=" + bigcategory + ", middlecategory=" + middlecategory + ", smallcategory=" + smallcategory + ", deliveryfee=" + deliveryfee + ", productdescription=" + productdescription + ", discountratio=" + discountratio + ", imagefile=" + imagefile + "]"; } }
package ah.customer.stripe.controller; import static ah.helper.AhConstant.STRIPE_REST_LARGE_LIMIT; import static ah.helper.HelperPrice.buildPriceCollectionResponse; import static ah.helper.HelperPrice.buildPriceResponse; import static ah.helper.HelperPrice.priceCreate; import static ah.helper.HelperPrice.priceGet; import static ah.helper.HelperPrice.priceInactive; import static ah.helper.HelperPrice.priceUpdate; import static ah.helper.HelperPrice.pricesGet; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.stripe.Stripe; import com.stripe.model.Price; import ah.config.StripeConfig; import ah.rest.AhResponse; @RestController @RequestMapping("/api/v1/prices") public class StripeControllerPrice { @Autowired public StripeControllerPrice(StripeConfig config) { Stripe.apiKey = config.stripeSecretKey(); } @GetMapping("/all") public ResponseEntity<AhResponse<Price>> getPrices() { return getPrices(STRIPE_REST_LARGE_LIMIT); } @GetMapping("/") public ResponseEntity<AhResponse<Price>> getPrices(@RequestBody String priceListParamsString) { return buildPriceCollectionResponse(pricesGet(priceListParamsString)); } @GetMapping("/{id}") public ResponseEntity<AhResponse<Price>> getPrice(@PathVariable("id") String priceCid) { return buildPriceResponse(priceGet(priceCid), "Error fetching Price"); } @PostMapping("/") public ResponseEntity<AhResponse<Price>> createPrice(@RequestBody String priceCreateParamsString) { return buildPriceResponse(priceCreate(priceCreateParamsString), "Error creating Price"); } @PutMapping("/{id}") public ResponseEntity<AhResponse<Price>> updatePrice(@PathVariable("id") String priceCid, @RequestBody String priceUpdateParamsString) { return buildPriceResponse(priceUpdate(priceCid, priceUpdateParamsString), "Error updating Price"); } @DeleteMapping("/{id}") public ResponseEntity<AhResponse<Price>> setPriceAsInactive(@PathVariable("id") String priceCid) { return buildPriceResponse(priceInactive(priceCid), "Error making inactive Price"); } }
/* Copyright 2015 Alfio Zappala Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package co.runrightfast.akka; import static co.runrightfast.commons.utils.ValidationUtils.notBlank; import java.util.Arrays; import org.apache.commons.lang3.Validate; /** * * @author alfio */ public interface AkkaUtils { public static final String USER = "/user"; public static final String WILDCARD = "*"; /** * Concatenates the path via path separator : '/' * * * @param basePath base path * @param path appended to base path * @param paths optional additional paths * @return actor path */ static String actorPath(final String basePath, final String path, final String... paths) { notBlank(basePath, "basePath"); notBlank(path, "path"); if (paths != null) { Validate.noNullElements(paths); } final StringBuilder sb = new StringBuilder(128) .append(basePath) .append('/') .append(path); if (paths != null) { Arrays.stream(paths).forEach(p -> sb.append('/').append(p)); } return sb.toString(); } }
package com.sun.tools.xjc.generator.bean.field; import com.sun.tools.xjc.generator.bean.ClassOutlineImpl; import com.sun.tools.xjc.model.CPropertyInfo; /** * {@link SingleField} that forces the primitive accessor type. * * @author Kohsuke Kawaguchi */ public class SinglePrimitiveAccessField extends SingleField { protected SinglePrimitiveAccessField(ClassOutlineImpl context, CPropertyInfo prop) { super(context, prop,true); } }
package com.otemainc.foodfuzz.adapter; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import com.otemainc.foodfuzz.Cart; import com.otemainc.foodfuzz.Drink; import com.otemainc.foodfuzz.Food; import com.otemainc.foodfuzz.Restaurant; public class tabPagerAdapter extends FragmentStatePagerAdapter { String[] tabArray = new String[]{"Food","Drinks","Restaurant","Cart"}; Integer tabno = 4; public tabPagerAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return tabArray[position]; } @Override public Fragment getItem(int position) { switch (position){ case 0: Food food = new Food(); return food; case 1: Drink drink = new Drink(); return drink; case 2: Restaurant restaurant = new Restaurant(); return restaurant; case 3: Cart cart = new Cart(); return cart; } return null; } @Override public int getCount() { return tabno; } }
package sign.com.web.role; import com.github.pagehelper.PageInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import sign.com.biz.role.dto.RoleDto; import sign.com.biz.role.service.RoleService; import sign.com.common.Util.DateUtil; import java.util.Date; import java.util.List; import java.util.UUID; /** * create by luolong on 2018/5/12 */ @RestController public class RoleRest { public Logger logger = LoggerFactory.getLogger(getClass()); @Autowired RoleService roleService; @RequestMapping("/role/save") public String save(@ModelAttribute RoleRegisForm from) { RoleDto roleDto = builderParameter(from); int save = roleService.save(roleDto); if (save == 1) { return "添加成功"; } return "添加失败"; } @RequestMapping("/role/queryById") public Object queryById(@RequestParam String id) { RoleDto roleDto = roleService.selectById(id); return roleDto; } @RequestMapping("/role/queryAll") public Object queryList() { List<RoleDto> roleDtos = roleService.findList(); return roleDtos; } @RequestMapping("/role/queryPage") public Object queryListByPage(@RequestParam int pageSize,@RequestParam int pageNum){ PageInfo<RoleDto> pageList = roleService.findPageList(pageSize, pageNum); return pageList; } private RoleDto builderParameter(RoleRegisForm form) { RoleDto roleDto = new RoleDto(); roleDto.setCreatedBy("system"); roleDto.setCreatedDate(new Date()); roleDto.setDescription(form.getDescription()); String roleCode = DateUtil.strChars(2,true,true)+DateUtil.randomChars(4); int i = 10; while (roleService.queryByRoleCode(roleCode) != null || i <= 0) { roleCode = DateUtil.strChars(2,true,true)+DateUtil.randomChars(4); i--; } if (i <= 0) { return null; } roleDto.setRoleCode(roleCode); roleDto.setRoleName(form.getRoleName()); return roleDto; } }
package com.xp.springboot.entities; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; /** * Entity Class representing Address * * @author Swapnil Ahirrao * */ @Entity @Table(name="Address") public class Address { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int addId; private String addressType; private String lane; private String state; private int pincode; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name="emp_id") @JsonBackReference private Employee emp; public Address() { super(); } public Address(int addId, String addressType, String lane, String state, int pincode, Employee emp) { super(); this.addId = addId; this.addressType = addressType; this.lane = lane; this.state = state; this.pincode = pincode; this.emp = emp; } public int getAddId() { return addId; } public void setAddId(int addId) { this.addId = addId; } public String getAddressType() { return addressType; } public void setAddressType(String addressType) { this.addressType = addressType; } public String getLane() { return lane; } public void setLane(String lane) { this.lane = lane; } public String getState() { return state; } public void setState(String state) { this.state = state; } public int getPincode() { return pincode; } public void setPincode(int pincode) { this.pincode = pincode; } public Employee getEmp() { return emp; } public void setEmp(Employee emp) { this.emp = emp; } @Override public String toString() { return "Address [addId=" + addId + ", addressType=" + addressType + ", lane=" + lane + ", state=" + state + ", pincode=" + pincode + ", emp=" + emp + "]"; } }
package database; /** * Supplier Data Access class * * @author Quynh Nguyen (Queenie) * Created: 04/15/2019 */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import model.Supplier; public class DBSupplier { private static final Logger LOGGER = Logger.getLogger(DBSupplier.class.getName()); public DBSupplier() { // TODO Auto-generated constructor stub } /* * get all Suppliers */ public static List<Supplier> getSuppliers() { List<Supplier> suppliers = new ArrayList<Supplier>(); String sql = "SELECT * FROM Suppliers"; try { Connection conn = DBConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); // loop through the result set while (rs.next()) { Supplier ele = new Supplier(); ele.setSupplierId(rs.getInt("SupplierId")); ele.setSupName(rs.getString("SupName")); suppliers.add(ele); } } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBSupplier.getSuppliers: " + e.getMessage()); } finally { DBConnection.closeConnection(); } return suppliers; } /* * get Product by productId */ public static Supplier getSupplier(int supplierId) { Supplier ele = new Supplier(); String sql = "SELECT * FROM Suppliers WHERE SupplierId=?"; try { Connection conn = DBConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setInt(1, supplierId); ResultSet rs = stmt.executeQuery(); // loop through the result set if (rs.next()) { ele.setSupplierId(rs.getInt("SupplierId")); ele.setSupName(rs.getString("SupName")); } } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBSupplier.getSupplier: " + e.getMessage()); } finally { DBConnection.closeConnection(); } return ele; } /* * update Product */ public static boolean updateSupplier(Supplier supplier) { boolean result = true; String sql = "UPDATE Suppliers SET SupName = ? WHERE SupplierId = ?"; try { Connection conn = DBConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, supplier.getSupName()); stmt.setInt(2, supplier.getSupplierId()); result = stmt.executeUpdate() == 1; } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBSupplier.updateSupplier: " + e.getMessage()); } finally { DBConnection.closeConnection(); } return result; } /* * delete Supplier by supplierId */ public static boolean deleteSupplier(int supplierId) { boolean result = true; Connection conn = DBConnection.getConnection(); String sql = "DELETE FROM Suppliers WHERE SupplierId = ?"; PreparedStatement stmt = null; try { conn.setAutoCommit(false); stmt = conn.prepareStatement(sql); stmt.setInt(1, supplierId); result = stmt.execute(); conn.commit(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBSupplier.deleteSupplier: " + e.getMessage()); try { conn.rollback(); } catch (SQLException e1) { LOGGER.log(Level.SEVERE, "DBSupplier.deleteSupplier: " + e.getMessage()); } } finally { try { conn.setAutoCommit(true); stmt.close(); } catch (SQLException e) { LOGGER.log(Level.SEVERE, "DBSupplier.deleteSupplier: " + e.getMessage()); } DBConnection.closeConnection(); } return result; } }
package kui.feign_client.service; import java.util.List; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import kui.feign_client.entity.User; @FeignClient("service-user") @Service public interface UserService { @RequestMapping("user/checkUserId/{u_id}") public boolean checkUserId(@PathVariable("u_id") String u_id); @RequestMapping(value="user/registerUser",method=RequestMethod.POST) public boolean registerUser( @RequestParam("u_id") String u_id, @RequestParam("name") String name, @RequestParam("password") String password, @RequestParam("interest_label") List<String> interestLabelList); @RequestMapping(value="user/loginUser",method=RequestMethod.POST) public boolean loginUser( @RequestParam("u_id") String u_id, @RequestParam("password") String password); @RequestMapping(value="user/getCurrentUser",method=RequestMethod.POST) public User getCurrentUser(); @RequestMapping("user/findUserByU_idList") public List<User> findUserByU_idList(@RequestBody List<String> u_idList); @RequestMapping("user/findUserByUserId") public User findUserByUserId(@RequestParam("userId") int userId); @RequestMapping("user/findAllUser") public List<User> findAllUser(); }
package com.nfschina.aiot.fragment; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; import com.nfschina.aiot.activity.Home; import com.nfschina.aiot.activity.R; import com.nfschina.aiot.animation.ExpandAnimation; import com.nfschina.aiot.entity.GreenHouse; import com.nfschina.aiot.entity.WarningInfo; import com.nfschina.aiot.util.DBConnectionUtil; /** * 报警信息的fragment * @author wujian */ public class InfoFragment extends Fragment implements OnClickListener { @ViewInject(R.id.core_info_lv) private PullToRefreshListView core_info_lv; @ViewInject(R.id.info_back) private ImageButton info_back; @ViewInject(R.id.info_gohome) private ImageButton info_gohome; private TextView pop_ignore_tv, pop_handler_tv; private MyInfoListAdapter infoListAdapter; private GreenHouse greenHouse;//当前温室实体 private List<WarningInfo> warningInfos = new ArrayList<WarningInfo>();//保存报警信息 private PopupWindow popupWindow;//长按弹出的对话框 private LayoutInflater inflater = null; MyHolder holder; private int page,size = 10; private boolean isHavaInfo = false; //private InfoListener infoListener; private DBConnectionUtil connectionUtil ; //将时间字符串先转化为format_ori格式的Date,然后再格式化为format的字符串 SimpleDateFormat format_ori = new SimpleDateFormat("yyyyMMddhhmmss"); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.core_info, null); ViewUtils.inject(this, view); // 以下为了获取当前在哪个温室 Intent intent = getActivity().getIntent(); Bundle bundle = intent.getExtras(); if (bundle != null) { greenHouse = (GreenHouse) bundle.get("greenhouse"); } info_back.setOnClickListener(this); info_gohome.setOnClickListener(this); core_info_lv.setMode(Mode.BOTH); //core_info_lv.setOnItemClickListener(this);//可以直接将listview条目的点击事件直接用在适配器中的convertView core_info_lv.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { loadDatas(core_info_lv.getScrollY()<0); } }); // 首次来到页面是需要自动加载数据 new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { core_info_lv.setRefreshing();// 刷新加载数据 return true; } }).sendEmptyMessageDelayed(0, 1000); return view; } /** * 实现下拉刷新、下拉加载更多的方法 * @param isRefresh */ protected void loadDatas(boolean isRefresh) { if (isRefresh) { page = 0;//下拉刷新,如果是刷新,就把页面设为第一个 warningInfos.clear(); new GetAlarmInfoByIdTask(page,size).execute(); getActivity().runOnUiThread(new Runnable() { @Override public void run() { core_info_lv.setMode(Mode.BOTH); } }); }else { page++;//上拉加载更多,加载下一个页面 new GetAlarmInfoByIdTask(page,size).execute(); core_info_lv.setAdapter(infoListAdapter); //infoListAdapter.notifyDataSetChanged(); } } /** * 根据当前温室id获取报警信息 * @author wujian */ private class GetAlarmInfoByIdTask extends AsyncTask<Void, Void, List<WarningInfo>>{ private int page; private int size; public GetAlarmInfoByIdTask(int page,int size){ this.page = page; this.size = size; } @Override protected List<WarningInfo> doInBackground(Void... params) { try { int count = 0; //根据温室ID以及报警信息状态 String sql = "select * from warningtb where warningstate = 0 and greenhouseid = '"+greenHouse.getId()+"' limit "+page*size+" , "+size+""; connectionUtil = new DBConnectionUtil(sql); ResultSet resultSet = connectionUtil.pst.executeQuery(); if (resultSet != null) { warningInfos = new ArrayList<WarningInfo>(); isHavaInfo = true; while (resultSet.next()) { WarningInfo warningInfo = new WarningInfo(resultSet.getInt("Warningid"), resultSet.getString("greenhouseid"), resultSet.getFloat("temperature"), resultSet.getInt("co2"), resultSet.getFloat("humidity"), resultSet.getInt("illuminance"), resultSet.getString("warningtime"), resultSet.getInt("warningstate")); warningInfos.add(warningInfo); count++; } } if (count < size || count == 0) { //如果这次加载的数据量小于size,或者没有加载到数据 getActivity().runOnUiThread(new Runnable() { @Override public void run() { core_info_lv.setMode(Mode.PULL_FROM_START); Toast.makeText(getActivity(), "已加载全部", Toast.LENGTH_LONG).show(); } }); } } catch (SQLException e) { e.printStackTrace(); }finally{ connectionUtil.close(); } return warningInfos; } @Override protected void onPostExecute(List<WarningInfo> result) { super.onPostExecute(result); if (result != null && result.size() > 0) { //数据适配 infoListAdapter = new MyInfoListAdapter(); core_info_lv.setAdapter(infoListAdapter); //停止刷新 core_info_lv.onRefreshComplete(); //就是给activity发送消息。 //infoListener.alarmShow(isHavaInfo); } else { //当没有数据时显示的界面 View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.nodata_view, null); emptyView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); ((ViewGroup)core_info_lv.getParent()).addView(emptyView); core_info_lv.setEmptyView(emptyView); core_info_lv.onRefreshComplete();//停止刷新 } } } /** * 适配报警信息的适配器 * @author wujian */ public class MyInfoListAdapter extends BaseAdapter { @Override public int getCount() { return warningInfos.size(); } @Override public Object getItem(int position) { return warningInfos.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { //if (convertView == null) { holder = new MyHolder(); convertView = LayoutInflater.from(parent.getContext()).inflate( R.layout.alarminfo_item, null); ViewUtils.inject(holder, convertView); // convertView.setTag(holder); // } else { // holder = (MyHolder) convertView.getTag(); //} holder.alarminfo_greenhouse_name.setText(greenHouse.getName()); //用于生成报警信息内容 String infoContent = ""; int infoCount = 1; if (warningInfos.get(position).getCo2() < 0) { infoContent += (infoCount++)+"、CO2低于最小阀值"+(-warningInfos.get(position).getCo2())+"ppm;\n"; }else if (warningInfos.get(position).getCo2() > 0) { infoContent +=(infoCount++)+"、CO2高于最大阀值"+warningInfos.get(position).getCo2()+"ppm;\n"; } if (warningInfos.get(position).getTemperature() < 0) { infoContent +=(infoCount++)+"、温度低于最小阀值"+(-warningInfos.get(position).getTemperature())+"℃;\n"; }else if (warningInfos.get(position).getTemperature() > 0) { infoContent +=(infoCount++)+"、温度高于最大阀值"+warningInfos.get(position).getTemperature()+"℃;\n"; } if (warningInfos.get(position).getHumidity() < 0 ) { infoContent +=(infoCount++)+"、湿度低于最小阀值"+(-warningInfos.get(position).getHumidity())+"%;\n"; }else if(warningInfos.get(position).getHumidity() > 0 ){ infoContent +=(infoCount++)+"、湿度高于最大阀值"+warningInfos.get(position).getHumidity()+"%;\n"; } if (warningInfos.get(position).getIlluminance() < 0) { infoContent +=(infoCount++)+"、光照低于最小阀值"+(-warningInfos.get(position).getIlluminance())+"xl;\n"; }else if (warningInfos.get(position).getIlluminance() > 0) { infoContent +=(infoCount++)+"、光照高于最大阀值"+warningInfos.get(position).getIlluminance()+"xl;\n"; } holder.alarminfo_item_content.setText(infoContent); try {//生成格式化的时间 date = format_ori.parse(warningInfos.get(position).getWarningtime()); String formatTime = format.format(date); holder.alarminfo_item_time.setText(formatTime); } catch (ParseException e) { e.printStackTrace(); } //报警信息级别的生成 String infoLevel = getWarningLevel(); switch (infoLevel) { case "需要注意": holder.alarminfo_item_level.setBackgroundColor(getResources().getColor(R.color.green_light)); holder.alarminfo_item_level.setText(infoLevel); break; case "立即处理": holder.alarminfo_item_level.setBackgroundColor(getResources().getColor(R.color.orange)); holder.alarminfo_item_level.setText(infoLevel); break; case "可以忽略": holder.alarminfo_item_level.setBackgroundColor(getResources().getColor(R.color.gray)); holder.alarminfo_item_level.setText(infoLevel); break; } //为了点击事件 View alarminfo_item_ll = (LinearLayout) convertView.findViewById(R.id.alarminfo_item_ll); alarminfo_item_ll.measure(0, 0); ((LinearLayout.LayoutParams)alarminfo_item_ll.getLayoutParams()).bottomMargin = (-1)*alarminfo_item_ll.getMeasuredHeight(); alarminfo_item_ll.setVisibility(View.GONE); //直接将点击事件注册在convertView convertView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { upAndDownAnimation(v,position); } }); //暂时去掉下面功能 //直接将点击事件注册在convertView(在PullToRefreshListView没有onItemLongClick这个方法的时候) // convertView.setOnLongClickListener(new OnLongClickListener() { // @Override // public boolean onLongClick(View v) { // inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); // initPopupWindow(inflater); // showPop(v); // pop_ignore_tv.setOnClickListener(new TextViewOnClick(position)); // pop_handler_tv.setOnClickListener(new TextViewOnClick(position)); // return true;//返回true让OnClickListener不再执行 // } // }); return convertView; } } /** * 暂时忽略 和 立即处理的点击事件 * @author My */ private class TextViewOnClick implements OnClickListener{ private int position; public TextViewOnClick(int position){ this.position = position; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.pop_ignore_tv://暂时忽略 //执行忽略操作 new IgnoreWarningTask(position).execute(); //关掉 if (popupWindow != null) { popupWindow.dismiss(); } Toast.makeText(getActivity(), "已经忽略当前报警信息", 1).show(); //这个时候数据库中的数据已经发生改变,需要直接显示给用户,刷新 core_info_lv.setRefreshing(); break; case R.id.pop_handler_tv://立刻处理 break; } } } /** * 忽略报警信息或者将报警信息置为已处理 * @author wujian */ public class IgnoreWarningTask extends AsyncTask<Integer, Void, Void>{ private int position; public IgnoreWarningTask(int position){ this.position = position; } @Override protected Void doInBackground(Integer... params) { try { //更新值 String sql = "update warningtb set warningstate = 1 where warningid = '"+warningInfos.get(position).getId()+"'"; connectionUtil = new DBConnectionUtil(sql); connectionUtil.pst.execute(); } catch (SQLException e) { e.printStackTrace(); }finally{ connectionUtil.close(); } return null; } } /** * 初始化Popupwindow * @param inflater */ private void initPopupWindow(LayoutInflater inflater) { View view = inflater.inflate(R.layout.pop_item_layout, null); popupWindow = new PopupWindow(view, 350, 100); pop_ignore_tv = (TextView) view.findViewById(R.id.pop_ignore_tv); pop_handler_tv = (TextView) view.findViewById(R.id.pop_handler_tv); } /** * Popupwindow显示 * @param v */ @SuppressWarnings("deprecation") private void showPop(View v) { popupWindow.setFocusable(false); popupWindow.setOutsideTouchable(true); popupWindow.setBackgroundDrawable(new BitmapDrawable());// 设置此项可点击Popupwindow外区域消失,注释则不消失 // 设置出现位置 int[] location = new int[2]; v.getLocationOnScreen(location); popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0] + v.getWidth() / 2 - popupWindow.getWidth() / 2, location[1] - popupWindow.getHeight()); } /** * 为了缓控件 * @author wujian */ private final class MyHolder { @ViewInject(R.id.alarminfo_greenhouse_name) private TextView alarminfo_greenhouse_name; @ViewInject(R.id.alarminfo_item_content) private TextView alarminfo_item_content; @ViewInject(R.id.alarminfo_item_time) private TextView alarminfo_item_time; @ViewInject(R.id.alarminfo_item_level) private TextView alarminfo_item_level; } /** * 实现上下箭头转换的动画 * @param v */ public void upAndDownAnimation(View v,int position){ //为了确保第一次查看报警信息将报警信息状态改变 TextView isFirstClick_other = (TextView) v.findViewById(R.id.isFirstClick_other); System.out.println(isFirstClick_other.getText()); if (isFirstClick_other.getText().equals("true")) { new IgnoreWarningTask(position).execute(); isFirstClick_other.setText("false"); } //为了条目中的箭头旋转的效果 TextView isFirstClick = (TextView) v.findViewById(R.id.isFirstClick); //用来判断是否是第一次点击条目 boolean firstClick_tv = isFirstClick.getText().toString().equals("true"); ImageView alarminfo_item_upordown_iv = (ImageView) v.findViewById(R.id.alarminfo_item_upordown_iv); if (firstClick_tv) { //判断是不是第一次点击listview item //为图标审定一个动画 Animation animation = AnimationUtils.loadAnimation(v.getContext(), R.anim.alarminfo_updown_iv); alarminfo_item_upordown_iv.startAnimation(animation); animation.setFillAfter(true);//保持旋转后的样子 isFirstClick.setText("false");//表示第一次已经点击完毕 } else if (!firstClick_tv) { Animation animation = AnimationUtils.loadAnimation(v.getContext(), R.anim.alarminfo_downup_iv); alarminfo_item_upordown_iv.startAnimation(animation); animation.setFillAfter(true); isFirstClick.setText("true"); } //下面是点击条目展开的动画效果 LinearLayout alarminfo_item_ll = (LinearLayout) v.findViewById(R.id.alarminfo_item_ll); ExpandAnimation expandAni = new ExpandAnimation(alarminfo_item_ll, 500); alarminfo_item_ll.startAnimation(expandAni); } /** * 随机获取报警信息级别 * @return */ public String getWarningLevel(){ String level = ""; int random = (int)(3 * Math.random())+1; switch (random) { case 1: level = "需要注意"; break; case 2: level = "立即处理"; break; case 3: level = "可以忽略"; break; } return level; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.info_back: getActivity().finish(); break; case R.id.info_gohome: Intent intent = new Intent(getActivity(), Home.class); startActivity(intent); getActivity().finish(); break; } } // /** // * 和activity进行通信的接口 // * @author wujian' // */ // public interface InfoListener{ // public void alarmShow(boolean isHavaInfo); // } // @Override // public void onAttach(Activity activity) { // super.onAttach(activity); // infoListener = (InfoListener) activity; // } }
package io.github.stormdb; import java.io.BufferedReader; import java.io.IOException; public final class StreamingDiffUtils { public static <T extends Comparable<T>> void diff(InputStream<T> original, InputStream<T> revised, OutputStream<Delta<T>> patch) throws StreamException { int position = 0; T line1 = original.read(); position++; T line2 = revised.read(); while (line1 != null && line2 != null) { int result = line1.compareTo(line2); if (result == 0) { line1 = original.read(); position++; line2 = revised.read(); } else if (result < 0) { patch.write(new Delta<T>(position, DeltaType.DELETE, line1)); line1 = original.read(); position++; } else { patch.write(new Delta<T>(position, DeltaType.INSERT, line2)); line2 = revised.read(); } } while (line1 != null) { patch.write(new Delta<T>(position, DeltaType.DELETE, line1)); line1 = original.read(); position++; } while (line2 != null) { patch.write(new Delta<T>(position, DeltaType.INSERT, line2)); line2 = revised.read(); } } private StreamingDiffUtils() { } }
package com.sour.mq.service; import com.sour.mq.bean.Book; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; import java.util.Date; /** * @author xgl * @date 2020/8/9 18:34 **/ @Service public class BookService { /** * 监听内容 * @RabbitListener 监听rabbitmq的内容 * * @author xgl * @date 2020/8/9 18:39 **/ @RabbitListener(queues = "sout.new") public void receive(Book book) { System.out.println(new Date().toString() + " - sout.new收到消息 :"); System.out.println(book); } @RabbitListener(queues = "sour") public void receive02(Message e) { System.out.println(new Date().toString() + " - sour收到消息 :"); System.out.println( e.getBody() ); System.out.println(e.getMessageProperties()); } }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.webui.common; import java.util.ArrayList; import java.util.Collection; import java.util.List; import com.google.common.html.HtmlEscapers; import com.vaadin.data.Property.ValueChangeEvent; import com.vaadin.data.Property.ValueChangeListener; import com.vaadin.data.Property.ValueChangeNotifier; import com.vaadin.event.Action; import com.vaadin.shared.ui.Orientation; import com.vaadin.ui.AbstractOrderedLayout; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.CustomComponent; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Table; import com.vaadin.ui.Tree; import com.vaadin.ui.VerticalLayout; /** * Component with a list of small buttons. Buttons are bound to {@link Action}s via * {@link SingleActionHandler}. The wrapped Action must have at least caption or image set. * * Additionally toolbar's buttons have their state enabled or disabled depending whether the toolbar's target is set * or not. * * @author K. Benedyczak */ public class Toolbar extends CustomComponent { private Orientation orientation; private ValueChangeNotifier source; private Object target; private List<Button> buttons; private AbstractOrderedLayout main; public Toolbar(ValueChangeNotifier source, Orientation orientation) { this.source = source; this.orientation = orientation; this.main = orientation == Orientation.HORIZONTAL ? new HorizontalLayout() : new VerticalLayout(); source.addValueChangeListener(getValueChangeListener()); buttons = new ArrayList<>(); main.setSpacing(true); main.addStyleName(Styles.tinySpacing.toString()); setCompositionRoot(main); setSizeUndefined(); } public Orientation getOrientation() { return orientation; } /** * @return a listener that can be registered on a selectable component as {@link Tree} or {@link Table} * to update the toolbar's target. */ public ValueChangeListener getValueChangeListener() { return new ValueChangeListener() { @Override public void valueChange(ValueChangeEvent event) { target = event.getProperty().getValue(); for (Button button: buttons) { updateButtonState(button); } } }; } private void updateButtonState(Button button) { Object buttonData = button.getData(); if (buttonData == null || !(buttonData instanceof SingleActionHandler)) return; SingleActionHandler handler = (SingleActionHandler) button.getData(); if (handler.isNeeded()) { button.setVisible(true); if (handler.isNeedsTarget() && target == null) { button.setEnabled(false); if (handler.isHideIfNotNeeded()) button.setVisible(false); } else { boolean en = handler.getActions(target, source).length == 1; button.setEnabled(en); if (handler.isHideIfNotNeeded()) button.setVisible(en); } } else { button.setVisible(false); } } public void addActionHandlers(Collection<SingleActionHandler> handlers) { for (SingleActionHandler handler: handlers) addActionHandler(handler); } public void addActionHandlers(SingleActionHandler... handlers) { for (SingleActionHandler handler: handlers) addActionHandler(handler); } public void addButtons(Button... buttons) { for (Button button: buttons) addButton(button); } public void addSeparator() { Label sep = new Label(); String style = orientation == Orientation.HORIZONTAL ? Styles.verticalLine.toString() : Styles.horizontalLine.toString(); sep.addStyleName(style); main.addComponent(sep); main.setComponentAlignment(sep, Alignment.MIDDLE_CENTER); } /** * Adds a custom button. It is styled in the same way as other in the toolbar, but its actions must * be configured manually. */ public void addButton(Button button) { button.addStyleName(Styles.vButtonLink.toString()); button.addStyleName(Styles.toolbarButton.toString()); buttons.add(button); main.addComponent(button); } public void addActionHandler(SingleActionHandler handler) { Action action = handler.getActionUnconditionally(); final Button button = new Button(); button.setData(handler); if (action.getIcon() != null) button.setIcon(action.getIcon()); else button.setCaption(action.getCaption()); if (action.getCaption() != null) button.setDescription(HtmlEscapers.htmlEscaper().escape(action.getCaption())); button.addStyleName(Styles.vButtonLink.toString()); button.addStyleName(Styles.toolbarButton.toString()); button.addClickListener(new Button.ClickListener() { @Override public void buttonClick(ClickEvent event) { SingleActionHandler handler = (SingleActionHandler) button.getData(); if (handler.isNeedsTarget() && target == null) return; handler.handleAction(handler.getActionUnconditionally(), source, target); } }); buttons.add(button); main.addComponent(button); updateButtonState(button); } }
package com.example.user.airport2; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.estimote.coresdk.common.requirements.SystemRequirementsChecker; import com.estimote.coresdk.observation.region.beacon.BeaconRegion; import com.estimote.coresdk.recognition.packets.Beacon; import com.estimote.coresdk.service.BeaconManager; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.UUID; public class MainActivity extends AppCompatActivity { private BeaconManager beaconManager; Switch sw1; TextView txtWaktu; Calendar waktu; ArrayList<Absen> logAbsent = new ArrayList<>(); String abc = ""; static BeaconRegion region1 = new BeaconRegion("region1", UUID.fromString("b9407f30-f5f8-466e-aff9-25556b57fe6d"), 39255, 27376); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtWaktu = (TextView) findViewById(R.id.textView1); sw1 = (Switch) findViewById(R.id.switch1); beaconManager = new BeaconManager(getApplicationContext()); sw1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { startMonitoring(); } else { // beaconManager.stopMonitoring(); beaconManager.disconnect(); Toast.makeText(MainActivity.this, "off service", Toast.LENGTH_SHORT).show(); } } }); notificationManager(); } @Override protected void onResume() { super.onResume(); SystemRequirementsChecker.checkWithDefaultDialogs(this); } public void notificationManager() { beaconManager.setMonitoringListener(new BeaconManager.BeaconMonitoringListener() { @Override public void onEnteredRegion(BeaconRegion beaconRegion, List<Beacon> beacons) { String region = beaconRegion.getIdentifier(); showNotification( "Your " + region + " closes in 47 minutes.", "Current security wait time is 15 minutes, " + "and it's a 5 minute walk from security to the gate. " + "Looks like you've got plenty of time!"); Absen masuk = new Absen(); waktu = Calendar.getInstance(); masuk.setWaktu(formatCalendar(waktu)); masuk.setTag("masuk"); logAbsent.add(masuk); txtWaktu.setText(abc + logAbsent.toString()); } @Override public void onExitedRegion(BeaconRegion beaconRegion) { String region = beaconRegion.getIdentifier(); showNotification( "Airport " + region, "you exit airport"); Absen keluar = new Absen(); waktu = Calendar.getInstance(); waktu.add(Calendar.HOUR, +1); keluar.setWaktu(formatCalendar(waktu)); keluar.setTag("keluar"); logAbsent.add(keluar); txtWaktu.setText(abc + logAbsent.toString()); } }); } public void startMonitoring() { beaconManager.connect(new BeaconManager.ServiceReadyCallback() { @Override public void onServiceReady() { long scanPeriod = 5*1000; long waitTime = 10*1000; beaconManager.setBackgroundScanPeriod(scanPeriod,waitTime); beaconManager.startMonitoring(region1); } }); } public void stopMonitoring() { beaconManager.connect(new BeaconManager.ServiceReadyCallback(){ @Override public void onServiceReady() { beaconManager.stopMonitoring(region1.getIdentifier()); } }); } public void showNotification(String title, String message) { Intent notifiIntent = new Intent(this, MainActivity.class); notifiIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pendingIntent = PendingIntent.getActivities(this, 0, new Intent[]{notifiIntent}, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new NotificationCompat.Builder(this) .setSmallIcon(android.R.drawable.ic_dialog_info) .setContentTitle(title) .setAutoCancel(true) .setContentIntent(pendingIntent) .setStyle(new NotificationCompat.BigTextStyle().bigText(message)) .build(); notification.defaults |= Notification.DEFAULT_SOUND; NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, notification); } public String formatCalendar(Calendar time) { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss'T'dd-MM-yyyy"); String output = sdf.format(time.getTime()); return output; } }
package cn.novelweb.video.edit; import java.util.HashMap; import java.util.Map; /** * <p>添加视频水印时设置水印位置</p> * <p>2020-02-26 00:19</p> * * @author Dai Yuanchuan **/ public enum WatermarkLocation { /** * 左上角 */ leftUp, /** * 右上角 */ rightUp, /** * 左下角 */ leftLower, /** * 右下角 */ rightLower, /** * 中间 */ middle; public static Map<WatermarkLocation, String> map = new HashMap<>(5); static { map.put(WatermarkLocation.leftUp, "overlay=10:10"); map.put(WatermarkLocation.rightUp, "overlay=main_w-overlay_w-10:10"); map.put(WatermarkLocation.leftLower, "overlay=10:main_h-overlay_h-10"); map.put(WatermarkLocation.rightLower, "overlay=main_w-overlay_w-10:main_h-overlay_h-10"); map.put(WatermarkLocation.middle, "overlay=main_w/2-overlay_w/2:main_h/2-overlay_h/2"); } }
package com.greenfox.exam.repository; import com.greenfox.exam.model.Car; import org.springframework.data.repository.CrudRepository; import java.util.List; public interface CarRepo extends CrudRepository<Car, Long> { List<Car> findAllByPlateIsLike(String plate); List<Car> findAllByCarBrandIsLike(String carBrand); }
package com.stk123.model.dto; import com.stk123.model.bo.Stk; public class StkChange { private Stk stk; private int period; private double closeChange; public Stk getStk() { return stk; } public void setStk(Stk stk) { this.stk = stk; } public double getCloseChange() { return closeChange; } public void setCloseChange(double closeChange) { this.closeChange = closeChange; } public int getPeriod() { return period; } public void setPeriod(int period) { this.period = period; } public String toString(){ return "period:"+period+",stk:"+stk.getCode()+",closeChange:"+closeChange; } }
package course.chapter15; import java.io.*; public class ReadWriteBinary { static byte[] bytes; public static void main(String[] args) { String filename = "/home/bogdan/Pictures/ranked.png"; String filename2 = "/home/bogdan/Pictures/ranked2.png"; readFileIntoArray(filename); writeArrayToFile(filename2); } static void readFileIntoArray(String fn) { FileInputStream fis = null; File f = new File(fn); long length = f.length(); System.out.println(length); try { fis = new FileInputStream(f); bytes = new byte[(int) length]; fis.read(bytes); System.out.println(bytes); } catch (IOException e) { System.err.println(e); } finally { try { fis.close(); } catch (IOException e) { System.err.println(e); } } } static void writeArrayToFile(String fn) { FileOutputStream fos = null; File f = new File(fn); try { fos = new FileOutputStream(f); fos.write(bytes); System.out.println(bytes); } catch (IOException e) { System.err.println(e); } finally { try { fos.close(); } catch (IOException e) { System.err.println(e); } } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package q07_array; import java.util.Random; import java.util.Scanner; /** * * @author shivani tangellapally */ public class Array { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int arr[] = new int[100]; for(int i =0; i<arr.length; i++){ Random r = new Random(); arr[i] = r.nextInt(1000); } System.out.println("Please enter index of the array that you want to display"); Scanner input = new Scanner(System.in); System.out.println(arr.length); int value = input.nextInt(); try{ System.out.println(arr[value]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Index Out of bound "+e.getMessage()); } } }
package System; import java.awt.*; import java.awt.event.*; import javax.swing.*; import Sul.*; public class Start_Panel extends JPanel { Main m; JLabel start = new JLabel("Start"); JLabel quit = new JLabel("Quit"); ImageIcon background = new ImageIcon("src/Image/Start.png"); Image back=background.getImage(); MouseAdapter sstart; MouseAdapter qquit; public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(back, 0, 0, getWidth(), getHeight(), this); } Start_Panel(Deck d, Main m){ this.m=m; setLayout(null); Color c1=new Color(255, 255, 255, 0); start.setLocation(70, 250); start.setSize(300, 100); start.setFont(new Font("DX시인과나",Font.BOLD,80)); start.setBackground(c1); start.setHorizontalAlignment(SwingConstants.CENTER); add(start); quit.setLocation(70, 400); quit.setSize(300, 100); quit.setFont(new Font("DX시인과나",Font.BOLD,80)); quit.setBackground(c1); quit.setHorizontalAlignment(SwingConstants.CENTER); add(quit); sstart=new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { //Color c2=new Color(0, 0, 0, 100); //start.setBackground(c1); //repaint(); m.change("Menu"); } }; qquit=new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println("Server Stop"); System.exit(0); } }; start.addMouseListener(sstart); quit.addMouseListener(qquit); } }
/* * © Copyright 2016 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied * verbatim in the file “COPYING“. In applying this licence, CERN does not waive the privileges and immunities granted * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction. */ package cern.molr.inspector.gui; import cern.molr.commons.registry.ObservableRegistry; import cern.molr.inspector.domain.Session; import cern.molr.inspector.domain.impl.SessionRegistry; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import java.util.Collection; import java.util.stream.Collectors; /** * Implementation {@link BorderPane} that allows the user to view and manipulate all the currently active * {@link Session}s * * @author tiagomr */ public class SessionsListPane extends BorderPane implements ObservableRegistry.OnCollectionChangedListener<Session> { //TODO tests have to be done private final ListView<Session> listView = new ListView<>(); private final ObservableList<Session> sessions = FXCollections.observableArrayList(); private final ObservableRegistry<Session> sessionsRegistry; private final Button terminateButton = new Button("Terminate"); private final Button terminateAllButton = new Button("Terminate all"); public SessionsListPane(SessionRegistry sessionsRegistry) { super(); this.sessionsRegistry = sessionsRegistry; initUI(); initData(); } private void initUI() { HBox hBox = new HBox(); hBox.setAlignment(Pos.CENTER_LEFT); terminateButton.setOnMouseClicked(event -> { terminateSession(listView.getSelectionModel().getSelectedItem()); terminateButton.setDisable(true); }); terminateButton.setDisable(true); hBox.getChildren().add(terminateButton); terminateAllButton.setOnMouseClicked(event -> terminateAllSessions()); terminateAllButton.setDisable(true); hBox.getChildren().add(terminateAllButton); hBox.setSpacing(10); hBox.setPadding(new Insets(15, 12, 15, 12)); setCenter(listView); setBottom(hBox); setPrefSize(500, 900); listView.setItems(sessions); listView.setCellFactory(param -> new SessionCell()); listView.setOnMouseClicked(event -> { if (listView.getSelectionModel().getSelectedItem() != null) { terminateButton.setDisable(false); } else { terminateButton.setDisable(true); } }); } private void initData() { sessions.addAll(sessionsRegistry.getEntries()); sessionsRegistry.addListener(this); if (!sessions.isEmpty()) { terminateAllButton.setDisable(false); } } @Override public void onCollectionChanged(Collection<Session> collection) { Platform.runLater(() -> { sessions.clear(); sessions.addAll(collection); if (sessions.isEmpty()) { terminateAllButton.setDisable(true); terminateButton.setDisable(true); } else { terminateAllButton.setDisable(false); } }); } static class SessionCell extends ListCell<Session> { @Override public void updateItem(Session session, boolean empty) { super.updateItem(session, empty); if (empty) { setGraphic(null); } else { Label label = new Label(session.getMission().getMissionContentClassName()); setGraphic(label); } } } private void terminateAllSessions() { sessions.stream() .collect(Collectors.toList()) .forEach(this::terminateSession); } private void terminateSession(Session session) { session.getController().terminate(); } }
package ru.sbt.test.refactoring; //import java.util.HashMap; //import java.util.Map; public class Tractor { private Position position = new Position(0,0); private Orientation orientation = Orientation.NORTH; // private final Map<Orientation, Orientation> map = new HashMap<>(); // // public Tractor() { // map.put(Orientation.NORTH, Orientation.EAST); // map.put(Orientation.EAST, Orientation.SOUTH); // map.put(Orientation.SOUTH, Orientation.WEST); // map.put(Orientation.WEST, Orientation.NORTH); // } public void move(String command) { if (command == "F") { moveForwards(); } else if (command == "T") { turnClockwise(); } } public void moveForwards() { switch (orientation) { case NORTH: position.incPosY(); break; case EAST: position.incPosX(); break; case SOUTH: position.decPosY(); break; case WEST: position.decPosX(); break; } if (position.isNotValid()) { throw new TractorInDitchException(); } } public void turnClockwise() { switch (orientation) { case NORTH: orientation = Orientation.EAST; break; case EAST: orientation = Orientation.SOUTH; break; case SOUTH: orientation = Orientation.WEST; break; case WEST: orientation = Orientation.NORTH; break; } // orientation = map.get(orientation); } public int getPositionX() { return position.getX(); } public int getPositionY() { return position.getY(); } public Orientation getOrientation() { return orientation; } }
package com.example.startup.FragmentStudent; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.example.startup.Backend.CustomRecyclerAssingment; import com.example.startup.Backend.StudentAssingmentSet; import com.example.startup.Constants.NavigationDrawerConstants; import com.example.startup.R; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Objects; import static android.content.Context.MODE_PRIVATE; public class Assingments extends Fragment { private String JsonURL = "https://edfinix.herokuapp.com/api/assignments/"; SharedPreferences sp; RecyclerView recyclerView; RecyclerView.Adapter mAdapter; RecyclerView.LayoutManager layoutManager; List<StudentAssingmentSet> testList; private ArrayList<String> arr = new ArrayList<String>(); private ArrayList<String> arr1 = new ArrayList<String>(); private ArrayList<String> arr2 = new ArrayList<String>(); RequestQueue rq; String date = ""; String time = ""; String sub = ""; Handler handler; TextView t; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getActivity().setTitle(NavigationDrawerConstants.TAG_Assignment); } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.activity_assingments, null); rq = Volley.newRequestQueue(getActivity()); sp = Objects.requireNonNull(this.getActivity()).getSharedPreferences("login", MODE_PRIVATE); String classn = sp.getString("sClass", ""); String section = sp.getString("sSection", ""); String link_student = JsonURL + classn + "/" + section; Log.d("link", link_student); recyclerView = root.findViewById(R.id.recycleViewContainer); recyclerView.setHasFixedSize(true); layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); testList = new ArrayList<>(); sendRequest(link_student); handler = new Handler(getActivity().getMainLooper()); return root; } public void sendRequest(final String link_student) { JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.GET, link_student,null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { StudentAssingmentSet personUtils = new StudentAssingmentSet(); try { JSONArray studentinfo= response.getJSONArray("assignments"); for (int i = 0; i < studentinfo.length(); i++) { JSONObject studentObj = (JSONObject) studentinfo.get(i); personUtils.setTestDate(studentObj.getString("title")); personUtils.setTestDetails(studentObj.getString("date")); personUtils.setTestTitle(studentObj.getString("details")); Log.d("data",studentObj.toString()); testList.add(personUtils); } mAdapter = new CustomRecyclerAssingment(getActivity(), testList); recyclerView.setAdapter(mAdapter); } catch (JSONException e1) { e1.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO: Handle error Log.e("Volley", "Error"); } }); rq.add(jsonObjectRequest); } }
package org.gracejvc.vanrin.dao; import java.util.List; import org.gracejvc.vanrin.model.Nationality; public interface NationalityADO { public List<Nationality> allNationlity(); public Nationality findNationalityById(int id); public void newNationality(Nationality n); public void removeNationality(int id); public void updateNationlity(Nationality n); }
package com.citibank.ods.common.functionality; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import org.apache.struts.action.ActionForm; import com.citibank.ods.common.BaseObject; import com.citibank.ods.common.form.BaseForm; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.util.FormatUtils; /** * * Classe base para as classes do tipo Fnc. Esta classe possui implementações * para formatação e parsing de números e datas. * * @version: 1.00 * @author Luciano Marubayashi, Dec 21, 2006 */ public abstract class BaseFnc extends BaseObject { /** * * A implementação deste método deve ser responsável pelo preenchimento dos * dados da FncVO. <br> * O preenchimento destes dados consiste na cópia de valores dispostos na * estrutura do Form para os dados dispostos na estrutura da FncVO. <br> * Adicionalmente, o parsing de números e datas provenientes do Form através * de atributos String ou String[] deverá ser realizado por este método, * utilizando os parsers implementados nesta classe. * * @param form_ - Form que contempla os dados submetidos pela requisição. * @param fncVO_ - FncVO que será atualizada com os valores obtidos do Form. */ public abstract void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ ); /** * * A implementação deste método deve ser responsável pelo preenchimento dos * dados do Form. <br> * O preenchimento destes dados consiste na cópia de valores dispostos na * estrutura da FncVO para os dados dispostos na estrutura do Form. <br> * Adicionalmente, a formatação de números e datas provenientes da FncVO para * popular os dados do Formd everá ser realizado por este método, utilizando * os formatadores implementados nesta classe. * * @param form_ - Form que contempla os dados que serão apresentados. * @param fncVO_ - FncVO que contempla os dados que serão disponibilizados no * Form. */ public abstract void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ ); /** * * A implementação deste método deve ser responsável pela criação da instância * adequada de FncVO que é utilizada pela Fnc. * * @return instância de FncVO criada. */ public abstract BaseFncVO createFncVO(); /** * * Faz o parsing de uma String para um BigDecimal, considerando formato e * Locale do número disposto na String. O formato da String é definido no * MessageResources do Form, identificado pelo nome formatKey_. O Locale para * o parsing é definido no Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para o parsing. * @param value_ - String na qual será realizado o parsing. * @param formatKey_ - nome do formato utilizado para o parsing. * @return Instância de BigDecimal que representa o valor "parsed". */ protected BigDecimal toBigDecimal( BaseForm baseForm_, String value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); BigDecimal value = formatUtils.toBigDecimal( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return value; } /** * * Faz o parsing de uma String para um BigInteger, considerando formato e * Locale do número disposto na String. O formato da String é definido no * MessageResources do Form, identificado pelo nome formatKey_. O Locale para * o parsing é definido no Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para o parsing. * @param value_ - String na qual será realizado o parsing. * @param formatKey_ - nome do formato utilizado para o parsing. * @return Instância de BigInteger que representa o valor "parsed". */ protected BigInteger toBigInteger( BaseForm baseForm_, String value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); BigInteger value = formatUtils.toBigInteger( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return value; } /** * * Faz o parsing de uma String para um Integer, considerando formato e Locale * do número disposto na String. O formato da String é definido no * MessageResources do Form, identificado pelo nome formatKey_. O Locale para * o parsing é definido no Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para o parsing. * @param value_ - String na qual será realizado o parsing. * @param formatKey_ - nome do formato utilizado para o parsing. * @return Instância de Integer que representa o valor "parsed". */ protected Integer toInteger( BaseForm baseForm_, String value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); Integer value = formatUtils.toInteger( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return value; } /** * * Faz o parsing de uma String para um Date, considerando formato e Locale do * número disposto na String. O formato da String é definido no * MessageResources do Form, identificado pelo nome formatKey_. O Locale para * o parsing é definido no Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para o parsing. * @param value_ - String na qual será realizado o parsing. * @param formatKey_ - nome do formato utilizado para o parsing. * @return Instância de Date que representa o valor "parsed". */ protected Date toDate( BaseForm baseForm_, String value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); Date value = formatUtils.toDate( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return value; } /** * * Formata um BigDecimal utilizando uma máscara, considerando o Locale de * formatação. A máscara de formatação é obtida do MessageResources do Form, * identificada pelo nome formatKey_.O Locale para formatação é definido no * Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para a formatação. * @param value_ - Valor que será formatado. * @param formatKey_ - Nome do formato (máscara) que será utilizada. * @return String que apresenta o valor informado formatado segundo a máscara * e Locale de formatação. Será retornado uma string vazia ("") caso o * valor informado para formatação seja null. */ protected String format( BaseForm baseForm_, BigDecimal value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); String formattedValue = formatUtils.format( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return formattedValue; } /** * * Formata um Integer utilizando uma máscara, considerando o Locale de * formatação. A máscara de formatação é obtida do MessageResources do Form, * identificada pelo nome formatKey_.O Locale para formatação é definido no * Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para a formatação. * @param value_ - Valor que será formatado. * @param formatKey_ - Nome do formato (máscara) que será utilizada. * @return String que apresenta o valor informado formatado segundo a máscara * e Locale de formatação. Será retornado uma string vazia ("") caso o * valor informado para formatação seja null. */ protected String format( BaseForm baseForm_, Integer value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); String formattedValue = formatUtils.format( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return formattedValue; } /** * * Formata um BigInteger utilizando uma máscara, considerando o Locale de * formatação. A máscara de formatação é obtida do MessageResources do Form, * identificada pelo nome formatKey_.O Locale para formatação é definido no * Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para a formatação. * @param value_ - Valor que será formatado. * @param formatKey_ - Nome do formato (máscara) que será utilizada. * @return String que apresenta o valor informado formatado segundo a máscara * e Locale de formatação. Será retornado uma string vazia ("") caso o * valor informado para formatação seja null. */ protected String format( BaseForm baseForm_, BigInteger value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); String formattedValue = formatUtils.format( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return formattedValue; } /** * * Formata um Date utilizando uma máscara, considerando o Locale de * formatação. A máscara de formatação é obtida do MessageResources do Form, * identificada pelo nome formatKey_.O Locale para formatação é definido no * Locale do Form. * * @param baseForm_ - Form que contempla as informações de MessageResources e * Locale para a formatação. * @param value_ - Valor que será formatado. * @param formatKey_ - Nome do formato (máscara) que será utilizada. * @return String que apresenta o valor informado formatado segundo a máscara * e Locale de formatação. Será retornado uma string vazia ("") caso o * valor informado para formatação seja null. */ protected String format( BaseForm baseForm_, Date value_, String formatKey_ ) { FormatUtils formatUtils = FormatUtils.getInstance(); String formattedValue = formatUtils.format( value_, formatKey_, baseForm_.getCurrentLocale(), baseForm_.getCurrentMessageResources() ); return formattedValue; } }
/***************************** * * (C) Copyright 2011 Marvell International Ltd. * * All Rights Reserved * * Author Linda * * Create Date Jan 26 2011 */ package com.marvell.usbsetting; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.CheckBoxPreference; import android.preference.PreferenceScreen; import android.preference.Preference; import android.content.Intent; import android.util.Log; import android.os.Handler; import android.os.SystemProperties; import android.os.AsyncResult; import android.os.Message; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.android.internal.telephony.Phone; import com.android.internal.telephony.PhoneFactory; import com.android.internal.telephony.TelephonyIntents; import com.android.internal.telephony.TelephonyProperties; public class WcdmaBandSetting extends PreferenceActivity implements Preference.OnPreferenceChangeListener { private static final boolean DBG = true; private static final String LOG_TAG = "WcdmaBandSetting"; // UMTS band bit private static final int UMTSBAND_BAND_1 = 0x01; // IMT-2100 private static final int UMTSBAND_BAND_2 = 0x02; // PCS-1900 private static final int UMTSBAND_BAND_3 = 0x04; // DCS-1800 private static final int UMTSBAND_BAND_4 = 0x08; // AWS-1700 private static final int UMTSBAND_BAND_5 = 0x10; // CLR-850 private static final int UMTSBAND_BAND_6 = 0x20; // 800Mhz private static final int UMTSBAND_BAND_7 = 0x40; // IMT-E 2600 private static final int UMTSBAND_BAND_8 = 0x80; // GSM-900 private static final int UMTSBAND_BAND_9 = 0x100; // not used // Set command controls parameters for GSM/UMTS/TD user mode and optionally // band setting private int mMode; private int mModemBand = 0; private int mSettingBand; private int mRequest = 0xFF000000; // UI objects private PreferenceScreen mFirstPrefScreen; private CheckBoxPreference mUmts_1; private CheckBoxPreference mUmts_2; private CheckBoxPreference mUmts_3; private CheckBoxPreference mUmts_4; private CheckBoxPreference mUmts_5; private CheckBoxPreference mUmts_6; private CheckBoxPreference mUmts_7; private CheckBoxPreference mUmts_8; private CheckBoxPreference mUmts_9; // toast infomations private final int toastLongTime = Toast.LENGTH_LONG; private final String bandSettingFailure = "Oops, Band Setting failure!"; private static final int MENU_SAVE = Menu.FIRST; private static final int MENU_CANCEL = Menu.FIRST + 1; private Phone mPhone; private MyHandler mHandler; public void getInitValue() { mMode = android.provider.Settings.Secure.getInt(mPhone.getContext() .getContentResolver(), android.provider.Settings.Secure.PREFERRED_NETWORK_MODE, Phone.PREFERRED_NT_MODE); mModemBand = android.provider.Settings.Secure.getInt(mPhone .getContext().getContentResolver(), "gsm.marvell.band", 0); mSettingBand = mModemBand; if (DBG) { log("getInitValue mMode=" + mMode + ",mModemBand=" + mModemBand + ",mSettingBand=" + mSettingBand); } InitAfterGetBand(mModemBand); } public void InitAfterGetBand(int mInitModemBand) { mUmts_1 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_1"); mUmts_1.setChecked((mInitModemBand & UMTSBAND_BAND_1) == 0x01); mUmts_1.setOnPreferenceChangeListener(this); mUmts_2 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_2"); mUmts_2.setChecked((mInitModemBand & UMTSBAND_BAND_2) == 0x02); mUmts_2.setOnPreferenceChangeListener(this); mUmts_3 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_3"); mUmts_3.setChecked((mInitModemBand & UMTSBAND_BAND_3) == 0x04); mUmts_3.setOnPreferenceChangeListener(this); mUmts_4 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_4"); mUmts_4.setChecked((mInitModemBand & UMTSBAND_BAND_4) == 0x08); mUmts_4.setOnPreferenceChangeListener(this); mUmts_5 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_5"); mUmts_5.setChecked((mInitModemBand & UMTSBAND_BAND_5) == 0x10); mUmts_5.setOnPreferenceChangeListener(this); mUmts_6 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_6"); mUmts_6.setChecked((mInitModemBand & UMTSBAND_BAND_6) == 0x20); mUmts_6.setOnPreferenceChangeListener(this); mUmts_7 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_7"); mUmts_7.setChecked((mInitModemBand & UMTSBAND_BAND_7) == 0x40); mUmts_7.setOnPreferenceChangeListener(this); mUmts_8 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_8"); mUmts_8.setChecked((mInitModemBand & UMTSBAND_BAND_8) == 0x80); mUmts_8.setOnPreferenceChangeListener(this); mUmts_9 = (CheckBoxPreference) mFirstPrefScreen .findPreference("button_umts_9"); mUmts_9.setChecked((mInitModemBand & UMTSBAND_BAND_9) == 0x100); mUmts_9.setOnPreferenceChangeListener(this); } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.wcdma_band_setting); mPhone = PhoneFactory.getDefaultPhone(); mHandler = new MyHandler(); mFirstPrefScreen = getPreferenceScreen(); getInitValue(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_SAVE, 0, R.string.menu_save).setIcon( android.R.drawable.ic_menu_save); menu.add(0, MENU_CANCEL, 0, R.string.menu_cancel).setIcon( android.R.drawable.ic_menu_close_clear_cancel); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_SAVE: if (mSettingBand != mModemBand) { // set modem band value // ril-mm.c case RIL_REQUEST_SELECT_BAND: // 24~31bits indicate the setting rule, FF is the general // setting, 00 is the LGE setting, here we consider general // 23~16bits is the mode, 15~0bits is the settingBand mRequest = ((mMode << 16) | 0xFF000000) | (mSettingBand & 0x0000FFFF); if (DBG) { log("menu set Band mRequest=" + mRequest + ",mMode=" + mMode + ",mSettingBand" + mSettingBand); } mPhone.selectBand(mRequest, mHandler .obtainMessage(MyHandler.MESSAGE_SET_BAND_VALUE)); } finish(); return true; case MENU_CANCEL: finish(); return true; } return super.onOptionsItemSelected(item); } public boolean onPreferenceChange(Preference preference, Object objValue) { boolean enable = (Boolean) objValue; if ((preference.getKey()).equals("button_umts_1")) { mUmts_1.setChecked(!mUmts_1.isChecked()); if (mUmts_1.isChecked()) { mSettingBand |= UMTSBAND_BAND_1; } else { mSettingBand &= (~UMTSBAND_BAND_1); } return true; } else if ((preference.getKey()).equals("button_umts_2")) { mUmts_2.setChecked(!mUmts_2.isChecked()); if (mUmts_2.isChecked()) { mSettingBand |= UMTSBAND_BAND_2; } else { mSettingBand &= (~UMTSBAND_BAND_2); } return true; } else if ((preference.getKey()).equals("button_umts_3")) { mUmts_3.setChecked(!mUmts_3.isChecked()); if (mUmts_3.isChecked()) { mSettingBand |= UMTSBAND_BAND_3; } else { mSettingBand &= (~UMTSBAND_BAND_3); } return true; } else if ((preference.getKey()).equals("button_umts_4")) { mUmts_4.setChecked(!mUmts_4.isChecked()); if (mUmts_4.isChecked()) { mSettingBand |= UMTSBAND_BAND_4; } else { mSettingBand &= (~UMTSBAND_BAND_4); } return true; } else if ((preference.getKey()).equals("button_umts_5")) { mUmts_5.setChecked(!mUmts_5.isChecked()); if (mUmts_5.isChecked()) { mSettingBand |= UMTSBAND_BAND_5; } else { mSettingBand &= (~UMTSBAND_BAND_5); } return true; } else if ((preference.getKey()).equals("button_umts_6")) { mUmts_6.setChecked(!mUmts_6.isChecked()); if (mUmts_6.isChecked()) { mSettingBand |= UMTSBAND_BAND_6; } else { mSettingBand &= (~UMTSBAND_BAND_6); } return true; } else if ((preference.getKey()).equals("button_umts_7")) { mUmts_7.setChecked(!mUmts_7.isChecked()); if (mUmts_7.isChecked()) { mSettingBand |= UMTSBAND_BAND_7; } else { mSettingBand &= (~UMTSBAND_BAND_7); } return true; } else if ((preference.getKey()).equals("button_umts_8")) { mUmts_8.setChecked(!mUmts_8.isChecked()); if (mUmts_8.isChecked()) { mSettingBand |= UMTSBAND_BAND_8; } else { mSettingBand &= (~UMTSBAND_BAND_8); } return true; } else if ((preference.getKey()).equals("button_umts_9")) { mUmts_9.setChecked(!mUmts_9.isChecked()); if (mUmts_9.isChecked()) { mSettingBand |= UMTSBAND_BAND_9; } else { mSettingBand &= (~UMTSBAND_BAND_9); } return true; } return true; } private class MyHandler extends Handler { private static final int MESSAGE_GET_BAND_VALUE = 0; private static final int MESSAGE_SET_BAND_VALUE = 1; @Override public void handleMessage(Message msg) { switch (msg.what) { case MESSAGE_GET_BAND_VALUE: handleGetBandValueResponse(msg); break; case MESSAGE_SET_BAND_VALUE: handleSetBandValueResponse(msg); break; } } private void handleGetBandValueResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (DBG) { log("handleGetBandBalueResponse ar.exception is" + (ar.exception == null)); } if (ar.exception == null) { mModemBand = ((int[]) ar.result)[0]; if (DBG) { log("handleGetBandValueResponse: modem bandValue = " + mModemBand); } } else { // if (DBG) // log("handleGetBandValueResponse: else: reset to default"); // resetBandToDefault(); if (DBG) log("handleGetBandValueResponse: else: GET failure, do nothing "); } } private void handleSetBandValueResponse(Message msg) { AsyncResult ar = (AsyncResult) msg.obj; if (ar.exception == null) { if (DBG) { log("handleSetBandValueResponse: set success"); } } else { Toast t1 = Toast.makeText(getApplicationContext(), bandSettingFailure, toastLongTime); t1.show(); mPhone.getBand(obtainMessage(MESSAGE_GET_BAND_VALUE)); } } private void resetBandToDefault() { // Set the Modem // ril-mm.c case RIL_REQUEST_SELECT_BAND: // 24~31bits indicate the setting rule, FF is the general setting, // 00 is the LGE setting, here we consider general // 23~16bits is the mode, 15~0bits is the settingBand mRequest = ((mMode << 16) | 0xFF000000) | (mModemBand & 0x0000FFFF); if (DBG) { log("reset Band to Default mRequest=" + mRequest + ",mMode=" + mMode + ",mModemBand" + mModemBand); } mPhone.selectBand(mRequest, this .obtainMessage(MyHandler.MESSAGE_SET_BAND_VALUE)); } } private static void log(String msg) { Log.d(LOG_TAG, msg); } }
/* * UserController * * Version 1.0 * * November 25, 2017 * * Copyright (c) 2017 Team 26, CMPUT 301, University of Alberta - All Rights Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta. * You can find a copy of the license in this project. Otherwise please contact rohan@ualberta.ca * * Purpose: Controller class for storing and retrieving the User */ package cmput301f17t26.smores.all_storage_controller; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.UUID; import cmput301f17t26.smores.all_models.Feed; import cmput301f17t26.smores.all_models.Habit; import cmput301f17t26.smores.all_models.HabitEvent; import cmput301f17t26.smores.all_models.User; /** * Created by apate on 2017-10-31. */ public class UserController { private User user; private static final String SAVED_DATA_KEY = "cmput301f17t26.smores.all_storage_controller.user_controller"; private static UserController mUserController = null; public static UserController getUserController(Context context) { if (mUserController == null) { mUserController = new UserController(context); return mUserController; } return mUserController; } private UserController( Context context) { initController(context); } private void retrieveUser(Context context) { SharedPreferences userData = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); Gson gson = new Gson(); String JSONUser = userData.getString(SAVED_DATA_KEY, ""); if (!JSONUser.equals("")) { user = gson.fromJson(JSONUser, new TypeToken<User>(){}.getType()); } } private void saveUser(Context context, User user) { SharedPreferences userData = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()); Gson gson = new Gson(); String jsonUser = gson.toJson(user); SharedPreferences.Editor prefsEditor = userData.edit(); prefsEditor.putString(SAVED_DATA_KEY, jsonUser); prefsEditor.apply(); retrieveUser(context); } public User getUser() { return user; } private void initController(Context context) { retrieveUser(context); } public boolean isUserSet() { return user != null; } boolean checkUsername(String username) { ArrayList<User> foundUsers = new ArrayList<User>(); ElasticSearchController.CheckUserTask checkUserTask = new ElasticSearchController.CheckUserTask(); checkUserTask.execute("username", username); try { foundUsers.addAll(checkUserTask.get()); } catch (Exception e) { e.printStackTrace(); } return foundUsers.size() == 0; } public boolean addUser(Context context, User user) { if (!checkUsername(user.getUsername())){ //username not unique return false; } else { //username unique ElasticSearchController.AddUserTask addUserTask = new ElasticSearchController.AddUserTask(); addUserTask.execute(user); saveUser(context, user); return true; } } public void updateFollowingList() { ElasticSearchController.CheckUserTask checkUserTask = new ElasticSearchController.CheckUserTask(); checkUserTask.execute("username", user.getUsername()); try { user.setFollowingList(checkUserTask.get().get(0).getFollowingList()); } catch (Exception e) { } } public ArrayList<HabitEvent> getFriendsHabitEvents() { ArrayList<HabitEvent> friendHabitEvents = new ArrayList<>(); for (UUID friendUUID: user.getFollowingList()) { ElasticSearchController.GetHabitEventTask getHabitEventTask = new ElasticSearchController.GetHabitEventTask(); getHabitEventTask.execute("mUserID", friendUUID.toString()); try { ArrayList<HabitEvent> friendI = getHabitEventTask.get(); Log.d("User controller", friendI.get(0).getHabitID().toString()); if (friendI.size() > 0) { Collections.sort(friendI, new Comparator<HabitEvent>() { @Override public int compare(HabitEvent o1, HabitEvent o2) { return o1.getDate().compareTo(o2.getDate()); } }); friendHabitEvents.addAll(friendI); } } catch (Exception e) { } } return friendHabitEvents; } public ArrayList<Habit> getFriendsHabits() { ArrayList<Habit> friendHabits = new ArrayList<>(); for (UUID friendUUID: user.getFollowingList()) { ElasticSearchController.GetHabitTask getHabitTask = new ElasticSearchController.GetHabitTask(); getHabitTask.execute("mUserID", friendUUID.toString()); try { ArrayList<Habit> friendI = getHabitTask.get(); Log.d("User controller", friendI.get(0).getTitle()); if (friendI.size() > 0) { friendHabits.addAll(friendI); } } catch (Exception e) { } } return friendHabits; } public ArrayList<HabitEvent> mostRecentFriendsHabitEvents() { ArrayList<HabitEvent> habitEvents = new ArrayList<>(); ArrayList<HabitEvent> friendsHabitEvents = getFriendsHabitEvents(); ArrayList<Habit> friendsHabits = getFriendsHabits(); HashMap<Habit, HabitEvent> habitHabitEventHashMap = pairUp(friendsHabits, friendsHabitEvents); for (Habit habit: habitHabitEventHashMap.keySet()) { if (habitHabitEventHashMap.get(habit) != null) { habitEvents.add(habitHabitEventHashMap.get(habit)); } } return habitEvents; } public ArrayList<Feed> getFeed() { ArrayList<HabitEvent> friendsHabitEvents = getFriendsHabitEvents(); ArrayList<Habit> friendsHabits = getFriendsHabits(); HashMap<Habit, HabitEvent> habitHabitEventHashMap = pairUp(friendsHabits, friendsHabitEvents); ArrayList<Feed> feed = new ArrayList<>(); for (Habit habit: habitHabitEventHashMap.keySet()) { Feed f = new Feed(getUsernameByID(habit.getUserID()), habit, habitHabitEventHashMap.get(habit)); feed.add(f); } // ArrayList<Habit> unprocessedHabits = new ArrayList<Habit>(); // // // // // // // unprocessedHabits.addAll(friendsHabits); // // for (Habit habit: friendsHabits) { // // for (HabitEvent habitEvent: friendsHabitEvents) { // if (habitEvent.getHabitID().equals(habit.getID())) { // Feed f = new Feed(getUsernameByID(habit.getUserID()), habit, habitEvent); // unprocessedHabits.remove(habit); // feed.add(f); // } // } // } // for (Habit habit: unprocessedHabits) { // Feed f = new Feed(getUsernameByID(habit.getUserID()), habit, null); // feed.add(f); // } Collections.sort(feed, new Comparator<Feed>() { @Override public int compare(Feed o1, Feed o2) { int compareValue = o1.getUsername().compareTo(o2.getUsername()); if (compareValue != 0) { return compareValue; } else { return o1.getHabit().getTitle().compareTo(o2.getHabit().getTitle()); } } }); return feed; } public HashMap<Habit,HabitEvent> pairUp(ArrayList<Habit> friendHabits, ArrayList<HabitEvent> friendHabitEvents) { HashMap<Habit, ArrayList<HabitEvent>> habitEventHashMap = new HashMap<>(); for (Habit habit: friendHabits) { ArrayList<HabitEvent> habitEvents = new ArrayList<>(); for (HabitEvent habitEvent: friendHabitEvents) { if (habitEvent.getHabitID().equals(habit.getID())) { habitEvents.add(habitEvent); } } Collections.sort(habitEvents, new Comparator<HabitEvent>() { @Override public int compare(HabitEvent o1, HabitEvent o2) { return o1.getDate().compareTo(o2.getDate()); } }); Collections.reverse(habitEvents); habitEventHashMap.put(habit, habitEvents); } HashMap<Habit, HabitEvent> habitHabitEventHashMap = new HashMap<>(); for (Habit habit: habitEventHashMap.keySet()) { habit.calculateStats(habitEventHashMap.get(habit)); if (habitEventHashMap.get(habit).size() == 0) { habitHabitEventHashMap.put(habit, null); } else { habitHabitEventHashMap.put(habit, habitEventHashMap.get(habit).get(0)); } } return habitHabitEventHashMap; } public String getUsernameByID(UUID uuid) { ElasticSearchController.CheckUserTask checkUserTask = new ElasticSearchController.CheckUserTask(); checkUserTask.execute("mID", uuid.toString()); try { ArrayList<User> users = checkUserTask.get(); return users.get(0).getUsername(); } catch (Exception e) { return null; } } }
package br.com.db1start.aula2; public class Calculadora { public int somar(int numero1, int numero2) { return numero1 + numero2; } public int sub(int numero1, int numero2) { return numero1 - numero2; } public int mult(int numero1, int numero2) { return numero1 * numero2; } public int div(int numero1, int numero2) { return numero1 / numero2; } public boolean parImpar(int numero) { if (numero % 2 == 0) { return true; } else { return false; } } public int comparar(int numero1, int numero2) { if (numero1 > numero2) { return numero1; } return numero2; } public int imparAte100(int numero1) { int contador = 0; for (int i = numero1+1; i < 100; i++) { if (!parImpar(i)) { contador = contador+1; } } return contador; } }
package com.project.android.app.kys.adapters; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.project.android.app.kys.R; import com.project.android.app.kys.business.Discipline; import java.util.ArrayList; public class CustomAdaptorDiscipline extends BaseAdapter { private static ArrayList<Discipline> Discipline_List; Context context; private LayoutInflater mInflater; public CustomAdaptorDiscipline(Context context, ArrayList<Discipline> results) { Discipline_List = results; this.context = context; mInflater = LayoutInflater.from(context); } public int getCount() { return Discipline_List.size(); } public Object getItem(int position) { return Discipline_List.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = mInflater.inflate(R.layout.custom_disciplinelist, null); holder = new ViewHolder(); holder.Initial = (TextView) convertView.findViewById(R.id.tv_disiplineInitials); holder.DepartmentName = (TextView) convertView.findViewById(R.id.tv_DiscilpineTitle); holder.DepartmentSummary = (TextView) convertView.findViewById(R.id.tv_disciplineSummary); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.Initial.setText(Discipline_List.get(position).getDisciplineInitials()); holder.DepartmentName.setText(Discipline_List.get(position).getDisciplineName()); holder.DepartmentSummary.setText(Discipline_List.get(position).getDisciplineSummary()); return convertView; } static class ViewHolder { TextView Initial; TextView DepartmentName; TextView DepartmentSummary; } }
package arcs.demo.particles; import arcs.api.Collection; import arcs.api.Handle; import arcs.api.ParticleBase; import arcs.api.PortableJson; import arcs.api.PortableJsonParser; import java.util.List; import java.util.Map; import java.util.function.Consumer; public class RenderText extends ParticleBase { private PortableJsonParser parser; public RenderText(PortableJsonParser parser) { this.parser = parser; } @Override public void setHandles(Map<String, Handle> handleByName) { super.setHandles(handleByName); this.output(); } @Override public void setOutput(Consumer<PortableJson> output) { super.setOutput(output); this.output(); } @Override public String getTemplate(String slotName) { return "Hello world!"; } }
package com.gaoshin.onsalelocal.yipit.service.impl; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gaoshin.onsalelocal.api.Offer; import com.gaoshin.onsalelocal.api.OfferDetails; import com.gaoshin.onsalelocal.api.OfferDetailsList; import com.gaoshin.onsalelocal.yipit.api.Division; import com.gaoshin.onsalelocal.yipit.api.DivisionListRequest; import com.gaoshin.onsalelocal.yipit.api.DivisionResponse; import com.gaoshin.onsalelocal.yipit.api.Source; import com.gaoshin.onsalelocal.yipit.api.SourceListRequest; import com.gaoshin.onsalelocal.yipit.api.SourceResponse; import com.gaoshin.onsalelocal.yipit.dao.YipitDao; import com.gaoshin.onsalelocal.yipit.entity.DbDivision; import com.gaoshin.onsalelocal.yipit.entity.DbSource; import com.gaoshin.onsalelocal.yipit.service.YipitService; import common.geo.Geocode; import common.util.reflection.ReflectionUtil; @Service("yipitService") @Transactional(readOnly=true) public class YipitServiceImpl extends ServiceBaseImpl implements YipitService { @Autowired private YipitDao yipitDao; @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void updateTasks() { yipitDao.updateTasks(); } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void seedTasks() { yipitDao.seedCityTasks(); } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void seedDivisions() throws Exception { DivisionListRequest req = new DivisionListRequest(); DivisionResponse response = req.call(DivisionResponse.class); for(Division div : response.getResponse().getDivisions()) { DbDivision db = ReflectionUtil.copy(DbDivision.class, div); db.setId(div.getSlug()); yipitDao.replace(db); } } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void seedDivisionTasks() { yipitDao.seedDivisionTasks(); } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void seedSources() throws Exception { SourceListRequest req = new SourceListRequest(); SourceResponse response = req.call(SourceResponse.class); for(Source div : response.getResponse().getSources()) { DbSource db = ReflectionUtil.copy(DbSource.class, div); db.setId(div.getSlug()); yipitDao.replace(db); } } @Override @Transactional(readOnly=false, rollbackFor=Throwable.class) public void seedCityTasks() { yipitDao.seedCityTasks(); } @Override public OfferDetailsList searchOffer(final float lat, final float lng, int radius) { List<Offer> offers = yipitDao.listOffersIn(lat, lng, radius); OfferDetailsList list = new OfferDetailsList(); for(Offer o : offers) { OfferDetails details = ReflectionUtil.copy(OfferDetails.class, o); list.getItems().add(details); float dis1 = Geocode.distance(o.getLatitude(), o.getLongitude(), lat, lng); details.setDistance(dis1); } Collections.sort(list.getItems(), new Comparator<OfferDetails>() { @Override public int compare(OfferDetails o1, OfferDetails o2) { return (int) ((o1.getDistance() - o2.getDistance()) * 1000); } }); return list; } }
import java.awt.geom.Rectangle2D; public class Comuna { private Individuo person; private Rectangle2D territory; // Alternatively: double width, length; public Comuna(){ territory = new Rectangle2D.Double(0, 0, 1000, 1000); // 1000x1000 m²; } public Comuna(double width, double length){ territory = new Rectangle2D.Double(0,0, width, length); person=null; } public double getWidth() { return this.territory.getWidth(); } public double getHeight() { return this.territory.getHeight(); } public void setPerson(Individuo person){ this.person=person; } public void computeNextState (double delta_t) { person.computeNextState(delta_t); } public void updateState () { person.updateState(); } // include others methods as necessary public String getStateDescription () { String s = person.getStateDescription(); return s; } public String getState() { String s = person.getState(); return s; } }
package com.BDD.blue_whale.entities; import java.security.Timestamp; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.rest.core.config.Projection; @Projection(name="ImpoExpo", types={com.BDD.blue_whale.entities.Import_export.class}) public interface ProjectionImport_export { @Value("#{target.id}") public Long getId(); public String getTrade_flow(); public Integer getYears(); public String getMonths(); public Float getValue(); public String getUnit_value(); public Float getNetweight(); public String getUnit_netweight(); public Timestamp getDate_modif(); public Country getCountry_expo(); public Country getCountry_impo(); public Product getProduct(); public Variety getVariety(); public Source getSource(); }
package org.carpark; import junit.framework.TestCase; import org.carpark.carpark.CarPark; import org.carpark.carpark.CarParkCharge; import org.carpark.carpark.CarParkSpaces; import org.carpark.paymentmachine.PaymentMachine; import org.carpark.transaction.Transaction; import java.util.Hashtable; import java.util.*; /** * Test CentralComputer class * @author Marjan Rahimi * @version March 2005 */ public class CentralComputerTest extends TestCase { CentralComputer centralComputer; CarParkCharge cpCharge; CarParkCharge cpCharge1; CarPark cp; DirectionSign ds; PaymentMachine pm; protected void setUp() throws Exception { super.setUp(); centralComputer = CentralComputer.getInstance(); cpCharge = new CarParkCharge(10,20,30,40,50,60,70,80,90,100,110); } /** * Test getInstance static method */ public void testGetInstance() { assertNotNull(centralComputer); CentralComputer cc2 = CentralComputer.getInstance(); assertNotNull(cc2); assertEquals(centralComputer, cc2); } /** * Test setCarParkCharge and getCarParkCharge methods */ public void testSetAndGetCarParkCharge() { //Test with null CarParkCharge boolean isCatched = false; try{ centralComputer.setCarParkCharge(cpCharge1); }catch(NullPointerException e){isCatched = true;} assertTrue(isCatched); //Test successful set centralComputer.setCarParkCharge(cpCharge); assertEquals(cpCharge, centralComputer.getCarParkCharge()); } /** * Test addCarPark method */ public void testAddCarPark() { //Test adding null CarPark boolean isCatched = false; try{ centralComputer.addCarPark(cp); }catch(NullPointerException e){isCatched = true;} assertTrue(isCatched); assertTrue(centralComputer.getCarParksList().isEmpty()); //Test successful adding CarPark cp1 = new CarPark(new ThreadGroup(""), "", 500, 1); centralComputer.addCarPark(cp1); assertEquals(centralComputer.getCarParksList().size(),1); CarPark cp2 = new CarPark(new ThreadGroup(""), "", 600, 2); centralComputer.addCarPark(cp2); CarPark cp3 = new CarPark(new ThreadGroup(""), "", 700, 3); centralComputer.addCarPark(cp3); assertEquals(centralComputer.getCarParksList().size(),3); Hashtable<Integer, CarPark> carParks = centralComputer.getCarParksList(); assertEquals(carParks.get(1),cp1); assertEquals(carParks.get(2),cp2); assertEquals(carParks.get(3),cp3); System.out.println(centralComputer.toString()); } /** * Test addDirectionSign method */ public void testAddDirectionSign() { //Test adding null DirectionSign boolean isCatched = false; try{ centralComputer.addDirectionSign(ds); }catch(NullPointerException e){isCatched = true;} assertTrue(isCatched); assertTrue(centralComputer.getDirectionSignList().isEmpty()); //Test successful adding Hashtable<Integer, Location> cpLocations = new Hashtable<Integer, Location>(); cpLocations.put(1,new Location(8374, Direction.LEFT)); cpLocations.put(1,new Location(374, Direction.RIGHT)); cpLocations.put(1,new Location(74, Direction.STRAIGHT)); cpLocations.put(1,new Location(4, Direction.LEFT)); DirectionSign ds1 = new DirectionSign(cpLocations); centralComputer.addDirectionSign(ds1); assertEquals(1, centralComputer.getDirectionSignList().size()); cpLocations = new Hashtable<Integer, Location>(); cpLocations.put(1,new Location(2345, Direction.LEFT)); cpLocations.put(1,new Location(345, Direction.RIGHT)); cpLocations.put(1,new Location(45, Direction.STRAIGHT)); cpLocations.put(1,new Location(5, Direction.LEFT)); DirectionSign ds2 = new DirectionSign(cpLocations); centralComputer.addDirectionSign(ds2); assertEquals(2, centralComputer.getDirectionSignList().size()); Vector<DirectionSign> dss = centralComputer.getDirectionSignList(); assertEquals(dss.get(0), ds1); assertEquals(dss.get(1), ds2); System.out.println(centralComputer.toString()); } /** * Test addPaymentMachine method */ public void testAddPaymentMachine(){ //Test adding null PaymentMachine boolean isCatched = false; try{ centralComputer.addPaymentMachine(pm); }catch(NullPointerException e){isCatched = true;} assertTrue(isCatched); assertTrue(centralComputer.getPaymentMachinesList().isEmpty()); //Test successful adding ThreadGroup tg = new ThreadGroup("test"); PaymentMachine pm1 = new PaymentMachine(tg, "First"); centralComputer.addPaymentMachine(pm1); assertEquals(1, centralComputer.getPaymentMachinesList().size()); PaymentMachine pm2 = new PaymentMachine(tg, "Second"); centralComputer.addPaymentMachine(pm2); PaymentMachine pm3 = new PaymentMachine(tg, "Third"); centralComputer.addPaymentMachine(pm3); assertEquals(3, centralComputer.getPaymentMachinesList().size()); Vector <PaymentMachine> paymentMachines = centralComputer.getPaymentMachinesList(); assertEquals(pm1, paymentMachines.get(0)); assertEquals(pm2, paymentMachines.get(1)); assertEquals(pm3, paymentMachines.get(2)); System.out.println(centralComputer.toString()); } /** * Test getTransactionArchive method */ public void testGetTransactionArchive(){ Vector<Transaction> tList = centralComputer.getTransactionArchive(); assertTrue(centralComputer.getTransactionArchive().isEmpty()); } /** * Test getMotoristRecords method */ public void testGetMotoristRecords(){ Hashtable<Integer, Counter> mRecords = centralComputer.getMotoristRecords(); assertTrue(centralComputer.getMotoristRecords().isEmpty()); } /** * Test getSpaceAvailablityTable method */ public void testGetSpaceAvailablityTable(){ Hashtable<Date, CarParkSpaces[]> sTable = centralComputer.getSpaceAvailabilityTable(); assertTrue(centralComputer.getSpaceAvailabilityTable().isEmpty()); } /** * Test toString method */ public void testToString(){ System.out.println(centralComputer.toString()); } }//TestCentralComputer
package io.github.satr.aws.lambda.bookstore.strategies.intenthandler; // Copyright © 2022, github.com/satr, MIT License import com.amazonaws.services.lambda.runtime.LambdaLogger; import io.github.satr.aws.lambda.bookstore.entity.formatter.MessageFormatter; import io.github.satr.aws.lambda.bookstore.request.Request; import io.github.satr.aws.lambda.bookstore.respond.Response; public class NotRecognizedIntentHandler extends AbstractIntentHandlerStrategy { public NotRecognizedIntentHandler(MessageFormatter messageFormatter) { super(null); } @Override public Response handle(Request request, LambdaLogger logger) { return getCloseFulfilledLexRespond(request, "Received Intent: %s", request.getIntentName()); } }
package com.amber; import com.AmberApplication; import com.amber.dao.CommentDao; import com.amber.dao.MessageDao; import com.amber.dao.TicketDao; import com.amber.model.*; import com.amber.service.MessageService; import com.amber.service.UserService; import com.amber.util.JedisAdapter; import org.apache.commons.lang.builder.ToStringBuilder; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Date; import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = AmberApplication.class) public class AmberApplicationTests { @Autowired TicketDao ticketDao; @Autowired CommentDao commentDao; @Autowired UserService userService; @Autowired MessageService messageService; @Autowired MessageDao messageDao; @Autowired JedisAdapter jedisAdapter; @Test public void contextLoads() { for (int i = 0; i < 11; i++) { Ticket ticket = new Ticket(); ticket.setStatus(0); Date date = new Date(); date.setTime(date.getTime() + 1000 * 3600 * 24); ticket.setExpired(date); ticket.setUserId(i + 1); ticket.setTicket(String.format("Ticket%d", i)); ticketDao.addTicket(ticket); ticketDao.updateStatus(2, String.format("Ticket%d", i)); } Assert.assertEquals(4, ticketDao.selectByTicket("Ticket3").getId()); } @Test public void add_comment_test() { for (int i = 0; i < 3; i++) { Comment comment = new Comment(); comment.setContent("this is a test comment" + String.valueOf(i)); comment.setCreatedDate(new Date()); comment.setEntityId(14); comment.setEntityType(EntityType.ENTITY_NEWS); comment.setUserId(46); Assert.assertEquals(1, commentDao.addComment(comment)); } } @Test public void select_user_from_comment_id_test() { int expectedUserId = 46; int newsId = 14; List<Comment> comments = commentDao.selectCommentByEntity(newsId, EntityType.ENTITY_NEWS); for (Comment comment : comments) { Assert.assertEquals(expectedUserId, userService.getUserById(comment.getUserId()).getId()); } } @Test public void add_message_should_succesful_test() { int expectFromId = 46; Message message = new Message(); message.setFromId(46); message.setToId(47); message.setContent("hello"); message.setCreatedDate(new Date()); message.setConversationId("46_47"); Assert.assertEquals(1, messageDao.addMessage(message)); Assert.assertEquals(expectFromId, messageDao.selectAllMessageByCid("46_47", 0, 1).get(0).getFromId()); } @Test public void should_equals_seri_user() { User user = new User(); user.setName("name"); user.setHeadUrl("https://sakdjoiadna"); user.setPassword("auidadas"); user.setSalt("asd178"); jedisAdapter.setObject("u", user); User user1 = jedisAdapter.getObject("u", User.class); Assert.assertEquals("name", user1.getName()); System.out.println(ToStringBuilder.reflectionToString(user1)); } }
package com.udacity.gradle.builditbigger.presentation; import com.udacity.gradle.builditbigger.R; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * A placeholder fragment containing a simple view. */ public class MainActivityFragment extends Fragment { @Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { final View root = inflater.inflate(R.layout.fragment_main, container, false); return root; } }
package me.bayanov.temperature.Converter; public interface Converter { double convertFromCelsius(double fromNumber); double convertToCelsius(double fromNumber); }
/** * 香港理工大学-中国科学院研究生院数据挖掘-PageRank算法实现 * @author chaoyu * @right Copyright by PolyU team * @github https://github.com/yuchao86/pagerank.git * @date 2012-10-18 */ package polyu.gucas.rawPagerank.wordretrieve; /* * Tutorial 05: "Inverted File Indexing" * compile and run with : * WordUtil,MyHtmlTextHandler,HtmlWordExtractor * together with your own code. */ import java.util.*; import javax.swing.text.html.*; public class MyHtmlTextHandler extends HTMLEditorKit.ParserCallback { public Set<String> wordSet=new HashSet<String>(); protected WordUtil wutil; private String delim_num="0123456789"; private String delim_pun=",.<>/?;':\"[]{}`~!@#$%^&*()-_=+"; private String delim_ctrl=" \t\n\r"; private String delim=delim_num+delim_pun+delim_ctrl; public MyHtmlTextHandler(WordUtil wu){ wutil=wu; } public void reset(){ wordSet.clear(); } // This method is inherited from the super class // HTMLEditorKit.ParserCallback public void handleText(char[] data, int pos) { String text=new String(data); if(text==null||text.length()<1)return; StringTokenizer tok=new StringTokenizer(text,delim); while(tok.hasMoreTokens()){ String temp=tok.nextToken(); if(temp==null||temp.length()<2)continue; if(wutil.isStopWord(temp))continue; temp=wutil.stem(temp); wordSet.add(temp); } } }
package com.esum.cluster.table; import com.esum.framework.common.sql.Record; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.table.InfoRecord; public class ClusterInfoRecord extends InfoRecord { public static final String HANG_ACTION_NOTIFY = "N"; public static final String HANG_ACTION_RESTART = "R"; public static final String MEMORY_ACTION_NOTIFY = "N"; public static final String LISTENER_ACTION_NOTIFY = "N"; public static final String LISTENER_ACTION_RESTART = "R"; public static final String LISTENER_ACTION_COMP_RESTART = "C"; private String nodeId; private boolean useCluster; private int checkInterval; private String targetNodeId; private boolean moveChannelData; private String targetQueueConfigPath; private boolean hangCheck; private int hangCheckInterval; private String hangAction; private boolean memoryCheck; private int memoryCheckInterval; private int memoryActionLevel; private String memoryAction; private boolean listenerCheck; private int listenerCheckInterval; private String listenerAction; public ClusterInfoRecord(Record record) throws ComponentException { super(record); } public ClusterInfoRecord(String[] ids, Record record) throws ComponentException { super(ids, record); } protected void init(Record record) throws ComponentException { nodeId = record.getString("NODE_ID"); useCluster = record.getString("USE_CLUSTER", "N").equals("Y"); this.checkInterval = record.getInt("CHECK_INTERVAL", 60*1000); this.targetNodeId = record.getString("TARGET_NODE_ID", null); this.moveChannelData = record.getString("MOVE_CHANNEL_DATA_FLAG", "N").equals("Y"); this.targetQueueConfigPath = record.getString("TARGET_QUEUE_CONFIG_PATH"); this.hangCheck = record.getString("HANG_CHECK_FLAG", "N").equals("Y"); if(this.hangCheck) { this.hangCheckInterval = record.getInt("HANG_CHECK_INTERVAL", 180*1000); this.hangAction = record.getString("HANG_ACTION", HANG_ACTION_NOTIFY); } this.memoryCheck = record.getString("MEMORY_CHECK_FLAG", "N").equals("Y"); if(this.memoryCheck) { this.memoryCheckInterval = record.getInt("MEMORY_CHECK_INTERVAL", 60*1000); this.memoryActionLevel = record.getInt("MEMORY_ACTION_LEVEL", 80); this.memoryAction = record.getString("MEMORY_ACTION", MEMORY_ACTION_NOTIFY); } this.listenerCheck = record.getString("LISTENER_CHECK_FLAG", "N").equals("Y"); if(this.listenerCheck) { this.listenerCheckInterval = record.getInt("LISTENER_CHECK_INTERVAL", 60*1000); this.listenerAction = record.getString("LISTENER_ACTION", LISTENER_ACTION_NOTIFY); } } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } public boolean isUseCluster() { return useCluster; } public void setUseCluster(boolean useCluster) { this.useCluster = useCluster; } public int getCheckInterval() { return checkInterval; } public void setCheckInterval(int checkInterval) { this.checkInterval = checkInterval; } public String getTargetNodeId() { return targetNodeId; } public void setTargetNodeId(String targetNodeId) { this.targetNodeId = targetNodeId; } public String getTargetQueueConfigPath() { return targetQueueConfigPath; } public void setTargetQueueConfigPath(String targetQueueConfigPath) { this.targetQueueConfigPath = targetQueueConfigPath; } public boolean isMoveChannelData() { return moveChannelData; } public void setMoveChannelData(boolean moveChannelData) { this.moveChannelData = moveChannelData; } public boolean isHangCheck() { return hangCheck; } public void setHangCheck(boolean hangCheck) { this.hangCheck = hangCheck; } public int getHangCheckInterval() { return hangCheckInterval; } public void setHangCheckInterval(int hangCheckInterval) { this.hangCheckInterval = hangCheckInterval; } public String getHangAction() { return hangAction; } public void setHangAction(String hangAction) { this.hangAction = hangAction; } public boolean isMemoryCheck() { return memoryCheck; } public void setMemoryCheck(boolean memoryCheck) { this.memoryCheck = memoryCheck; } public int getMemoryCheckInterval() { return memoryCheckInterval; } public void setMemoryCheckInterval(int memoryCheckInterval) { this.memoryCheckInterval = memoryCheckInterval; } public int getMemoryActionLevel() { return memoryActionLevel; } public void setMemoryActionLevel(int memoryActionLevel) { this.memoryActionLevel = memoryActionLevel; } public String getMemoryAction() { return memoryAction; } public void setMemoryAction(String memoryAction) { this.memoryAction = memoryAction; } public boolean isListenerCheck() { return listenerCheck; } public void setListenerCheck(boolean listenerCheck) { this.listenerCheck = listenerCheck; } public int getListenerCheckInterval() { return listenerCheckInterval; } public void setListenerCheckInterval(int listenerCheckInterval) { this.listenerCheckInterval = listenerCheckInterval; } public String getListenerAction() { return listenerAction; } public void setListenerAction(String listenerAction) { this.listenerAction = listenerAction; } }
// A Purse holds a collection of Coins import java.util.ArrayList; import java.util.Arrays; public class Purse { private ArrayList<Coin> coins; public Purse() { coins = new ArrayList(); } // adds aCoin to the purse public void add(Coin aCoin) { coins.add(aCoin); } // returns total value of all coins in purse public double getTotal() { double sum =0; for (int i = 0; i < this.coins.size(); i++) { sum += coins.get(i).getValue(); } return sum; } // returns the number of coins in the Purse that matches aCoin // (both myName & myValue) public int count(Coin aCoin) { int total = 0; for (Coin c : this.coins) { if (c.equals(aCoin)) { total++; } } return total; } public String findSmallest(){ double smallest = 0.25; String out = ""; for (Coin x : this.coins){ if (x.getValue() <= smallest){ smallest = x.getValue(); out = x.getName(); } } return out; } }
package org.wso2.carbon.identity.recovery.endpoint.dto; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import org.wso2.carbon.identity.recovery.endpoint.dto.PropertyDTO; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.*; import javax.validation.constraints.NotNull; @ApiModel(description = "") public class CodeValidationRequestDTO { private String code = null; private String step = null; private List<PropertyDTO> properties = new ArrayList<PropertyDTO>(); /** **/ @ApiModelProperty(value = "") @JsonProperty("code") public String getCode() { return code; } public void setCode(String code) { this.code = code; } /** **/ @ApiModelProperty(value = "") @JsonProperty("step") public String getStep() { return step; } public void setStep(String step) { this.step = step; } /** **/ @ApiModelProperty(value = "") @JsonProperty("properties") public List<PropertyDTO> getProperties() { return properties; } public void setProperties(List<PropertyDTO> properties) { this.properties = properties; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CodeValidationRequestDTO {\n"); sb.append(" code: ").append(code).append("\n"); sb.append(" step: ").append(step).append("\n"); sb.append(" properties: ").append(properties).append("\n"); sb.append("}\n"); return sb.toString(); } }
package com.git.cloud.handler.automation.pv.impl; import java.util.HashMap; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.git.cloud.foundation.common.WebApplicationManager; import com.git.cloud.foundation.util.UUIDGenerator; import com.git.cloud.handler.automation.pv.OpenstackPowerVcCommonHandler; import com.git.cloud.handler.automation.se.boc.SeConstants; import com.git.cloud.powervc.common.OpenstackPowerVcServiceFactory; import com.git.cloud.powervc.model.VolumeModel; import com.git.cloud.resmgt.common.dao.impl.CmDeviceDAO; import com.git.cloud.resmgt.openstack.model.vo.VolumeDetailVo; import com.git.support.common.PVOperation; /** * 创建数据卷 * @author SunHailong * @version 版本号 2017-4-1 */ public class CreateDataVolumeHandler extends OpenstackPowerVcCommonHandler { private static Logger logger = LoggerFactory.getLogger(CreateDataVolumeHandler.class); @SuppressWarnings("unchecked") @Override public void executeOperate(HashMap<String, Object> reqMap) throws Exception { String rrinfoId = (String) reqMap.get(SeConstants.RRINFO_ID); HashMap<String, String> deviceParams; List<String> deviceIdList = getAutomationService().getDeviceIdsSort(rrinfoId); String logCommon = ""; String volumeId = ""; String volumeIaasUuid = ""; boolean isShare = false; for(int i=0 ; i<deviceIdList.size() ; i++) { if(!isShare) { // 非共享卷时 logCommon = "创建第" + (i+1) + "个数据盘"; logger.debug(logCommon + "开始..."); deviceParams = (HashMap<String, String>) reqMap.get(deviceIdList.get(i)); String domainName = deviceParams.get("DOMAIN_NAME"); String openstackIp = deviceParams.get("OPENSTACK_IP"); if(openstackIp == null || "".equals(openstackIp)) { throw new Exception("服务器IP地址为空,请检查参数[OPENSTACK_IP]."); } String token = deviceParams.get("TOKEN"); if(token == null || "".equals(token)) { throw new Exception("认证TOKEN为空,请检查参数[TOKEN]."); } String projectId = deviceParams.get("PROJECT_ID"); if(projectId == null || "".equals(projectId)) { throw new Exception("ProjectId为空,请检查参数[PROJECT_ID]."); } String azName = deviceParams.get("AVAILABILITY_ZONE"); if(azName == null || "".equals(azName)) { throw new Exception("可用分区为空,请检查参数[AVAILABILITY_ZONE]."); } String dataDisk = deviceParams.get("DATA_DISK"); if(dataDisk == null || "".equals(dataDisk)) { throw new Exception("数据卷大小为空,请检查参数[DATA_DISK]."); } String hostType = deviceParams.get("HOST_TYPE"); if(hostType == null || "".equals(hostType)) { throw new Exception("主机类型为空,请检查参数[HOST_TYPE]."); } VolumeModel volumeModel = new VolumeModel(); String volumeName = "dataDisk"+System.currentTimeMillis(); volumeModel.setName(volumeName); volumeModel.setAzName(azName); volumeModel.setVolumeType(deviceParams.get("VOLUME_TYPE")); volumeModel.setDiskSize(dataDisk); //volumeModel.setIsShare("H".equals(hostType) ? "false" : "true"); String share = deviceParams.get("IS_SHARE"); if(share != null && "true".equals(share)) { isShare = true; } volumeModel.setIsShare(share); volumeId = UUIDGenerator.getUUID(); volumeIaasUuid = OpenstackPowerVcServiceFactory.getVolumeServiceInstance(openstackIp, domainName, token).createVolume(projectId, volumeModel, PVOperation.CREATE_DATA_VOLUME); logger.debug(logCommon + "完成,开始进行数据处理..."); CmDeviceDAO cmDeviceDAO = (CmDeviceDAO) WebApplicationManager.getBean("cmDeviceDAO"); VolumeDetailVo volumeVo = new VolumeDetailVo(); volumeVo.setVolumeId(volumeId); volumeVo.setAzName(azName); String myProjectId = deviceParams.get("MY_PROJECT_ID"); volumeVo.setProjectId(myProjectId); volumeVo.setVolumeName(volumeName); volumeVo.setVolumeSize(dataDisk); volumeVo.setVolumeType(deviceParams.get("VOLUME_TYPE")); volumeVo.setIsShareVol(share); volumeVo.setSysVolumeVal("1"); volumeVo.setIaasUuid(volumeIaasUuid); cmDeviceDAO.saveOpenstackVolume(volumeVo); logger.debug(logCommon + "结束..."); } setHandleResultParam(deviceIdList.get(i), "DATA_VOLUME_ID", volumeIaasUuid); setHandleResultParam(deviceIdList.get(i), "MY_DATA_VOLUME_ID", volumeId); } // 保存流程参数 this.saveParam(reqMap); } }
package com.example.dagger2mvpdemo.entity; import java.util.List; /** * @author 时志邦 * @Description: ${TODO}(用一句话描述该文件做什么) */ public class User { /** * newsID : A921721650580 * title : 得瑟得瑟4 * imageUrl : http://www.infoacq.com/files/images/436760688950/images/201802/20180225102.jpg * type : 1 */ public String newsID; public String title; public String imageUrl; public int type; }
package com.pibs.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.pibs.constant.ActionConstant; import com.pibs.constant.MapConstant; import com.pibs.constant.MiscConstant; import com.pibs.constant.ModuleConstant; import com.pibs.constant.ParamConstant; import com.pibs.form.BillingDiscountFormBean; import com.pibs.model.Discount; import com.pibs.model.BillingDiscount; import com.pibs.model.User; import com.pibs.service.ServiceManager; import com.pibs.service.ServiceManagerImpl; import com.pibs.util.PIBSUtils; public class BillingDiscountAction extends Action { private final static Logger logger = Logger.getLogger(BillingDiscountAction.class); @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO Auto-generated method stub BillingDiscountFormBean formBean = (BillingDiscountFormBean) form; String forwardAction = ActionConstant.NONE; String command = request.getParameter("command"); //session expired checking if (request.getSession().getAttribute(MiscConstant.USER_SESSION) == null) { forwardAction = ActionConstant.SHOW_AJAX_EXPIRED; } else { if (command!=null) { int module = ModuleConstant.BILLING_DISCOUNT; if (command.equalsIgnoreCase(ParamConstant.AJAX_GO_TO_CHILD)) { //fetch the data int patientSystemCaseId = Integer.parseInt(request.getParameter("patientCaseSystemId")); BillingDiscount model = new BillingDiscount(); model.setPatientCaseSystemId(patientSystemCaseId); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.SEARCHBY); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { @SuppressWarnings("unchecked") List<BillingDiscount> rsList = (ArrayList<BillingDiscount>) resultMap.get(MapConstant.CLASS_LIST); formBean.populateBillingDiscountEntityList(rsList); } formBean.setTransactionStatus(false); formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_RESET); forwardAction = ActionConstant.SHOW_AJAX_GO_TO_CHILD; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_GO_TO_CHILD_SEARCH)) { formBean.setPatientCaseSystemId(Integer.parseInt(request.getParameter("patientCaseSystemId"))); formBean.setTransactionStatus(false); formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_RESET); forwardAction = ActionConstant.SHOW_AJAX_GO_TO_CHILD_SEARCH; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_SEARCH)) { //get all the records from DB int page = 1; if(request.getParameter("page") != null) { page = Integer.parseInt(request.getParameter("page")); } int offset = (page-1) * MiscConstant.RECORDS_PER_PAGE; String category = null; if(request.getParameter("category") != null) { category=(String) request.getParameter("category"); formBean.setCategory(category); if (category.equals("filter")) { category = ActionConstant.SEARCHBY; } else { category = ActionConstant.SEARCHALL; } } String criteria = null; if(formBean.getCriteria()!=null && formBean.getCriteria().trim().length() > 0) { criteria = formBean.getCriteria(); } HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, ModuleConstant.DISCOUNT); dataMap.put(MapConstant.ACTION, category); dataMap.put(MapConstant.SEARCH_CRITERIA, criteria); dataMap.put(MapConstant.PAGINATION_LIMIT, MiscConstant.RECORDS_PER_PAGE); dataMap.put(MapConstant.PAGINATION_OFFSET, offset); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { @SuppressWarnings("unchecked") List<Discount> qryList = (List<Discount>) resultMap.get(MapConstant.CLASS_LIST); formBean.setModelList(qryList); int totalNoOfRecords = (int) resultMap.get(MapConstant.PAGINATION_TOTALRECORDS); int noOfPages = (int) Math.ceil(totalNoOfRecords * 1.0 / MiscConstant.RECORDS_PER_PAGE); formBean.setNoOfPages(noOfPages); formBean.setCurrentPage(page); } else { formBean.setModelList(null); formBean.setNoOfPages(0); formBean.setCurrentPage(0); } forwardAction = ActionConstant.SHOW_AJAX_TABLE; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_ADD)) { formBean.getDiscountDetails(request);//fetch the details formBean.setTransactionStatus(false); formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_RESET); forwardAction = ActionConstant.SHOW_AJAX_ADD; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_EDIT)) { //fetch the data int id = Integer.parseInt(request.getParameter("id")); BillingDiscount model = new BillingDiscount(); model.setId(id); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.GET_DATA); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { model = (BillingDiscount) resultMap.get(MapConstant.CLASS_DATA); formBean.populateFormBean(model); } formBean.setTransactionStatus(false); formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_RESET); forwardAction = ActionConstant.SHOW_AJAX_EDIT; } else if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE) || command.equalsIgnoreCase(ParamConstant.AJAX_UPDATE)) { //populateModel BillingDiscount model = (BillingDiscount) formBean.populateModel(formBean); User user = (User) request.getSession().getAttribute(MiscConstant.USER_SESSION); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.USER_SESSION_DATA, user); if (command.equalsIgnoreCase(ParamConstant.AJAX_SAVE)) { dataMap.put(MapConstant.ACTION, ActionConstant.SAVE); } else { dataMap.put(MapConstant.ACTION, ActionConstant.UPDATE); } ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { //check resultmap action status boolean transactionStatus = (boolean) resultMap.get(MapConstant.TRANSACTION_STATUS); formBean.setTransactionStatus(transactionStatus); if (transactionStatus) { //show success page //add confirmation message if (dataMap.get(MapConstant.ACTION).equals(ActionConstant.SAVE)) { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_SAVED); PIBSUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_SAVED+" - "+module); //logger.info(MiscConstant.TRANS_MESSSAGE_SAVED); }else { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_UPDATED); PIBSUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_UPDATED+" - "+module); //logger.info(MiscConstant.TRANS_MESSSAGE_UPDATED); } //update the list in the form service = null; resultMap = null; model = new BillingDiscount(); model.setPatientCaseSystemId(formBean.getPatientCaseSystemId()); dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.SEARCHBY); service = new ServiceManagerImpl(); resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { @SuppressWarnings("unchecked") List<BillingDiscount> rsList = (ArrayList<BillingDiscount>) resultMap.get(MapConstant.CLASS_LIST); formBean.populateBillingDiscountEntityList(rsList); } forwardAction = ActionConstant.AJAX_SUCCESS; } else { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_ERROR); //logger.info(MiscConstant.TRANS_MESSSAGE_ERROR); PIBSUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_ERROR+" - "+module); forwardAction = ActionConstant.AJAX_FAILED; } } } else if (command.equalsIgnoreCase(ParamConstant.AJAX_DELETE)) { //fetch the data int id = Integer.parseInt(request.getParameter("id")); User user = (User) request.getSession().getAttribute(MiscConstant.USER_SESSION); BillingDiscount model = new BillingDiscount(); model.setId(id); HashMap<String,Object> dataMap = new HashMap<String, Object>(); dataMap.put(MapConstant.MODULE, module); dataMap.put(MapConstant.CLASS_DATA, model); dataMap.put(MapConstant.ACTION, ActionConstant.DELETE); dataMap.put(MapConstant.USER_SESSION_DATA, user); ServiceManager service = new ServiceManagerImpl(); Map<String, Object> resultMap = service.executeRequest(dataMap); if (resultMap!=null && !resultMap.isEmpty()) { //check resultmap action status boolean transactionStatus = (boolean) resultMap.get(MapConstant.TRANSACTION_STATUS); formBean.setTransactionStatus(transactionStatus); if (transactionStatus) { //show success page //add confirmation message formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_DELETED); //logger.info(MiscConstant.TRANS_MESSSAGE_DELETED); PIBSUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_DELETED+" - "+module); forwardAction = ActionConstant.AJAX_SUCCESS; } else { formBean.setTransactionMessage(MiscConstant.TRANS_MESSSAGE_ERROR); //logger.info(MiscConstant.TRANS_MESSSAGE_ERROR); PIBSUtils.writeLogInfo(logger, MiscConstant.TRANS_MESSSAGE_ERROR+" - "+module); forwardAction = ActionConstant.AJAX_FAILED; } } } } else { //show main screen forwardAction = ActionConstant.SHOW_AJAX_MAIN; } } return mapping.findForward(forwardAction); } }
package org.vaadin.peholmst.samples.springsecurity.hybrid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; import org.springframework.security.core.context.SecurityContextHolder; import javax.sql.DataSource; @SpringBootApplication(exclude = { SecurityAutoConfiguration.class }) public class HybridSecuritySampleApplication { @Configuration @EnableGlobalMethodSecurity(securedEnabled = true) public static class SecurityConfiguration extends GlobalMethodSecurityConfiguration { @Autowired DataSource dataSource; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.jdbcAuthentication().dataSource(dataSource) .usersByUsernameQuery( "select username,password, enabled from users where username=?") .authoritiesByUsernameQuery( "select username, role from user_roles where username=?"); } @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return authenticationManager(); } @Bean public DriverManagerDataSource dataSource(){ DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("com.mysql.jdbc.Driver");; ds.setUrl("jdbc:mysql://localhost/analyzer"); ds.setUsername("analyzer"); ds.setPassword("analyzerpassword"); return ds; } static { // Use a custom SecurityContextHolderStrategy SecurityContextHolder.setStrategyName(VaadinSessionSecurityContextHolderStrategy.class.getName()); } } public static void main(String[] args) { SpringApplication.run(HybridSecuritySampleApplication.class, args); } }
package com.limegroup.gnutella.gui.options.panes; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JRadioButton; import javax.swing.JTextField; import org.gudy.azureus2.core3.config.COConfigurationManager; import org.limewire.i18n.I18nMarker; import com.limegroup.gnutella.gui.BoxPanel; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.gui.LabeledComponent; import com.limegroup.gnutella.gui.SizedTextField; import com.limegroup.gnutella.gui.SizedWholeNumberField; import com.limegroup.gnutella.gui.WholeNumberField; import com.limegroup.gnutella.gui.GUIUtils.SizePolicy; import com.limegroup.gnutella.settings.ConnectionSettings; /** * This class defines the panel in the options window that allows the user to * select a proxy to use. */ public final class ProxyPaneItem extends AbstractPaneItem { public final static String TITLE = I18n.tr("Proxy Options"); public final static String LABEL = I18n.tr("Configure Proxy Options for FrostWire."); /** * Constant for the key of the locale-specific <tt>String</tt> for the * label on the RadioButtons. */ private final String NO_PROXY_LABEL_KEY = I18nMarker.marktr("No Proxy"); private final String SOCKS4_PROXY_LABEL_KEY = I18nMarker.marktr("Socks v4"); private final String SOCKS5_PROXY_LABEL_KEY = I18nMarker.marktr("Socks v5"); private final String HTTP_PROXY_LABEL_KEY = I18nMarker.marktr("HTTP"); /** * Constant for the key of the locale-specific <tt>String</tt> for the * label on the proxy host field. */ private final String PROXY_HOST_LABEL_KEY = I18nMarker.marktr("Proxy:"); /** * Constant for the key of the locale-specific <tt>String</tt> for the * label on the port text field. */ private final String PROXY_PORT_LABEL_KEY = I18nMarker.marktr("Port:"); /** * Constant handle to the check box that enables or disables this feature. */ private final ButtonGroup BUTTONS = new ButtonGroup(); private final JRadioButton NO_PROXY_BUTTON = new JRadioButton(I18n.tr(NO_PROXY_LABEL_KEY)); private final JRadioButton SOCKS4_PROXY_BUTTON = new JRadioButton(I18n.tr(SOCKS4_PROXY_LABEL_KEY)); private final JRadioButton SOCKS5_PROXY_BUTTON = new JRadioButton(I18n.tr(SOCKS5_PROXY_LABEL_KEY)); private final JRadioButton HTTP_PROXY_BUTTON = new JRadioButton(I18n.tr(HTTP_PROXY_LABEL_KEY)); /** * Constant <tt>JTextField</tt> instance that holds the ip address to use * as a proxy. */ private final JTextField PROXY_HOST_FIELD = new SizedTextField(12, SizePolicy.RESTRICT_HEIGHT); /** * Constant <tt>WholeNumberField</tt> instance that holds the port of the * proxy. */ private final WholeNumberField PROXY_PORT_FIELD = new SizedWholeNumberField(8080, 5, SizePolicy.RESTRICT_BOTH); /** * The constructor constructs all of the elements of this * <tt>AbstractPaneItem</tt>. * * @param key the key for this <tt>AbstractPaneItem</tt> that the * superclass uses to generate locale-specific keys */ public ProxyPaneItem() { super(TITLE, LABEL); BUTTONS.add(NO_PROXY_BUTTON); BUTTONS.add(SOCKS4_PROXY_BUTTON); BUTTONS.add(SOCKS5_PROXY_BUTTON); BUTTONS.add(HTTP_PROXY_BUTTON); NO_PROXY_BUTTON.addItemListener(new LocalProxyListener()); add(NO_PROXY_BUTTON); add(SOCKS4_PROXY_BUTTON); add(SOCKS5_PROXY_BUTTON); add(HTTP_PROXY_BUTTON); add(getHorizontalSeparator()); BoxPanel panel = new BoxPanel(BoxPanel.X_AXIS); LabeledComponent comp = new LabeledComponent(PROXY_HOST_LABEL_KEY, PROXY_HOST_FIELD, LabeledComponent.NO_GLUE, LabeledComponent.LEFT); panel.add(comp.getComponent()); panel.addHorizontalComponentGap(); comp = new LabeledComponent(PROXY_PORT_LABEL_KEY, PROXY_PORT_FIELD, LabeledComponent.NO_GLUE, LabeledComponent.LEFT); panel.add(comp.getComponent()); add(panel); } /** * Defines the abstract method in <tt>AbstractPaneItem</tt>. * <p> * * Sets the options for the fields in this <tt>PaneItem</tt> when the * window is shown. */ public void initOptions() { String proxy = ConnectionSettings.PROXY_HOST.getValue(); int proxyPort = ConnectionSettings.PROXY_PORT.getValue(); int connectionMethod = ConnectionSettings.CONNECTION_METHOD.getValue(); PROXY_PORT_FIELD.setValue(proxyPort); NO_PROXY_BUTTON.setSelected( connectionMethod == ConnectionSettings.C_NO_PROXY); SOCKS4_PROXY_BUTTON.setSelected( connectionMethod == ConnectionSettings.C_SOCKS4_PROXY); SOCKS5_PROXY_BUTTON.setSelected( connectionMethod == ConnectionSettings.C_SOCKS5_PROXY); HTTP_PROXY_BUTTON.setSelected( connectionMethod == ConnectionSettings.C_HTTP_PROXY); PROXY_HOST_FIELD.setText(proxy); updateState(); } /** * Defines the abstract method in <tt>AbstractPaneItem</tt>. * <p> * * Applies the options currently set in this window, displaying an error * message to the user if a setting could not be applied. * * @throws IOException * if the options could not be applied for some reason */ public boolean applyOptions() throws IOException { int connectionMethod = ConnectionSettings.C_NO_PROXY; if (SOCKS4_PROXY_BUTTON.isSelected()) { connectionMethod = ConnectionSettings.C_SOCKS4_PROXY; } else if (SOCKS5_PROXY_BUTTON.isSelected()) { connectionMethod = ConnectionSettings.C_SOCKS5_PROXY; } else if (HTTP_PROXY_BUTTON.isSelected()) { connectionMethod = ConnectionSettings.C_HTTP_PROXY; } final int proxyPort = PROXY_PORT_FIELD.getValue(); final String proxyHost = PROXY_HOST_FIELD.getText(); ConnectionSettings.PROXY_PORT.setValue(proxyPort); ConnectionSettings.CONNECTION_METHOD.setValue(connectionMethod); ConnectionSettings.PROXY_HOST.setValue(proxyHost); // put proxy configuration in vuze options COConfigurationManager.setParameter("Enable.Proxy", connectionMethod != ConnectionSettings.C_NO_PROXY); COConfigurationManager.setParameter("Enable.SOCKS", connectionMethod == ConnectionSettings.C_SOCKS4_PROXY || connectionMethod == ConnectionSettings.C_SOCKS5_PROXY); COConfigurationManager.setParameter("Proxy.Host", proxyHost); COConfigurationManager.setParameter("Proxy.Port", String.valueOf(proxyPort)); COConfigurationManager.save(); return false; } public boolean isDirty() { if(ConnectionSettings.PROXY_PORT.getValue() != PROXY_PORT_FIELD.getValue()) return true; if(!ConnectionSettings.PROXY_HOST.getValue().equals(PROXY_HOST_FIELD.getText())) return true; switch(ConnectionSettings.CONNECTION_METHOD.getValue()) { case ConnectionSettings.C_SOCKS4_PROXY: return !SOCKS4_PROXY_BUTTON.isSelected(); case ConnectionSettings.C_SOCKS5_PROXY: return !SOCKS5_PROXY_BUTTON.isSelected(); case ConnectionSettings.C_HTTP_PROXY: return !HTTP_PROXY_BUTTON.isSelected(); case ConnectionSettings.C_NO_PROXY: return !NO_PROXY_BUTTON.isSelected(); default: return true; } } private void updateState() { PROXY_HOST_FIELD.setEditable(!NO_PROXY_BUTTON.isSelected()); PROXY_PORT_FIELD.setEditable(!NO_PROXY_BUTTON.isSelected()); PROXY_HOST_FIELD.setEnabled(!NO_PROXY_BUTTON.isSelected()); PROXY_PORT_FIELD.setEnabled(!NO_PROXY_BUTTON.isSelected()); } /** * Listener class that responds to the checking and the unchecking of the * RadioButton specifying whether or not to use a proxy configuration. It * makes the other fields editable or not editable depending on the state * of the JRadioButton. */ private class LocalProxyListener implements ItemListener { public void itemStateChanged(ItemEvent e) { updateState(); } } }