public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) { boolean isValid = false; if(value==null){ //当状态为空时使用默认值 return true; } for(int i=0;i<values.length;i++){ if(values[i].equals(String.valueOf(value))){ isValid = true; break; } } return isValid; }
public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) { boolean isValid = false; for(int i=0;i<values.length;i++){ if(values[i].equals(String.valueOf(value))){ isValid = true; break; } } return isValid; }
private String processTag(final String s) { // ending tags Matcher m = P_END_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); if (allowed(name)) { if (!inArray(name, vSelfClosingTags)) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) - 1); return "</" + name + ">"; } } } } // starting tags m = P_START_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); final String body = m.group(2); String ending = m.group(3); //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); if (allowed(name)) { String params = ""; final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); final List<String> paramNames = new ArrayList<String>(); final List<String> paramValues = new ArrayList<String>(); while (m2.find()) { paramNames.add(m2.group(1)); //([a-z0-9]+) paramValues.add(m2.group(3)); //(.*?) } while (m3.find()) { paramNames.add(m3.group(1)); //([a-z0-9]+) paramValues.add(m3.group(3)); //([^\"\\s']+) } String paramName, paramValue; for (int ii = 0; ii < paramNames.size(); ii++) { paramName = paramNames.get(ii).toLowerCase(); paramValue = paramValues.get(ii); // debug( "paramName='" + paramName + "'" ); // debug( "paramValue='" + paramValue + "'" ); // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); if (allowedAttribute(name, paramName)) { if (inArray(paramName, vProtocolAtts)) { paramValue = processParamProtocol(paramValue); } params += " " + paramName + "=\"" + paramValue + "\""; } } if (inArray(name, vSelfClosingTags)) { ending = " /"; } if (inArray(name, vNeedClosingTags)) { ending = ""; } if (ending == null || ending.length() < 1) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) + 1); } else { vTagCounts.put(name, 1); } } else { ending = " /"; } return "<" + name + params + ending + ">"; } else { return ""; } } // comments m = P_COMMENT.matcher(s); if (!stripComment && m.find()) { return "<" + m.group() + ">"; } return ""; }
private String processTag(final String s) { // ending tags Matcher m = P_END_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); if (allowed(name)) { if (!inArray(name, vSelfClosingTags)) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) - 1); return "</" + name + ">"; } } } } // starting tags m = P_START_TAG.matcher(s); if (m.find()) { final String name = m.group(1).toLowerCase(); final String body = m.group(2); String ending = m.group(3); //debug( "in a starting tag, name='" + name + "'; body='" + body + "'; ending='" + ending + "'" ); if (allowed(name)) { String params = ""; final Matcher m2 = P_QUOTED_ATTRIBUTES.matcher(body); final Matcher m3 = P_UNQUOTED_ATTRIBUTES.matcher(body); final List<String> paramNames = new ArrayList<String>(); final List<String> paramValues = new ArrayList<String>(); while (m2.find()) { paramNames.add(m2.group(1)); //([a-z0-9]+) paramValues.add(m2.group(3)); //(.*?) } while (m3.find()) { paramNames.add(m3.group(1)); //([a-z0-9]+) paramValues.add(m3.group(3)); //([^\"\\s']+) } String paramName, paramValue; for (int ii = 0; ii < paramNames.size(); ii++) { paramName = paramNames.get(ii).toLowerCase(); paramValue = paramValues.get(ii); // debug( "paramName='" + paramName + "'" ); // debug( "paramValue='" + paramValue + "'" ); // debug( "allowed? " + vAllowed.get( name ).contains( paramName ) ); if (allowedAttribute(name, paramName)) { if (inArray(paramName, vProtocolAtts)) { paramValue = processParamProtocol(paramValue); } params += " " + paramName + "=\"" + paramValue + "\""; } } if (inArray(name, vSelfClosingTags)) { ending = " /"; } if (inArray(name, vNeedClosingTags)) { ending = ""; } if (ending == null || ending.length() < 1) { if (vTagCounts.containsKey(name)) { vTagCounts.put(name, vTagCounts.get(name) + 1); } else { vTagCounts.put(name, 1); } } else { ending = " /"; } return "<" + name + params + ending + ">"; } else { return ""; } } // comments m = P_COMMENT.matcher(s); if (!stripComment && m.find()) { return "<" + m.group() + ">"; } return ""; }
public HTMLFilter() { vAllowed = new HashMap<>(); final ArrayList<String> a_atts = new ArrayList<String>(); a_atts.add("href"); a_atts.add("target"); vAllowed.put("a", a_atts); final ArrayList<String> img_atts = new ArrayList<String>(); img_atts.add("src"); img_atts.add("width"); img_atts.add("height"); img_atts.add("alt"); vAllowed.put("img", img_atts); final ArrayList<String> no_atts = new ArrayList<String>(); vAllowed.put("b", no_atts); vAllowed.put("strong", no_atts); vAllowed.put("i", no_atts); vAllowed.put("em", no_atts); vSelfClosingTags = new String[]{"img"}; vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; vDisallowed = new String[]{}; vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. vProtocolAtts = new String[]{"src", "href"}; vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; stripComment = true; encodeQuotes = true; alwaysMakeTags = true; }
public HTMLFilter() { vAllowed = new HashMap<>(); final ArrayList<String> a_atts = new ArrayList<String>(); a_atts.add("href"); a_atts.add("target"); vAllowed.put("a", a_atts); final ArrayList<String> img_atts = new ArrayList<String>(); img_atts.add("src"); img_atts.add("width"); img_atts.add("height"); img_atts.add("alt"); vAllowed.put("img", img_atts); final ArrayList<String> no_atts = new ArrayList<String>(); vAllowed.put("b", no_atts); vAllowed.put("strong", no_atts); vAllowed.put("i", no_atts); vAllowed.put("em", no_atts); vSelfClosingTags = new String[]{"img"}; vNeedClosingTags = new String[]{"a", "b", "strong", "i", "em"}; vDisallowed = new String[]{}; vAllowedProtocols = new String[]{"http", "mailto", "https"}; // no ftp. vProtocolAtts = new String[]{"src", "href"}; vRemoveBlanks = new String[]{"a", "b", "strong", "i", "em"}; vAllowedEntities = new String[]{"amp", "gt", "lt", "quot"}; stripComment = true; encodeQuotes = true; alwaysMakeTags = true; }
private String decodeEntities(String s) { StringBuffer buf = new StringBuffer(); Matcher m = P_ENTITY.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.decode(match).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENTITY_UNICODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENCODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); s = validateEntities(s); return s; }
private String decodeEntities(String s) { StringBuffer buf = new StringBuffer(); Matcher m = P_ENTITY.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.decode(match).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENTITY_UNICODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); buf = new StringBuffer(); m = P_ENCODE.matcher(s); while (m.find()) { final String match = m.group(1); final int decimal = Integer.valueOf(match, 16).intValue(); m.appendReplacement(buf, Matcher.quoteReplacement(chr(decimal))); } m.appendTail(buf); s = buf.toString(); s = validateEntities(s); return s; }
public HTMLFilter(final Map<String,Object> conf) { assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed")); vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); vDisallowed = (String[]) conf.get("vDisallowed"); vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); vProtocolAtts = (String[]) conf.get("vProtocolAtts"); vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); vAllowedEntities = (String[]) conf.get("vAllowedEntities"); stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; }
public HTMLFilter(final Map<String,Object> conf) { assert conf.containsKey("vAllowed") : "configuration requires vAllowed"; assert conf.containsKey("vSelfClosingTags") : "configuration requires vSelfClosingTags"; assert conf.containsKey("vNeedClosingTags") : "configuration requires vNeedClosingTags"; assert conf.containsKey("vDisallowed") : "configuration requires vDisallowed"; assert conf.containsKey("vAllowedProtocols") : "configuration requires vAllowedProtocols"; assert conf.containsKey("vProtocolAtts") : "configuration requires vProtocolAtts"; assert conf.containsKey("vRemoveBlanks") : "configuration requires vRemoveBlanks"; assert conf.containsKey("vAllowedEntities") : "configuration requires vAllowedEntities"; vAllowed = Collections.unmodifiableMap((HashMap<String, List<String>>) conf.get("vAllowed")); vSelfClosingTags = (String[]) conf.get("vSelfClosingTags"); vNeedClosingTags = (String[]) conf.get("vNeedClosingTags"); vDisallowed = (String[]) conf.get("vDisallowed"); vAllowedProtocols = (String[]) conf.get("vAllowedProtocols"); vProtocolAtts = (String[]) conf.get("vProtocolAtts"); vRemoveBlanks = (String[]) conf.get("vRemoveBlanks"); vAllowedEntities = (String[]) conf.get("vAllowedEntities"); stripComment = conf.containsKey("stripComment") ? (Boolean) conf.get("stripComment") : true; encodeQuotes = conf.containsKey("encodeQuotes") ? (Boolean) conf.get("encodeQuotes") : true; alwaysMakeTags = conf.containsKey("alwaysMakeTags") ? (Boolean) conf.get("alwaysMakeTags") : true; }
public String filter(final String input) { reset(); String s = input; debug("************************************************"); debug(" INPUT: " + input); s = escapeComments(s); debug(" escapeComments: " + s); s = balanceHTML(s); debug(" balanceHTML: " + s); s = checkTags(s); debug(" checkTags: " + s); s = processRemoveBlanks(s); debug("processRemoveBlanks: " + s); s = validateEntities(s); debug(" validateEntites: " + s); debug("************************************************\n\n"); return s; }
public String filter(final String input) { reset(); String s = input; debug("************************************************"); debug(" INPUT: " + input); s = escapeComments(s); debug(" escapeComments: " + s); s = balanceHTML(s); debug(" balanceHTML: " + s); s = checkTags(s); debug(" checkTags: " + s); s = processRemoveBlanks(s); debug("processRemoveBlanks: " + s); s = validateEntities(s); debug(" validateEntites: " + s); debug("************************************************\n\n"); return s; }
public static String sqlInject(String str){ if(StringUtils.isBlank(str)){ return null; } //去掉'|"|;|\字符 str = StringUtils.replace(str, "'", ""); str = StringUtils.replace(str, "\"", ""); str = StringUtils.replace(str, ";", ""); str = StringUtils.replace(str, "\\", ""); //转换成小写 str = str.toLowerCase(); //非法字符 String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; //判断是否包含非法字符 for(String keyword : keywords){ if(str.indexOf(keyword) != -1){ throw new RRException("包含非法字符"); } } return str; }
public static String sqlInject(String str){ if(StringUtils.isBlank(str)){ return null; } //去掉'|"|;|\字符 str = StringUtils.replace(str, "'", ""); str = StringUtils.replace(str, "\"", ""); str = StringUtils.replace(str, ";", ""); str = StringUtils.replace(str, "\\", ""); //转换成小写 str = str.toLowerCase(); //非法字符 String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; //判断是否包含非法字符 for(String keyword : keywords){ if(str.indexOf(keyword) != -1){ throw new RRException("包含非法字符"); } } return str; }
private String encodeQuotes(final String s){ if(encodeQuotes){ StringBuffer buf = new StringBuffer(); Matcher m = P_VALID_QUOTES.matcher(s); while (m.find()) { final String one = m.group(1); //(>|^) final String two = m.group(2); //([^<]+?) final String three = m.group(3); //(<|$) m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); } m.appendTail(buf); return buf.toString(); }else{ return s; } }
private String encodeQuotes(final String s){ if(encodeQuotes){ StringBuffer buf = new StringBuffer(); Matcher m = P_VALID_QUOTES.matcher(s); while (m.find()) { final String one = m.group(1); //(>|^) final String two = m.group(2); //([^<]+?) final String three = m.group(3); //(<|$) m.appendReplacement(buf, Matcher.quoteReplacement(one + regexReplace(P_QUOTE, """, two) + three)); } m.appendTail(buf); return buf.toString(); }else{ return s; } }
private String checkTags(String s) { Matcher m = P_TAGS.matcher(s); final StringBuffer buf = new StringBuffer(); while (m.find()) { String replaceStr = m.group(1); replaceStr = processTag(replaceStr); m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); } m.appendTail(buf); s = buf.toString(); // these get tallied in processTag // (remember to reset before subsequent calls to filter method) for (String key : vTagCounts.keySet()) { for (int ii = 0; ii < vTagCounts.get(key); ii++) { s += "</" + key + ">"; } } return s; }
private String checkTags(String s) { Matcher m = P_TAGS.matcher(s); final StringBuffer buf = new StringBuffer(); while (m.find()) { String replaceStr = m.group(1); replaceStr = processTag(replaceStr); m.appendReplacement(buf, Matcher.quoteReplacement(replaceStr)); } m.appendTail(buf); s = buf.toString(); // these get tallied in processTag // (remember to reset before subsequent calls to filter method) for (String key : vTagCounts.keySet()) { for (int ii = 0; ii < vTagCounts.get(key); ii++) { s += "</" + key + ">"; } } return s; }
private String processParamProtocol(String s) { s = decodeEntities(s); final Matcher m = P_PROTOCOL.matcher(s); if (m.find()) { final String protocol = m.group(1); if (!inArray(protocol, vAllowedProtocols)) { // bad protocol, turn into local anchor link instead s = "#" + s.substring(protocol.length() + 1, s.length()); if (s.startsWith("#//")) { s = "#" + s.substring(3, s.length()); } } } return s; }
private String processParamProtocol(String s) { s = decodeEntities(s); final Matcher m = P_PROTOCOL.matcher(s); if (m.find()) { final String protocol = m.group(1); if (!inArray(protocol, vAllowedProtocols)) { // bad protocol, turn into local anchor link instead s = "#" + s.substring(protocol.length() + 1, s.length()); if (s.startsWith("#//")) { s = "#" + s.substring(3, s.length()); } } } return s; }
private String processRemoveBlanks(final String s) { String result = s; for (String tag : vRemoveBlanks) { if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){ P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">")); } result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){ P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); } result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); } return result; }
private String processRemoveBlanks(final String s) { String result = s; for (String tag : vRemoveBlanks) { if(!P_REMOVE_PAIR_BLANKS.containsKey(tag)){ P_REMOVE_PAIR_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?></" + tag + ">")); } result = regexReplace(P_REMOVE_PAIR_BLANKS.get(tag), "", result); if(!P_REMOVE_SELF_BLANKS.containsKey(tag)){ P_REMOVE_SELF_BLANKS.putIfAbsent(tag, Pattern.compile("<" + tag + "(\\s[^>]*)?/>")); } result = regexReplace(P_REMOVE_SELF_BLANKS.get(tag), "", result); } return result; }
private String balanceHTML(String s) { if (alwaysMakeTags) { // // try and form html // s = regexReplace(P_END_ARROW, "", s); s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s); } else { // // escape stray brackets // s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); // // the last regexp causes '<>' entities to appear // (we need to do a lookahead assertion so that the last bracket can // be used in the next pass of the regexp) // s = regexReplace(P_BOTH_ARROWS, "", s); } return s; }
private String balanceHTML(String s) { if (alwaysMakeTags) { // // try and form html // s = regexReplace(P_END_ARROW, "", s); s = regexReplace(P_BODY_TO_END, "<$1>", s); s = regexReplace(P_XML_CONTENT, "$1<$2", s); } else { // // escape stray brackets // s = regexReplace(P_STRAY_LEFT_ARROW, "<$1", s); s = regexReplace(P_STRAY_RIGHT_ARROW, "$1$2><", s); // // the last regexp causes '<>' entities to appear // (we need to do a lookahead assertion so that the last bracket can // be used in the next pass of the regexp) // s = regexReplace(P_BOTH_ARROWS, "", s); } return s; }
private String validateEntities(final String s) { StringBuffer buf = new StringBuffer(); // validate entities throughout the string Matcher m = P_VALID_ENTITIES.matcher(s); while (m.find()) { final String one = m.group(1); //([^&;]*) final String two = m.group(2); //(?=(;|&|$)) m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); } m.appendTail(buf); return encodeQuotes(buf.toString()); }
private String validateEntities(final String s) { StringBuffer buf = new StringBuffer(); // validate entities throughout the string Matcher m = P_VALID_ENTITIES.matcher(s); while (m.find()) { final String one = m.group(1); //([^&;]*) final String two = m.group(2); //(?=(;|&|$)) m.appendReplacement(buf, Matcher.quoteReplacement(checkEntity(one, two))); } m.appendTail(buf); return encodeQuotes(buf.toString()); }
private String escapeComments(final String s) { final Matcher m = P_COMMENTS.matcher(s); final StringBuffer buf = new StringBuffer(); if (m.find()) { final String match = m.group(1); //(.*?) m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->")); } m.appendTail(buf); return buf.toString(); }
private String escapeComments(final String s) { final Matcher m = P_COMMENTS.matcher(s); final StringBuffer buf = new StringBuffer(); if (m.find()) { final String match = m.group(1); //(.*?) m.appendReplacement(buf, Matcher.quoteReplacement("<!--" + htmlSpecialChars(match) + "-->")); } m.appendTail(buf); return buf.toString(); }
private static Map<String,Cookie> readCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; }
private static Map<String,Cookie> readCookieMap(HttpServletRequest request){ Map<String,Cookie> cookieMap = new HashMap<>(); Cookie[] cookies = request.getCookies(); if(null!=cookies){ for(Cookie cookie : cookies){ cookieMap.put(cookie.getName(), cookie); } } return cookieMap; }
public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); }
public static String encode(byte[] from) { StringBuilder to = new StringBuilder((int) ((double) from.length * 1.34D) + 3); int num = 0; char currentByte = 0; int i; for (i = 0; i < from.length; ++i) { for (num %= 8; num < 8; num += 6) { switch (num) { case 0: currentByte = (char) (from[i] & lead6byte); currentByte = (char) (currentByte >>> 2); case 1: case 3: case 5: default: break; case 2: currentByte = (char) (from[i] & last6byte); break; case 4: currentByte = (char) (from[i] & last4byte); currentByte = (char) (currentByte << 2); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead2byte) >>> 6); } break; case 6: currentByte = (char) (from[i] & last2byte); currentByte = (char) (currentByte << 4); if (i + 1 < from.length) { currentByte = (char) (currentByte | (from[i + 1] & lead4byte) >>> 4); } } to.append(encodeTable[currentByte]); } } if (to.length() % 4 != 0) { for (i = 4 - to.length() % 4; i > 0; --i) { to.append("="); } } return to.toString(); }
public static ExecutorRouteStrategyEnum match(String name, ExecutorRouteStrategyEnum defaultItem){ if (name != null) { for (ExecutorRouteStrategyEnum item: ExecutorRouteStrategyEnum.values()) { if (item.name().equals(name)) { return item; } } } return defaultItem; }
public static ExecutorBlockStrategyEnum match(String name, ExecutorBlockStrategyEnum defaultItem) { if (name != null) { for (ExecutorBlockStrategyEnum item:ExecutorBlockStrategyEnum.values()) { if (item.name().equals(name)) { return item; } } } return defaultItem; }
protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; }
protected static long getDatacenterId(long maxDatacenterId) { long id = 0L; try { InetAddress ip = InetAddress.getLocalHost(); NetworkInterface network = NetworkInterface.getByInetAddress(ip); if (network == null) { id = 1L; } else { byte[] mac = network.getHardwareAddress(); id = ((0x000000FF & (long) mac[mac.length - 1]) | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6; id = id % (maxDatacenterId + 1); } } catch (Exception e) { System.out.println(" getDatacenterId: " + e.getMessage()); } return id; }
public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; }
public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; }
public SnowflakeIdWorker(long workerId, long dataCenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (dataCenterId > maxDataCenterId || dataCenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDataCenterId)); } this.workerId = workerId; this.dataCenterId = dataCenterId; }
public IdWorker(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; }
public IdWorkerUtils(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; }
public IdWorker(long workerId, long datacenterId) { if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; }
public synchronized long nextId() { long timestamp = timeGen(); //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果是同一时间生成的,则进行毫秒内序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒内序列溢出 if (sequence == 0) { //阻塞到下一个毫秒,获得新的时间戳 timestamp = tilNextMillis(lastTimestamp); } } //时间戳改变,毫秒内序列重置 else { sequence = 0L; } //上次生成ID的时间截 lastTimestamp = timestamp; //移位并通过或运算拼到一起组成64位的ID return ((timestamp - twepoch) << timestampLeftShift) | (dataCenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; }
public synchronized long nextId() { long timestamp = timeGen(); if (timestamp < lastTimestamp) { throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } if (lastTimestamp == timestamp) { // 当前毫秒内,则+1 sequence = (sequence + 1) & sequenceMask; if (sequence == 0) { // 当前毫秒内计数满了,则等待下一秒 timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0L; } lastTimestamp = timestamp; // ID偏移组合生成最终的ID,并返回ID long nextId = ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; return nextId; }
public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
public static String getIpAddress(HttpServletRequest request) { // 获取请求主机IP地址,如果通过代理进来,则透过防火墙获取真实IP地址 String ip = request.getHeader("X-Forwarded-For"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 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.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } } else if (ip.length() > 15) { String[] ips = ip.split(","); for (int index = 0; index < ips.length; index++) { String strIp = (String) ips[index]; if (!("unknown".equalsIgnoreCase(strIp))) { ip = strIp; break; } } } return ip; }
public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; }
public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; }
public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; }
public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; }
public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; }
public static boolean hasRole(String role) { if (!role.startsWith("ROLE_")) { role = "ROLE_" + role; } boolean hasRole = false; List<SimpleGrantedAuthority> list = getCurrentAuthorities(); for (SimpleGrantedAuthority s : list) { if (role.equals(s.getAuthority())) { hasRole = true; break; } } return hasRole; }
public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
public static Map<String, String> getHeaders(HttpServletRequest request) { Map<String, String> map = new LinkedHashMap<>(); Enumeration<String> enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; }
public void add_user_controller_should_return201_when_user_is_saved() throws Exception{ //given User user = new User(); user.setUserName(USER_NAME); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); String requestJson = objectWriter.writeValueAsString(user); //when when(userService.saveUser(new User())).thenReturn(user); //then mockMvc.perform(post("/users").content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.userName").value(USER_NAME)); verify(userService, times(1)).saveUser(any(User.class)); verifyNoMoreInteractions(userService); }
public void add_product_controller_should_return201_when_product_isSaved() throws Exception { //given Product product = new Product(); product.setProductName(PRODUCT_NAME); product.setCategory(PRODUCT_CATEGORY); ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); ObjectWriter objectWriter = mapper.writer().withDefaultPrettyPrinter(); String requestJson = objectWriter.writeValueAsString(product); //when when(productService.addProduct(new Product())).thenReturn(product); //then mockMvc.perform(post("/admin/products").content(requestJson).contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(status().isCreated()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.productName").value(PRODUCT_NAME)) .andExpect(jsonPath("$.category").value(PRODUCT_CATEGORY)); verify(productService, times(1)).addProduct(any(Product.class)); verifyNoMoreInteractions(productService); }
public void testGetAllOrders2() { ArrayList<Order> orders = new ArrayList<>(); orders.add(new Order()); Response<ArrayList<Order>> response = new Response<>(1, null, orders); ResponseEntity<Response<ArrayList<Order>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Response result = adminOrderService.getAllOrders(headers); Assert.assertNotNull(result); }
public void testGetAllTravels2() { ArrayList<AdminTrip> adminTrips = new ArrayList<>(); adminTrips.add(new AdminTrip()); Response<ArrayList<AdminTrip>> response = new Response<>(1, null, adminTrips); ResponseEntity<Response<ArrayList<AdminTrip>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Response result = adminTravelServiceImpl.getAllTravels(headers); Assert.assertNotNull(result); }
public void testTicketCollect2() { //mock getOrderByIdFromOrder( Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(1); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); }
public void testCancelOrder2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); }
public void testTicketCollect2() { //mock getOrderByIdFromOrder( Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(1); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); }
public void testCalculateRefund2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); }
public void testTicketExecute2() { //mock getOrderByIdFromOrder( Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(2); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); }
public void testCancelOrder2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.cancelOrder("order_id", "login_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); }
public void testTicketExecute2() { //mock getOrderByIdFromOrder( Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(2); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); //mock executeOrderOther() Response response3 = new Response(1, null, null); ResponseEntity<Response> re3 = new ResponseEntity<>(response3, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re3); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); }
public void testCalculateRefund2() { //mock getOrderByIdFromOrder() Response<Order> response = new Response<>(0, null, null); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock getOrderByIdFromOrderOther() Order order = new Order(); order.setStatus(6); Response<Order> response2 = new Response<>(1, null, order); ResponseEntity<Response<Order>> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re2); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted", null), result); }
public void testTicketExecute1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(2); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock executeOrder() Response response2 = new Response(1, null, null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 6, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re2); Response result = executeServiceImpl.ticketExecute("order_id", headers); Assert.assertEquals(new Response<>(1, "Success.", null), result); }
public void testCalculateRefund1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(6); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null), result); }
public void testTicketCollect1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(1); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); //mock executeOrder() Response response2 = new Response(1, null, null); ResponseEntity<Response> re2 = new ResponseEntity<>(response2, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/status/" + "order_id" + "/" + 2, HttpMethod.GET, requestEntity, Response.class)).thenReturn(re2); Response result = executeServiceImpl.ticketCollect("order_id", headers); Assert.assertEquals(new Response<>(1, "Success", null), result); }
public void testCalculateRefund1() { //mock getOrderByIdFromOrder() Order order = new Order(); order.setStatus(6); Response<Order> response = new Response<>(1, null, order); ResponseEntity<Response<Order>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order/" + "order_id", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<Order>>() { })).thenReturn(re); Response result = cancelServiceImpl.calculateRefund("order_id", headers); Assert.assertEquals(new Response<>(0, "Order Status Cancel Not Permitted, Refound error", null), result); }
public void testDipatchSeat() { long mills = System.currentTimeMillis(); Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); HttpEntity requestEntityTicket = new HttpEntity(seatRequest, headers); Response<Ticket> response = new Response<>(); ResponseEntity<Response<Ticket>> reTicket = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { })).thenReturn(reTicket); Ticket result = preserveServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); Assert.assertNull(result); }
public void testDipatchSeat() { long mills = System.currentTimeMillis(); Seat seatRequest = new Seat(new Date(mills), "G1234", "start_station", "dest_station", 2); HttpEntity requestEntityTicket = new HttpEntity<>(seatRequest, headers); Response<Ticket> response = new Response<>(); ResponseEntity<Response<Ticket>> reTicket = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-seat-service:18898/api/v1/seatservice/seats", HttpMethod.POST, requestEntityTicket, new ParameterizedTypeReference<Response<Ticket>>() { })).thenReturn(reTicket); Ticket result = rebookServiceImpl.dipatchSeat(new Date(mills), "G1234", "start_station", "dest_station", 2, headers); Assert.assertNull(result); }
public void testGetAllOrders1() { Response<ArrayList<Order>> response = new Response<>(0, null, null); ResponseEntity<Response<ArrayList<Order>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-order-service:12031/api/v1/orderservice/order", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-order-other-service:12032/api/v1/orderOtherService/orderOther", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<Order>>>() { })).thenReturn(re); Response result = adminOrderService.getAllOrders(headers); Assert.assertEquals(new Response<>(1, "Get the orders successfully!", new ArrayList<>()), result); }
public void testGetAllTravels1() { Response<ArrayList<AdminTrip>> response = new Response<>(0, null, null); ResponseEntity<Response<ArrayList<AdminTrip>>> re = new ResponseEntity<>(response, HttpStatus.OK); Mockito.when(restTemplate.exchange( "http://ts-travel-service:12346/api/v1/travelservice/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Mockito.when(restTemplate.exchange( "http://ts-travel2-service:16346/api/v1/travel2service/admin_trip", HttpMethod.GET, requestEntity, new ParameterizedTypeReference<Response<ArrayList<AdminTrip>>>() { })).thenReturn(re); Response result = adminTravelServiceImpl.getAllTravels(headers); Assert.assertEquals(new Response<>(0, null, new ArrayList<>()), result); }
public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; }
public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; }
public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; }
public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; }
public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; }
public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { if (!StringUtils.isEmpty(TEST_USER_ID)) { template.header(AuthConstant.CURRENT_USER_HEADER, TEST_USER_ID); } } }; }
public void listAccount() { Pageable pageRequest = PageRequest.of(0, 2); // test empty Page<Account> accounts = accountRepo.findAll(pageRequest); assertEquals(0, accounts.getTotalElements()); // create 1 new accountRepo.save(newAccount); assertEquals(1, accountRepo.count()); // create 2 more newAccount.setId(null); accountRepo.save(newAccount); assertEquals(2, accountRepo.count()); newAccount.setId(null); accountRepo.save(newAccount); assertEquals(3, accountRepo.count()); accounts = accountRepo.findAll(pageRequest); assertEquals(2, accounts.getNumberOfElements()); pageRequest = pageRequest.next(); accounts = accountRepo.findAll(pageRequest); assertEquals(1, accounts.getNumberOfElements()); assertEquals(2, accounts.getTotalPages()); assertEquals(3, accounts.getTotalElements()); }
public void testListCompany() { Pageable pageRequest = PageRequest.of(0, 2); // test empty Page<Company> companies = companyRepo.findAll(pageRequest); assertEquals(0, companies.getTotalElements()); // create 1 new companyRepo.save(newCompany); assertEquals(1, companyRepo.count()); // create 2 more newCompany.setId(null); companyRepo.save(newCompany); assertEquals(2, companyRepo.count()); newCompany.setId(null); companyRepo.save(newCompany); assertEquals(3, companyRepo.count()); companies = companyRepo.findAll(pageRequest); assertEquals(2, companies.getNumberOfElements()); pageRequest = pageRequest.next(); companies = companyRepo.findAll(pageRequest); assertEquals(1, companies.getNumberOfElements()); assertEquals(2, companies.getTotalPages()); assertEquals(3, companies.getTotalElements()); }