text
stringlengths
10
2.72M
package com.tencent.mm.plugin.wxcredit; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.wxcredit.a.a; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.wallet_core.d.g; import com.tencent.mm.wallet_core.d.i; class e$2 extends g { final /* synthetic */ e qwh; e$2(e eVar, MMActivity mMActivity, i iVar) { this.qwh = eVar; super(mMActivity, iVar); } public final boolean d(int i, int i2, String str, l lVar) { if (i != 0 || i2 != 0) { return false; } if (lVar instanceof a) { a aVar = (a) lVar; e.h(this.qwh).putString("KEY_SESSION_KEY", aVar.token); e.i(this.qwh).putString("key_mobile", aVar.bTi); e.j(this.qwh).putBoolean("key_need_bind_deposit", aVar.cdW); e.k(this.qwh).putBoolean("key_is_bank_user", aVar.qwj); } this.qwh.a(this.fEY, 0, e.l(this.qwh)); return true; } public final boolean m(Object... objArr) { String str = (String) objArr[0]; String str2 = (String) objArr[1]; e.m(this.qwh).putString("key_name", str); e.n(this.qwh).putString("key_indentity", str2); this.uXK.a(new a(str, str2, e.o(this.qwh).getString("KEY_SESSION_KEY"), e.p(this.qwh).getString("key_bank_type")), true, 1); return true; } }
package com.twu.infrastructure; import com.twu.model.User; import java.util.Scanner; public class ManageBookMenu { private User user; private ManageMainMenu menu; public ManageBookMenu(User user, ManageMainMenu menu) { this.user = user; this.menu = menu; } public void showBookSubMenu(){ String menuMessage = "Please choose one of the following options:\n" + "A: Book List\n" + "B: Check out Book\n" + "C: Return Book\n" + "D: Exit\n" + "E: Main Menu"; System.out.println(menuMessage); getBookSubMenuChoice(); } public void getBookSubMenuChoice() { User testuser = user; ManageBooks bookManager = new ManageBooks(testuser, this); Scanner scanChoice = new Scanner(System.in); while(scanChoice.hasNextLine()) { String choice = scanChoice.nextLine(); if(!choice.toUpperCase().equals("A") && !choice.toUpperCase().equals("B") && !choice.toUpperCase().equals("C") && !choice.toUpperCase().equals("D") && !choice.toUpperCase().equals("E")){ choice = "OTHER"; } ManageMessages.menuOptions option = ManageMessages.menuOptions.valueOf(choice.toUpperCase()); switch(option){ case A: bookManager.showAvailableBooks(); showBookSubMenu(); break; case B: System.out.println("What book would you like to check out?"); bookManager.checkOutBook(); break; case C: System.out.println("What book would you like to return?"); bookManager.returnBook(); break; case D: System.exit(0); break; case E: menu.mainMenu(); break; case OTHER: System.out.println("Please select a valid option!"); getBookSubMenuChoice(); break; } } } public void bookCheckOutSuccess(){ System.out.println("Thank you! Enjoy the book!"); showBookSubMenu(); } public void bookCheckOutError(){ System.out.println("Sorry, that book is not available!"); showBookSubMenu(); } public void bookReturnSuccess(){ System.out.println("Thank you for returning the book"); showBookSubMenu(); } public void bookReturnError(){ System.out.println("That is not a valid book to return"); showBookSubMenu(); } }
package com.zy.crm.entity; import java.io.Serializable; public class User implements Serializable{ private Integer userId; private String userCode; private String userName; private String userPwd; private Integer userState; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPwd() { return userPwd; } public void setUserPwd(String userPwd) { this.userPwd = userPwd; } public Integer getUserState() { return userState; } public void setUserState(Integer userState) { this.userState = userState; } }
package parcial.model; public class Prestamo { private double valor; private double interes; private double plazo; private Asociado a1; public Prestamo(double valor, double interes, double plazo, Asociado a1) { this.valor = valor; this.interes = interes; this.plazo = plazo; this.a1 = a1; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public double getInteres() { return interes; } public void setInteres(double interes) { this.interes = interes; } public double getPlazo() { return plazo; } public void setPlazo(double plazo) { this.plazo = plazo; } public Asociado getA1() { return a1; } public void setA1(Asociado a1) { this.a1 = a1; } }
package com.example.signin; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import org.jetbrains.annotations.NotNull; public class forgotPassword extends AppCompatActivity { private EditText resetmail; private Button sub; private FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_forgot_password); resetmail = findViewById(R.id.resetmail); sub = findViewById(R.id.sub); sub.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = resetmail.getText().toString().trim(); if (TextUtils.isEmpty(email)){ resetmail.setError("Email required"); } auth = FirebaseAuth.getInstance(); auth.sendPasswordResetEmail(email).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void unused) { Toast.makeText(forgotPassword.this, "password link has been sent to your registered email", Toast.LENGTH_SHORT).show(); finish(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull @NotNull Exception e) { Toast.makeText(forgotPassword.this, "Something went wrong"+e, Toast.LENGTH_SHORT).show(); } }); } }); } }
package com.phgof.android_project.PacelableData; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * Created by Ph.GOF on 4/1/2018. */ public class MyData implements Parcelable { int x=1; String names; protected MyData(Parcel in) { x = in.readInt(); names = in.readString(); } public static final Creator<MyData> CREATOR = new Creator<MyData>() { @Override public MyData createFromParcel(Parcel in) { return new MyData(in); } @Override public MyData[] newArray(int size) { return new MyData[size]; } }; public void setNames(String names){ this.names = names; } public MyData(String newname) { this.names = newname; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(x); dest.writeString(names); } }
package com.json; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import com.json.StateValue.Matcher; /** * json对应的数据结构 * */ class Value { private List<Attr> attrs = new ArrayList<>(); private List<JsonObject> objs = new ArrayList<>(); private List<JsonArray> arrays = new ArrayList<>(); private List<Object> sequence = new ArrayList<>();//具体的json对象结构顺序 public Value(StateValue value) { genAttrs(value); assembleObjectAndArray(); } /** * 获取根节点 * */ private Object root(){ return sequence.get(0); } /** * 提取json中的所有key值 * @return key key值 value 该key值出现的次数 * */ public Map<String, Integer> jsonKeys(){ Counter<String> counter = new Counter<>(); for(Attr attr : this.attrs){ if(!StringUtil.isEmpty(attr.name)){ counter.add(attr.name); } } for(JsonObject obj : this.objs){ if(!StringUtil.isEmpty(obj.name)){ counter.add(obj.name); } } for(JsonArray array : this.arrays){ if(!StringUtil.isEmpty(array.name)){ counter.add(array.name); } } return counter.getResult(); } /** * 提取json中的所有value值 * @return key value值 value 该value值出现的次数 * */ public Map<String, Integer> jsonValues(){ Counter<String> counter = new Counter<>(); for(Attr attr : this.attrs){ if(!StringUtil.isEmpty(attr.value)){ counter.add(attr.value); } } return counter.getResult(); } /** * 输出json的数据结构 * */ public Set<String> jsonStructure(){ Object obj = sequence.get(0); HashSet<String> set = new HashSet<>(); if(obj instanceof JsonObject){ JsonObject o = (JsonObject) obj; o.structureString(set, "root"); } else if(obj instanceof JsonArray){ JsonArray a = (JsonArray) obj; a.structureString(set, "root"); } return set; } public Object parse(String content, Class<?> cls) throws Exception{ Object o = null; if(ClassUtil.getInstance().inSimpleEncapsolution(cls)){ Attr a = new Attr(); a.value = content; o = getValue(a, cls); } else {//key是个复合类 Value v = Analysis.analysis(content); Object root = v.root(); if(root instanceof JsonObject){ JsonObject ro = (JsonObject) root; o = parseObject(cls, ro); } else if(root instanceof JsonArray){ JsonArray ra = (JsonArray) root; o = parseArray(cls, ra); } } return o; } /** * 解析后的json字符串内容 * */ public String rootJsonString(){ Object obj = sequence.get(0); if(obj instanceof JsonObject){ JsonObject o = (JsonObject) obj; return o.jsonString(); } else if(obj instanceof JsonArray){ JsonArray a = (JsonArray) obj; return a.jsonString(); } else { return null; } } public <T> List<T> parseList(Class<T> c) throws Exception{ Object root = root(); if(root instanceof JsonArray){ return parseArray(c, JsonArray.class.cast(root)); } return null; } public <T> T parseObject(Class<T> c) throws Exception{ Object root = root(); if(root instanceof JsonObject){ return parseObject(c, JsonObject.class.cast(root)); } return null; } /** * 将obj转为封装类 * */ private <T> T parseObject(Class<T> cls, JsonObject obj) throws Exception{ T t = cls.newInstance(); for(Field f : cls.getDeclaredFields()){ if(Modifier.isFinal(f.getModifiers()) || Modifier.isStatic(f.getModifiers())){ continue; } Method method = t.getClass().getMethod("set" + StringUtil.upperFirstLetter(f.getName()), f.getType()); if(f.getType().isPrimitive() || ClassUtil.getInstance().inSimpleEncapsolution(f.getType())){//Attr Attr attr = null; for(Attr a : obj.attrs){ if(f.getName().equals(a.name)){ attr = a; // obj.attrs.remove(a); break; } } if(attr != null){ parsePrimitiveAttr(t, method, attr); } } else if(Collection.class.isAssignableFrom(f.getType()) || f.getType().isArray()){//Array JsonArray array = null; for(JsonArray a : obj.arrays){ if(f.getName().equals(a.name)){ array = a; // obj.arrays.remove(a); break; } } if(array != null){ if(f.getType().isArray()){//数组 Class<?> typeCls = f.getType().getComponentType(); List list = parseArray(typeCls, array); Object o = list2Array(list, typeCls); method.invoke(t, o); } else {//列表 ParameterizedType type = (ParameterizedType) f.getGenericType(); List list = parseList(type, array); if(f.getType() == List.class){ method.invoke(t, list);//初始化列表 } else if(f.getType() == Set.class){ method.invoke(t, new HashSet<>(list));//初始化列表 } else { method.invoke(t, f.getType().newInstance());//初始化列表 method = t.getClass().getMethod("get" + StringUtil.upperFirstLetter(f.getName()), null); Collection collection = (Collection<?>) method.invoke(t, null); collection.addAll(list); } } } } else {//object JsonObject _obj = null; for(JsonObject o : obj.objs){ if(f.getName().equals(o.name)){ _obj = o; obj.objs.remove(o); break; } } if(_obj != null){ if(Map.class.isAssignableFrom(f.getType())){//Map ParameterizedType pt = (ParameterizedType) f.getGenericType(); Type[] types = pt.getActualTypeArguments(); Class keyCls = (Class) types[0]; Class valueCls = (Class) types[1]; Map map = parseMap(keyCls, valueCls, _obj); method.invoke(t, map); } else {//Object method.invoke(t, parseObject(f.getType(), _obj)); } } } } return t; } /** * 将array转为封装类列表 * */ private <T> List<T> parseArray(Class<T> cls, JsonArray array) throws Exception{ List<T> list = new ArrayList<>(); if(cls.isPrimitive() || ClassUtil.getInstance().inSimpleEncapsolution(cls)){ for(int i = 0; i < array.attrs.size(); ++ i){ T t = (T) getValue(array.attrs.get(i), cls); list.add(t); } } else if(Collection.class.isAssignableFrom(cls) || cls.isArray()){//Array if(cls.isArray()){//数组 for(int i = 0; i < array.arrays.size(); ++ i){ T t = (T) parseArray(cls.getComponentType(), array.arrays.get(i)); list.add(t); } } else {//列表 } } else {//Object for(int i = 0; i < array.objs.size(); ++ i){ T t = parseObject(cls, array.objs.get(i)); list.add(t); } } return list; } private List parseList(ParameterizedType type, JsonArray array) throws Exception{ List list = new ArrayList<>(); try {//最后一层 Class typeCls = (Class) type.getActualTypeArguments()[0]; if(ClassUtil.getInstance().inSimpleEncapsolution(typeCls)){ for(Attr attr : array.attrs){ list.add(getValue(attr, typeCls)); } } else {//Object for(JsonObject obj : array.objs){ list.add(parseObject(typeCls, obj)); } } } catch (Exception e) {//还有列表嵌套 for(JsonArray a : array.arrays){ ParameterizedType pt = (ParameterizedType) type.getActualTypeArguments()[0]; List l = parseList(pt, a); list.add(l); } } return list; } private <T> void parsePrimitiveAttr(T t, Method method, Attr attr) throws Exception{ Object value = getValue(attr, method.getParameterTypes()[0]); method.invoke(t, value); } /** * 获取基础值 * */ private Object getValue(Attr attr, Class<?> paramClass){ Object value = null; if(paramClass == int.class || paramClass == Integer.class){ value = Integer.parseInt(attr.value); } else if(paramClass == byte.class || paramClass == Byte.class){ value = Byte.parseByte(attr.value); } else if(paramClass == short.class || paramClass == Short.class){ value = Short.parseShort(attr.value); } else if(paramClass == long.class || paramClass == Long.class){ value = Long.parseLong(attr.value); } else if(paramClass == float.class || paramClass == Float.class){ value = Float.parseFloat(attr.value); } else if(paramClass == double.class || paramClass == Double.class){ value = Double.parseDouble(attr.value); } else if(paramClass == short.class || paramClass == Boolean.class){ value = Boolean.parseBoolean(attr.value); } else if(paramClass == char.class || paramClass == Character.class){ value = attr.value.charAt(0); } else {//字符串 value = attr.value; } return value; } /** * @return 一个是数组的Object * */ private Object list2Array(List list, Class<?> cls){ Object o = Array.newInstance(cls, list.size()); if(cls.isArray()){ for(int i = 0; i < list.size(); ++ i){ List _l = (List) list.get(i); Object _o = list2Array(_l, cls.getComponentType()); Array.set(o, i, _o); } } else {//最后一层 for(int i = 0; i < list.size(); ++ i){ Array.set(o, i, list.get(i)); } } return o; } private Map parseMap(Class<?> keyCls, Class<?> valueCls, JsonObject obj) throws Exception{ if(!ClassUtil.getInstance().inSimpleEncapsolution(keyCls)){ throw new Exception(keyCls.getName() + "作为Map类型key值无法解析,目前key值仅支持基础类型"); } Map map = new HashMap<>(); for(Attr attr : obj.attrs){ Attr a = new Attr(); a.value = attr.name; Object key = getValue(a, keyCls); Object value = getValue(attr, valueCls); if(key == null && value == null){ continue; } else { map.put(key, value); } } for(JsonArray array : obj.arrays){ Attr a = new Attr(); a.value = array.name; Object key = getValue(a, keyCls); Object value = parseArray(valueCls, array); if(key == null && value == null){ continue; } else { map.put(key, value); } } for(JsonObject o : obj.objs){ Attr a = new Attr(); a.value = o.name; Object key = getValue(a, keyCls); Object value = parseObject(valueCls, o); if(key == null && value == null){ continue; } else { map.put(key, value); } } return map; } @Override public boolean equals(Object obj) { if(obj instanceof Value){ Value v = (Value) obj; Object o1 = root(); Object o2 = v.root(); if(o1.getClass() == o2.getClass()){ return o1.equals(o2); } } return false; } /** * 生成属性对象数据 * */ private void genAttrs(StateValue value){ for(int i = 0; i < value.getContents().size(); ++ i){ Matcher matcher = value.getContents().get(i); switch (matcher.state) { case State.MEM_KEY: if(matcher.value == null){ continue; } String attrName = matcher.value; matcher = value.getContents().get(++ i); if(matcher.value != null){//属性 Attr attr = new Attr(); attr.name = attrName; attr.value = matcher.value;//值都是字符串 attrs.add(attr); sequence.add(attr); } else {//对象或者数组 matcher = value.getContents().get(++ i); switch (matcher.state) { case State.OBJECT: JsonObject obj = new JsonObject(); obj.name = attrName; this.objs.add(obj); sequence.add(obj); break; case State.ARRAY: JsonArray array = new JsonArray(); array.name = attrName; this.arrays.add(array); sequence.add(array); break; } } break; case State.ARRAY_FINISH: sequence.add(State.ARRAY_FINISH); break; case State.OBJECT_FINISH: sequence.add(State.OBJECT_FINISH); break; case State.OBJECT://初始对象 JsonObject obj = new JsonObject(); this.objs.add(obj); sequence.add(obj); break; case State.ARRAY://初始队列 JsonArray array = new JsonArray(); this.arrays.add(array); sequence.add(array); break; case State.ELEMENT://队列的基础值 if(matcher.value != null){ Attr attr = new Attr(); attr.value = matcher.value; this.attrs.add(attr); sequence.add(attr); } break; } } } /** * 装配属性对象数据,即分配那个类或数组中包含哪些数据 * */ private void assembleObjectAndArray(){ Stack<JsonObject> so = new Stack<>(); Stack<JsonArray> sa = new Stack<>(); Stack<Integer> sf = new Stack<>(); JsonObject nowObj = null; JsonArray nowArray = null; int flag = -1;//表示当前为JsonObject还是JsonArray for(int i = 0; i < sequence.size(); ++ i){ Object obj = sequence.get(i); if(obj instanceof JsonObject){ JsonObject o = (JsonObject) obj; if(nowObj != null){ so.push(nowObj); } switch (flag) {//添加属性 case State.OBJECT: nowObj.objs.add(o); break; case State.ARRAY: nowArray.objs.add(o); break; } //当前对象置换 nowObj = o; if(flag != -1){ sf.push(flag); } flag = State.OBJECT; } else if(obj instanceof JsonArray){ JsonArray a = (JsonArray) obj; if(nowArray != null){ sa.push(nowArray); } switch (flag) {//添加属性 case State.OBJECT: nowObj.arrays.add(a); break; case State.ARRAY: nowArray.arrays.add(a); break; } //当前对象置换 nowArray = a; if(flag != -1){ sf.push(flag); } flag = State.ARRAY; } else if(obj instanceof Attr){ Attr attr = (Attr) obj; switch (flag) {//添加属性 case State.OBJECT: nowObj.attrs.add(attr); break; case State.ARRAY: nowArray.attrs.add(attr); break; } } else {//终结 int state = (int) obj; if(sf.isEmpty()){ flag = -1; } else { flag = sf.pop(); } switch (state) { case State.ARRAY_FINISH: if(sa.isEmpty()){ nowArray = null; } else { nowArray = sa.pop(); } break; case State.OBJECT_FINISH: if(so.isEmpty()){ nowObj = null; } else { nowObj = so.pop(); } break; } } } } public class Attr{ String name;//属性名 String value;//属性值 public String jsonString() { StringBuilder builder = new StringBuilder(); if(name == null){ builder.append("\"").append(value).append("\""); } else { builder.append("\"").append(name).append("\" : \"").append(value).append("\""); } return builder.toString(); } public String simpleMsg(){ return name + " : " + value; } /** * 获取结构字符串 * @param structure 用于存放结构字符串的容器 * @param parentStructureString 父类字符串 * */ public void structureString(Set<String> structure, String parentStructureString){ if(!StringUtil.isEmpty(name)){ parentStructureString += "." + name; } structure.add(parentStructureString); } @Override public String toString() { return simpleMsg(); } @Override public boolean equals(Object obj) { if(obj instanceof Attr){ Attr a = (Attr) obj; if(name != null && a.name != null && name.equals(a.name) && value.equals(a.value)){ return true; } else if(name == null && a.name == null && value.equals(a.value)){ return true; } } return false; } } public class JsonArray{ String name;//属性名 List<JsonObject> objs;//属性值-复合封装类 List<JsonArray> arrays;//属性值-数组 List<Attr> attrs;//属性值-基础封装类 public JsonArray() { this.objs = new ArrayList<>(); this.arrays = new ArrayList<>(); this.attrs = new ArrayList<>(); } public String simpleMsg(){ int childCount = objs.size() + arrays.size() + attrs.size(); return "Array " + name + "(" + childCount + ")"; } public String jsonString() { StringBuilder builder = new StringBuilder(); if(name == null){ builder.append("["); } else { builder.append("\"").append(name).append("\" : ["); } for(Attr attr : attrs){ builder.append(attr.jsonString()).append(","); } for(JsonObject o : objs){ builder.append(o.jsonString()).append(","); } for(JsonArray a : arrays){ builder.append(a.jsonString()).append(","); } if(builder.charAt(builder.length() - 1) == ','){ builder.deleteCharAt(builder.length() - 1); } builder.append("]"); return builder.toString(); } /** * 获取结构字符串 * @param structure 用于存放结构字符串的容器 * @param parentStructureString 父类字符串 * */ public void structureString(Set<String> structure, String parentStructureString){ if(!StringUtil.isEmpty(name)){ parentStructureString += "." + name; } parentStructureString += "{Array}"; structure.add(parentStructureString); for(Attr attr : this.attrs){ attr.structureString(structure, parentStructureString); } for(JsonObject obj : this.objs){ obj.structureString(structure, parentStructureString); } for(JsonArray array : this.arrays){ array.structureString(structure, parentStructureString); } } @Override public String toString() { return simpleMsg(); } @Override public boolean equals(Object obj) { if(obj instanceof JsonArray){ JsonArray a = (JsonArray) obj; if(!StringUtil.isEmpty(name) && !StringUtil.isEmpty(a.name) && !name.equals(a.name)){ return false; } else if(!StringUtil.isEmpty(name) && StringUtil.isEmpty(a.name)){ return false; } else if(StringUtil.isEmpty(name) && !StringUtil.isEmpty(a.name)){ return false; } for(JsonObject o : objs){ boolean isSame = false; for(JsonObject oa : a.objs){ if(oa.equals(o)){ isSame = true; break; } } if(!isSame){ return false; } } for(JsonArray o : arrays){ boolean isSame = false; for(JsonArray oa : a.arrays){ if(oa.equals(o)){ isSame = true; break; } } if(!isSame){ return false; } } for(Attr o : attrs){ boolean isSame = false; for(Attr oa : a.attrs){ if(oa.equals(o)){ isSame = true; break; } } if(!isSame){ return false; } } return true; } return false; } } public class JsonObject{ String name;//属性名 List<JsonObject> objs;//属性值-复合封装类 List<JsonArray> arrays;//属性值-数组 List<Attr> attrs;//属性值-基础封装类 public JsonObject() { this.objs = new ArrayList<>(); this.arrays = new ArrayList<>(); this.attrs = new ArrayList<>(); } public String simpleMsg(){ int childCount = objs.size() + arrays.size() + attrs.size(); return "Object " + name + "(" + childCount + ")"; } public String jsonString() { StringBuilder builder = new StringBuilder(); if(name == null){ builder.append("{"); } else { builder.append("\"").append(name).append("\" : {"); } for(Attr attr : attrs){ builder.append(attr.jsonString()).append(","); } for(JsonObject o : objs){ builder.append(o.jsonString()).append(","); } for(JsonArray a : arrays){ builder.append(a.jsonString()).append(","); } if(builder.charAt(builder.length() - 1) == ','){ builder.deleteCharAt(builder.length() - 1); } builder.append("}"); return builder.toString(); } /** * 获取结构字符串 * @param structure 用于存放结构字符串的容器 * @param parentStructureString 父类字符串 * */ public void structureString(Set<String> structure, String parentStructureString){ if(!StringUtil.isEmpty(name)){ parentStructureString += "." + name; } parentStructureString += "{Object}"; structure.add(parentStructureString); for(Attr attr : this.attrs){ attr.structureString(structure, parentStructureString); } for(JsonObject obj : this.objs){ obj.structureString(structure, parentStructureString); } for(JsonArray array : this.arrays){ array.structureString(structure, parentStructureString); } } @Override public String toString() { return simpleMsg(); } @Override public boolean equals(Object obj) { if(obj instanceof JsonObject){ JsonObject a = (JsonObject) obj; if(!StringUtil.isEmpty(name) && !StringUtil.isEmpty(a.name) && !name.equals(a.name)){ return false; } else if(!StringUtil.isEmpty(name) && StringUtil.isEmpty(a.name)){ return false; } else if(StringUtil.isEmpty(name) && !StringUtil.isEmpty(a.name)){ return false; } for(JsonObject o : objs){ boolean isSame = false; for(JsonObject oa : a.objs){ if(oa.equals(o)){ isSame = true; break; } } if(!isSame){ return false; } } for(JsonArray o : arrays){ boolean isSame = false; for(JsonArray oa : a.arrays){ if(oa.equals(o)){ isSame = true; break; } } if(!isSame){ return false; } } for(Attr o : attrs){ boolean isSame = false; for(Attr oa : a.attrs){ if(oa.equals(o)){ isSame = true; break; } } if(!isSame){ return false; } } return true; } return false; } } public String attrString(){ return "attrs : " + attrs.toString() + "\nobjects : " + objs.toString() + "\narrays : " + arrays.toString(); } public String sequenceString(){ StringBuilder builder = new StringBuilder(); for(int i = 0; i < sequence.size(); ++ i){ Object obj = sequence.get(i); if(obj instanceof Integer){ int state = (int) obj; builder.append(State.name(state)).append("\n"); } else { builder.append(obj.toString()).append("\n"); } } return builder.toString(); } @Override public String toString() { return attrString(); } }
public class TassaTest { double importo; public TassaTest(double newImporto) { importo=newImporto; } public double getTassa() { double tassa=0; int tassa10=1000; int tassa7=700; int tassa5=500; double a=0; if(importo<=10000) tassa=((importo*10)/100); if (importo>10000 && importo <=20000) { a=importo-10000; tassa=((a*7)/100)+tassa10; } if (importo>20000 && importo <=30000) { a=importo-20000; tassa=((a*5)/100)+tassa10+tassa7; } if (importo>30000) { a=importo-30000; tassa=((a*3)/100)+tassa10+tassa7+tassa5; } return tassa; } }
package heihei.shenqi.presentation.rtys; import java.util.List; import heihei.shenqi.data.Task; import heihei.shenqi.presentation.BasePresenter; import heihei.shenqi.presentation.BaseView; /** * User: lyjq(1752095474) * Date: 2016-07-25 */ public class PicContract { interface View extends BaseView<Presenter> { void setLoadingIndicator(boolean active); void showTasks(List<Task> tasks); void addTasks(List<Task> tasks); void showError(String str); boolean isActive(); } interface Presenter extends BasePresenter { void onRefresh(); void onLoadMore(); } }
package org.ros.android.view.visualization.shape; import org.ros.android.view.visualization.VisualizationView; import uk.co.blogspot.fractiousg.texample.GLText; import javax.microedition.khronos.opengles.GL10; public class TextShape extends BaseShape { private final GLText glText; private final String text; private float x; private float y; public TextShape(GLText glText, String text) { this.glText = glText; this.text = text; } public void setOffset(float x, float y) { this.x = x; this.y = y; } @Override protected void scale(VisualizationView view, GL10 gl) { // Counter adjust for the camera zoom. gl.glScalef(1 / (float) view.getCamera().getZoom(), 1 / (float) view.getCamera().getZoom(), 1.0f); } @Override protected void drawShape(VisualizationView view, GL10 gl) { gl.glEnable(GL10.GL_TEXTURE_2D); glText.begin(getColor().getRed(), getColor().getGreen(), getColor().getBlue(), getColor() .getAlpha()); glText.draw(text, x, y); glText.end(); gl.glDisable(GL10.GL_TEXTURE_2D); } }
package com.example.isafety; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class SosHomeActivity extends AppCompatActivity { private Button sosButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sos_home); sosButton = findViewById(R.id.panic_button_sos); sosButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SosHomeActivity.this, SOSMessageActivity.class)); } }); } }
package com.alodiga.wallet.ejb; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.ejb.TransactionManagement; import javax.ejb.TransactionManagementType; import javax.interceptor.Interceptors; import javax.persistence.EntityTransaction; import javax.persistence.NoResultException; import javax.persistence.Query; import org.apache.log4j.Logger; //import com.alodiga.businessportal.ws.BPBusinessWSProxy; //import com.alodiga.businessportal.ws.BpBusiness; //import com.alodiga.businessportal.ws.BusinessSearchType; import com.alodiga.wallet.common.ejb.ProductEJB; import com.alodiga.wallet.common.ejb.ProductEJBLocal; import com.alodiga.wallet.common.ejb.UtilsEJB; import com.alodiga.wallet.common.ejb.UtilsEJBLocal; import com.alodiga.wallet.common.exception.EmptyListException; import com.alodiga.wallet.common.exception.GeneralException; import com.alodiga.wallet.common.exception.NegativeBalanceException; import com.alodiga.wallet.common.exception.NullParameterException; import com.alodiga.wallet.common.exception.RegisterNotFoundException; import com.alodiga.wallet.common.genericEJB.AbstractWalletEJB; import com.alodiga.wallet.common.genericEJB.EJBRequest; import com.alodiga.wallet.common.genericEJB.WalletContextInterceptor; import com.alodiga.wallet.common.genericEJB.WalletLoggerInterceptor; import com.alodiga.wallet.common.model.BalanceHistory; import com.alodiga.wallet.common.model.BankHasProduct; import com.alodiga.wallet.common.model.Category; import com.alodiga.wallet.common.model.CommissionItem; import com.alodiga.wallet.common.model.DocumentTypeEnum; import com.alodiga.wallet.common.model.Period; import com.alodiga.wallet.common.model.Product; import com.alodiga.wallet.common.model.ProductData; import com.alodiga.wallet.common.model.ProductIntegrationType; import com.alodiga.wallet.common.model.Provider; import com.alodiga.wallet.common.model.StatusTransactionApproveRequest; import com.alodiga.wallet.common.model.StatusTransactionApproveRequestEnum; import com.alodiga.wallet.common.model.TransactionApproveRequest; import com.alodiga.wallet.common.utils.Constants; import com.alodiga.wallet.common.utils.EJBServiceLocator; import com.alodiga.wallet.common.utils.EjbConstants; import com.alodiga.wallet.common.utils.EjbUtils; import com.alodiga.wallet.common.utils.QueryConstants; import com.alodiga.wallet.common.utils.SendMailTherad; import com.alodiga.wallet.common.utils.SendSmsThread; @Interceptors({WalletLoggerInterceptor.class, WalletContextInterceptor.class}) @Stateless(name = EjbConstants.PRODUCT_EJB, mappedName = EjbConstants.PRODUCT_EJB) @TransactionManagement(TransactionManagementType.BEAN) public class ProductEJBImp extends AbstractWalletEJB implements ProductEJB, ProductEJBLocal { private static final Logger logger = Logger.getLogger(ProductEJBImp.class); @EJB private UtilsEJBLocal utilsEJB; //Category public List<Category> getCategories(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { return (List<Category>) listEntities(Category.class, request, logger, getMethodName()); } public Category deleteCategory(EJBRequest request) throws GeneralException, NullParameterException { return null; } public Category loadCategory(EJBRequest request) throws GeneralException, RegisterNotFoundException, NullParameterException { return (Category) loadEntity(Category.class, request, logger, getMethodName()); } public Category saveCategory(EJBRequest request) throws GeneralException, NullParameterException { return (Category) saveEntity(request, logger, getMethodName()); } //Product public List<Product> getProducts(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { return (List<Product>) listEntities(Product.class, request, logger, getMethodName()); } public List<Product> filterProducts(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { if (request == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "request"), null); } Map<String, Object> params = request.getParams(); if (params == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "params"), null); } Boolean isFilter = true; Map orderField = new HashMap(); orderField.put(Product.NAME, QueryConstants.ORDER_DESC); return (List<Product>) createSearchQuery(Product.class, request, orderField, logger, getMethodName(), "customers", isFilter); } public List<Product> getProductsByEnterprise(Long enterpriseId) throws GeneralException, EmptyListException, NullParameterException { List<Product> products = null; if (enterpriseId == null || enterpriseId.equals("")) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "enterpriseId"), null); } // Query query = null; try { query = createQuery("SELECT p FROM Product p WHERE p.enterprise.id = ?1"); query.setParameter("1", enterpriseId); products = query.setHint("toplink.refresh", "true").getResultList(); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } if (products.isEmpty()) { throw new EmptyListException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName()), null); } return products; } public Product loadProduct(EJBRequest request) throws GeneralException, RegisterNotFoundException, NullParameterException { return (Product) loadEntity(Product.class, request, logger, getMethodName()); } public Product loadProductById(Long productId) throws GeneralException, RegisterNotFoundException, NullParameterException { if (productId == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "productId"), null); } Product product = new Product(); try { Query query = createQuery("SELECT p FROM Product p WHERE p.id = ?1"); query.setParameter("1", productId); product = (Product) query.getSingleResult(); } catch (Exception ex) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), ex.getMessage()), null); } if (product == null) { throw new RegisterNotFoundException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName()), null); } return product; } public Product enableProduct(EJBRequest request) throws GeneralException, NullParameterException, RegisterNotFoundException { return (Product) saveEntity(request, logger, getMethodName()); } public Product deleteProduct(EJBRequest request) throws GeneralException, NullParameterException { return null; } public void deleteProductHasProvider(Long productId) throws NullParameterException, GeneralException { if (productId == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "productId or providerId"), null); } try { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); //String sql = "DELETE FROM ProductHasProvider php WHERE php.product.id=" + productId; StringBuilder sqlBuilder = new StringBuilder("DELETE FROM ProductHasProvider php WHERE php.product.id=?1"); Query query = createQuery(sqlBuilder.toString()); query.setParameter("1", productId); query.executeUpdate(); transaction.commit(); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } } public Product saveProduct(EJBRequest request) throws GeneralException, NullParameterException { return (Product) saveEntity(request, logger, getMethodName()); } //promotion public void deletePromotionTypeHasPromotion(EJBRequest request) throws NullParameterException, GeneralException { Object param = request.getParam(); if (param == null || !(param instanceof Long)) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "promotionId"), null); } Map<String, Object> map = new HashMap<String, Object>(); map.put("promotionId", (Long) param); try { //executeNameQuery(PromotionTypeHasPromotion.class, QueryConstants.DELETE_PROMOTION_TYPE_HAS_PROMOTION, map, getMethodName(), logger, "PromotionTypeHasPromotion", null, null); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } } //provider public Provider deleteProvider(EJBRequest request) throws GeneralException, NullParameterException { return null; } public List<Provider> getProviders(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { return (List<Provider>) listEntities(Provider.class, request, logger, getMethodName()); } public List<Provider> getSMSProviders(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { List<Provider> providers = null; // Query query = null; try { query = createQuery("SELECT p FROM Provider p WHERE p.isSMSProvider=1 AND p.enabled=1"); if (request.getLimit() != null && request.getLimit() > 0) { query.setMaxResults(request.getLimit()); } else { query.setMaxResults(20); } providers = query.setHint("toplink.refresh", "true").getResultList(); } catch (Exception e) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } if (providers.isEmpty()) { throw new EmptyListException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName()), null); } return providers; } public Provider loadProvider(EJBRequest request) throws GeneralException, RegisterNotFoundException, NullParameterException { return (Provider) loadEntity(Provider.class, request, logger, getMethodName()); } public Provider saveProvider(EJBRequest request) throws GeneralException, NullParameterException { return (Provider) saveEntity(request, logger, getMethodName()); } //PinFree public Boolean deletePinFree(EJBRequest request) throws GeneralException, NullParameterException { return (Boolean) removeEntity(request, logger, getMethodName()); } // public Float getPercentDiscount(Long levelId, Long productId) throws GeneralException, NullParameterException { if (levelId == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "levelId"), null); } if (productId == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "productId"), null); } Float discount = 0F; try { Query query = createQuery("SELECT lhp FROM LevelHasProduct lhp WHERE lhp.endingDate IS NULL AND lhp.level.id=?1 AND lhp.product.id=?2 "); query.setParameter("1", levelId); query.setParameter("2", productId); // discount = ((LevelHasProduct) query.getSingleResult()).getDiscountPercent(); } catch (Exception ex) { ex.getMessage(); throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), ex.getMessage()), null); } return discount; } //ProductData public ProductData saveProductData(EJBRequest request) throws GeneralException, NullParameterException { return (ProductData) saveEntity(request, logger, getMethodName()); } //Period public List<Period> getPeriods(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { return (List<Period>) listEntities(Period.class, request, logger, getMethodName()); } @Override public List<ProductIntegrationType> getProductIntegrationType(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { return (List<ProductIntegrationType>) listEntities(ProductIntegrationType.class, request, logger, getMethodName()); } //BankHasProduct @Override public List<BankHasProduct> getBankHasProduct(EJBRequest request) throws EmptyListException, GeneralException, NullParameterException { List<BankHasProduct> bankHasProductList = null; Map<String, Object> params = request.getParams(); if (!params.containsKey(EjbConstants.PARAM_PRODUCT_ID)) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), EjbConstants.PARAM_PRODUCT_ID), null); } bankHasProductList = (List<BankHasProduct>) getNamedQueryResult(BankHasProduct.class, QueryConstants.BANK_BY_PRODUCT, request, getMethodName(), logger, "bankHasProductList"); return bankHasProductList; } @Override public BankHasProduct saveBankHasProduct(BankHasProduct bankHasProduct) throws RegisterNotFoundException, NullParameterException, GeneralException { BankHasProduct _bankHasProduct = null; if (bankHasProduct == null) { throw new NullParameterException("bankHasProduct", null); } _bankHasProduct = (BankHasProduct) saveEntity(bankHasProduct, logger, getMethodName()); return _bankHasProduct; } @Override public List<BankHasProduct> getBankHasProductByID(BankHasProduct bankHasProduct) throws GeneralException, EmptyListException, NullParameterException { List<BankHasProduct> bankHasProductList = null; try { if (bankHasProduct == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "bankHasProduct"), null); } //To change body of generated methods, choose Tools | Templates. StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM bank_has_product where productId="); sqlBuilder.append(bankHasProduct.getProductId().getId()); sqlBuilder.append(" and bankId="); sqlBuilder.append(bankHasProduct.getBankId().getId()); Query query = entityManager.createNativeQuery(sqlBuilder.toString(), BankHasProduct.class); bankHasProductList = (List<BankHasProduct>) query.setHint("toplink.refresh", "true").getResultList(); } catch (Exception ex) { throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), ex.getMessage()), ex); } return bankHasProductList; } @Override public List<TransactionApproveRequest> getTransactionApproveRequestByParams(EJBRequest request) throws GeneralException, NullParameterException, EmptyListException { List<TransactionApproveRequest> operations = new ArrayList<TransactionApproveRequest>(); Map<String, Object> params = request.getParams(); StringBuilder sqlBuilder = new StringBuilder("SELECT t FROM TransactionApproveRequest t WHERE t.createDate BETWEEN ?1 AND ?2 and t.requestNumber like '%"+DocumentTypeEnum.MRAR.getDocumentType()+"%'"); if (!params.containsKey(QueryConstants.PARAM_BEGINNING_DATE) || !params.containsKey(QueryConstants.PARAM_ENDING_DATE)) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "beginningDate & endingDate"), null); } if (params.containsKey(QueryConstants.PARAM_STATUS_TRANSACTION_APPROVE_REQUEST_ID)) { sqlBuilder.append(" AND t.statusTransactionApproveRequestId.id=").append(params.get(QueryConstants.PARAM_STATUS_TRANSACTION_APPROVE_REQUEST_ID)); } if (params.containsKey(QueryConstants.PARAM_PRODUCT_ID)) { sqlBuilder.append(" AND t.productId.id=").append(params.get(QueryConstants.PARAM_PRODUCT_ID)); } if (params.containsKey(QueryConstants.PARAM_REQUEST_NUMBER)) { sqlBuilder.append(" AND t.requestNumber='").append(params.get(QueryConstants.PARAM_REQUEST_NUMBER)).append("'"); } Query query = null; try { System.out.println("query:********"+sqlBuilder.toString()); query = createQuery(sqlBuilder.toString()); query.setParameter("1", EjbUtils.getBeginningDate((Date) params.get(QueryConstants.PARAM_BEGINNING_DATE))); query.setParameter("2", EjbUtils.getEndingDate((Date) params.get(QueryConstants.PARAM_ENDING_DATE))); if (request.getLimit() != null && request.getLimit() > 0) { query.setMaxResults(request.getLimit()); } operations = query.setHint("toplink.refresh", "true").getResultList(); } catch (Exception e) { e.printStackTrace(); throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } if (operations.isEmpty()) { throw new EmptyListException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName()), null); } return operations; } @Override public TransactionApproveRequest loadTransactionApproveRequest(EJBRequest request) throws RegisterNotFoundException, NullParameterException, GeneralException { TransactionApproveRequest transactionApproveRequest = (TransactionApproveRequest) loadEntity(TransactionApproveRequest.class, request, logger, getMethodName()); return transactionApproveRequest; } @Override public TransactionApproveRequest saveTransactionApproveRequest(TransactionApproveRequest transactionApproveRequest) throws RegisterNotFoundException, NullParameterException, GeneralException { if (transactionApproveRequest == null) { throw new NullParameterException("transactionApproveRequest", null); } return (TransactionApproveRequest) saveEntity(transactionApproveRequest); } @Override public List<StatusTransactionApproveRequest> getStatusTransactionApproveRequests(EJBRequest request) throws GeneralException, EmptyListException, NullParameterException { List<StatusTransactionApproveRequest> statusTransactionApproveRequests = (List<StatusTransactionApproveRequest>) listEntities(StatusTransactionApproveRequest.class, request, logger, getMethodName()); return statusTransactionApproveRequests; } @Override public StatusTransactionApproveRequest loadStatusTransactionApproveRequestbyCode(EJBRequest request) throws RegisterNotFoundException, NullParameterException, GeneralException { List<StatusTransactionApproveRequest> statuses = null; Map<String, Object> params = request.getParams(); if (!params.containsKey(QueryConstants.PARAM_CODE)) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), QueryConstants.PARAM_CODE), null); } try { statuses = (List<StatusTransactionApproveRequest>) getNamedQueryResult(StatusTransactionApproveRequest.class, QueryConstants.CODE_BY_STATUS, request, getMethodName(), logger, "User"); } catch (EmptyListException e) { throw new RegisterNotFoundException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName(), "user"), null); } return statuses.get(0); } @Override public TransactionApproveRequest updateTransactionApproveRequest(TransactionApproveRequest transactionApproveRequest) throws RegisterNotFoundException, NullParameterException, GeneralException, NegativeBalanceException { if (transactionApproveRequest == null) { throw new NullParameterException("transactionApproveRequest", null); } Float rechargeAmount; EJBRequest request = new EJBRequest(); StatusTransactionApproveRequest statusTransactionApproveRequestId = null; Map params = new HashMap<String, Object>(); if (transactionApproveRequest.getIndApproveRequest()) { try { params.put(QueryConstants.PARAM_CODE, StatusTransactionApproveRequestEnum.APPR.getStatusTransactionApproveRequest()); request.setParams(params); statusTransactionApproveRequestId = loadStatusTransactionApproveRequestbyCode(request); transactionApproveRequest.setStatusTransactionApproveRequestId(statusTransactionApproveRequestId); List<CommissionItem> commissionItems = utilsEJB.getCommissionItems(transactionApproveRequest.getTransactionId().getId()); if (!commissionItems.isEmpty()) { rechargeAmount = calculateAmountRecharge(commissionItems.get(0),transactionApproveRequest.getTransactionId().getAmount()); saveTransactionApproveRequest(transactionApproveRequest); BalanceHistory balancehistory = createBalanceHistory(transactionApproveRequest.getUnifiedRegistryUserId(),transactionApproveRequest.getProductId(), rechargeAmount,2); balancehistory.setTransactionId(transactionApproveRequest.getTransactionId()); // saveBalanceHistory(balancehistory); try { // BPBusinessWSProxy proxy = new BPBusinessWSProxy(); // BpBusiness bpBussiness = proxy.getBusiness(BusinessSearchType.ID, String.valueOf(transactionApproveRequest.getUnifiedRegistryUserId())); // bpBussiness.getPhoneNumber(); SendSmsThread sendMailTherad = new SendSmsThread("584160136793",transactionApproveRequest.getTransactionId().getTotalAmount(), transactionApproveRequest.getRequestNumber(), Constants.SEND_TYPE_SMS_RECHARGE,transactionApproveRequest.getUnifiedRegistryUserId(),entityManager); sendMailTherad.run(); } catch (Exception ex) { ex.printStackTrace(); } } } catch (RegisterNotFoundException e) { e.printStackTrace(); throw new RegisterNotFoundException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName(), "transactionApproveRequest"), null); } catch (EmptyListException e) { e.printStackTrace(); throw new RegisterNotFoundException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName(), "transactionApproveRequest"), null); } catch (NegativeBalanceException e) { throw new NegativeBalanceException("Current amount can not be negative"); } catch (Exception e) { e.printStackTrace(); throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } } else { try { params.put(QueryConstants.PARAM_CODE, StatusTransactionApproveRequestEnum.REJE.getStatusTransactionApproveRequest()); request.setParams(params); statusTransactionApproveRequestId = loadStatusTransactionApproveRequestbyCode(request); transactionApproveRequest.setStatusTransactionApproveRequestId(statusTransactionApproveRequestId); saveTransactionApproveRequest(transactionApproveRequest); } catch (RegisterNotFoundException e) { e.printStackTrace(); throw new RegisterNotFoundException(logger, sysError.format(EjbConstants.ERR_EMPTY_LIST_EXCEPTION, this.getClass(), getMethodName(), "transactionApproveRequest"), null); } catch (Exception e) { e.printStackTrace(); throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), e.getMessage()), null); } } return transactionApproveRequest; } private BalanceHistory createBalanceHistory(Long userId, Product productId, float transferAmount, int transactionType) throws GeneralException, NullParameterException, NegativeBalanceException, RegisterNotFoundException { BalanceHistory currentBalanceHistory = loadLastBalanceHistoryByUserId(userId, productId.getId()); float currentAmount = currentBalanceHistory != null ? currentBalanceHistory.getCurrentAmount() : 0f; BalanceHistory balanceHistory = new BalanceHistory(); balanceHistory.setUserId(userId); balanceHistory.setDate(new Timestamp(new java.util.Date().getTime())); balanceHistory.setOldAmount(currentAmount); balanceHistory.setVersion(currentBalanceHistory!=null?currentBalanceHistory.getId():null); balanceHistory.setProductId(productId); float newCurrentAmount = 0.0f; switch (transactionType) { case 1: //descontar el saldo newCurrentAmount = currentAmount - transferAmount; break; case 2://incrementar el saldo newCurrentAmount = currentAmount + transferAmount;//SUMO AL MONTO ACTUAL (EL DESTINO) break; } if (newCurrentAmount < 0) { throw new NegativeBalanceException("Current amount can not be negative"); } balanceHistory.setCurrentAmount(newCurrentAmount); return balanceHistory; } public BalanceHistory loadLastBalanceHistoryByUserId(Long userId, Long productId) throws GeneralException, RegisterNotFoundException, NullParameterException { if (userId == null) { throw new NullParameterException(sysError.format(EjbConstants.ERR_NULL_PARAMETER, this.getClass(), getMethodName(), "accountId"), null); } BalanceHistory balanceHistory = null; try { Date maxDate = (Date) entityManager.createQuery("SELECT MAX(b.date) FROM BalanceHistory b WHERE b.userId = " + userId + " and b.productId.id= "+ productId).getSingleResult(); Query query = entityManager.createQuery("SELECT b FROM BalanceHistory b WHERE b.date = :maxDate AND b.userId = " + userId+ " and b.productId.id= "+ productId); query.setParameter("maxDate", maxDate); List result = (List) query.setHint("toplink.refresh", "true").getResultList(); if (!result.isEmpty()) { balanceHistory = ((BalanceHistory) result.get(0)); } } catch (NoResultException ex) { throw new RegisterNotFoundException(logger, sysError.format(EjbConstants.ERR_REGISTER_NOT_FOUND_EXCEPTION, this.getClass(), getMethodName(), "BalanceHistory"), null); } catch (Exception e) { e.printStackTrace(); throw new GeneralException(logger, sysError.format(EjbConstants.ERR_GENERAL_EXCEPTION, this.getClass(), getMethodName(), "BalanceHistory"), null); } return balanceHistory; } private float calculateAmountRecharge(CommissionItem commisionItem, float amountTransaction) { float amountRecharge = 0; switch (commisionItem.getCommissionId().getIndApplicationCommission()) { case 1: amountRecharge = amountTransaction - commisionItem.getAmount(); break; case 2: amountRecharge = amountTransaction; break; default: amountRecharge = amountTransaction - commisionItem.getAmount(); break; } return amountRecharge; } @Override public BalanceHistory saveBalanceHistory(BalanceHistory balancehistory) throws GeneralException, NullParameterException { if (balancehistory == null) { throw new NullParameterException("balancehistory", null); } return (BalanceHistory) saveEntity(balancehistory); } }
package com.niit.MobileShoppingBackend.test; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.niit.MobileShoppingBackend.DAO.ProductDAO; import com.niit.MobileShoppingBackend.DTO.Product; public class ProductTestCase { private static AnnotationConfigApplicationContext context; private static ProductDAO productDao; private static Product product; @BeforeClass //For initialisation of the classes public static void init() { //Initialisation of AnnotationConfigApplicationContext class context=new AnnotationConfigApplicationContext(); //Indicates from where to scan the classes for annotations context.scan("com.niit.MobileShoppingBackend"); //Refresh the context context.refresh(); //Here we are indicating that this is the class which as annotations //we need to type cast it perticular class since it is returning object productDao=(ProductDAO)context.getBean("productDao"); } /* @Test public void testAddPrducts() { product =new Product(); product.setName("Core2"); product.setBrand("Samsung"); product.setDescription("This is one of the best phone available in the market"); product.setUnitPrice(6500.00); product.setQuantity(2); product.setActive(true); product.setCategoryId(2); product.setSupplierId(2); product.setBrandId(1); product.setTypeId(2); assertEquals("Something went wrong while adding new product ",true,productDao.add(product)); } */ /* @Test public void testGetProduct() { product=productDao.get(4); assertEquals("Something went wrong while retrieving the data by the id ","Samsung",product.getBrand()); } */ /* @Test public void testListProduct() { assertEquals("Successfully fetched the list of categories which are active from the DB",3,productDao.list().size()); } */ /* @Test public void testListActiveProductsByCategory() { assertEquals("Successfully fetched the list of categories which are active from the DB",1,productDao.listActiveProductsByCategory(3).size()); assertEquals("Successfully fetched the list of categories which are active from the DB",2,productDao.listActiveProductsByCategory(2).size()); } */ }
package ativ_fix_hashmap_02_AndreLucas; import java.util.HashMap; import java.util.Scanner; public class acesso { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); HashMap<String, String> login = new HashMap<String, String>(); for (int i = 0; i < 2; i++) { System.out.print("Digite o usuario: "); String usuario = sc.nextLine(); System.out.print("Digite a senha: "); String senha = sc.nextLine(); login.put(usuario, senha); } /* Para conferir as senhas e usuários inseridos * for(String i : login.keySet()) { * System.out.println("Usuário: "+ i + "\nSenha: "+login.get(i)); }**/ //Acessando o sistema System.out.print("Digite o seu usuário: "); String consultUsuario = sc.nextLine(); System.out.print("Digite a sua senha: "); String consultSenha = sc.nextLine(); if(login.containsKey(consultUsuario) == true && login.containsValue(consultSenha) == true) { System.out.println("ACESSO PERMITIDO!!"); }else { System.out.println("ACESSO NEGADO!!"); } } }
package com.tencent.mm.plugin.account.ui; import android.app.ProgressDialog; import android.os.Bundle; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.account.a.j; import com.tencent.mm.plugin.account.friend.a.v; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.h; import com.tencent.mm.ui.f.a.b; import com.tencent.mm.ui.f.a.c.a; import com.tencent.mm.ui.f.a.d; final class BindFacebookUI$a implements a { final /* synthetic */ BindFacebookUI ePD; private BindFacebookUI$a(BindFacebookUI bindFacebookUI) { this.ePD = bindFacebookUI; } /* synthetic */ BindFacebookUI$a(BindFacebookUI bindFacebookUI, byte b) { this(bindFacebookUI); } public final void m(Bundle bundle) { x.d("MicroMsg.BindFacebookUI", "token:" + BindFacebookUI.c(this.ePD).eFo); g.Ei().DT().set(65830, BindFacebookUI.c(this.ePD).eFo); if (BindFacebookUI.c(this.ePD).utp != 0) { g.Ei().DT().set(65832, Long.valueOf(BindFacebookUI.c(this.ePD).utp)); } BindFacebookUI.a(this.ePD, ProgressDialog.show(this.ePD, this.ePD.getString(j.app_tip), this.ePD.getString(j.facebook_auth_binding), true)); BindFacebookUI.e(this.ePD).setOnCancelListener(BindFacebookUI.d(this.ePD)); BindFacebookUI.a(this.ePD, new v(1, BindFacebookUI.c(this.ePD).eFo)); g.DF().a(BindFacebookUI.a(this.ePD), 0); BindFacebookUI.cl(true); } public final void a(d dVar) { x.d("MicroMsg.BindFacebookUI", "onFacebookError:" + dVar.utw); h.b(this.ePD, dVar.getMessage(), this.ePD.getString(j.contact_info_facebookapp_bind_fail), true); BindFacebookUI.cl(false); } public final void a(b bVar) { x.d("MicroMsg.BindFacebookUI", "onError:" + bVar.getMessage()); h.b(this.ePD, bVar.getMessage(), this.ePD.getString(j.contact_info_facebookapp_bind_fail), true); BindFacebookUI.cl(false); } public final void onCancel() { x.d("MicroMsg.BindFacebookUI", "onCancel"); BindFacebookUI.cl(false); } }
public class mixedMessages23 { public static void main (String[] args) { candidate1(); candidate2(); candidate3(); candidate4(); candidate5(); } public static void candidate1() { //00 11 21 32 42 int x = 0; int y = 0; while (x < 5) { y = x - y; System.out.print(x + ""+ y+" "); x = x + 1; } System.out.println(); } public static void candidate2() { //00 11 23 36 410 int x = 0; int y = 0; while (x < 5) { y = y + x; System.out.print(x + ""+ y+" "); x = x + 1; } System.out.println(); } public static void candidate3() { //02 14 25 36 47 int x = 0; int y = 0; while (x < 5) { y = y + 2; if (y > 4) { y = y - 1; } System.out.print(x + ""+ y+" "); x = x + 1; } System.out.println(); } public static void candidate4() { //11 34 59 int x = 0; int y = 0; while (x < 5) { x = x + 1; y = y + x; System.out.print(x + ""+ y+" "); x = x + 1; } System.out.println(); } public static void candidate5() { //02 14 36 59 - Wrong! 02 14 36 48... int x = 0; int y = 0; while (x < 5) { if (y < 5) { x = x + 1; if (y < 3) { x = x - 1; } } y = y + 2; System.out.print(x + ""+ y+" "); x = x + 1; } System.out.println(); } }
package ru.molkov.core; import java.io.Serializable; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class ModelWorker<T extends GenericModel> implements GenericDao<T> { @Autowired private SessionFactory sessionFactory; private Class<T> type; public ModelWorker() { super(); } public ModelWorker(Class<T> type) { this(); this.type = type; } @Transactional public void create(T model) { getSession().save(model); } @Transactional public void update(T model) { if (model.identity() == null) return; getSession().merge(model); } @Transactional public void delete(T model) { if (model.identity() == null) return; getSession().delete(model); } @SuppressWarnings("unchecked") @Transactional public T find(Object id) { T result = null; if (id != null) result = (T) getSession().get(type, (Serializable) id); return result; } @SuppressWarnings("unchecked") @Transactional public List<T> findAll() { return getSession().createCriteria(type).list(); } protected Session getSession() { return sessionFactory.getCurrentSession(); } }
package com.bowlong.net.proto.gen; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.nio.charset.Charset; import com.bowlong.util.NewList; import com.bowlong.util.NewMap; import com.bowlong.util.StrBuilder; @SuppressWarnings({ "unused", "resource" }) public class Bio2GCSharpNative { /** * @param args * @return */ public static String b2g(Class<?> c, boolean src) { B2Class B2C = c.getAnnotation(B2Class.class); String namespace = ""; if (B2C != null) { namespace = B2C.namespace(); } // String p = "gen_b2g"; String p = (src ? "src/" : "") + "gen_b2g"; if (namespace != null && !namespace.isEmpty()) { p = p + "/" + namespace; } File path = new File(p); if (!path.exists()) path.mkdirs(); Class<?>[] classes = c.getDeclaredClasses(); StrBuilder sb = new StrBuilder(); sb.pn("using System;"); sb.pn("using System.Collections;"); sb.pn("using Toolkit;"); sb.pn(""); sb.pn("namespace ${1} {", c.getSimpleName()); sb.pn(""); for (Class<?> class1 : classes) { String sname = class1.getSimpleName(); if (B2G.isServer(class1)) { g2s_call(class1, namespace, sb); } } String sname = c.getSimpleName(); sb.pn("}"); writeFile(p + "/CallNative" + sname + ".cs", sb.toString()); System.out.println(sb); return sb.toString(); } // 生成客户端接口 public static void g2s_call(Class<?> c, String namespace, StrBuilder sb) { String sname = c.getSimpleName(); Method[] methods = c.getMethods(); String cname = c.getSimpleName(); sb.pn("public abstract class CallNative${1} {", cname); StrBuilder sb2 = new StrBuilder(); for (Method m : methods) { String rtype = B2G.getReturnType(m); if (B2G.isServer(m) && rtype.equals("void")) continue; String mname = B2G.getNethodName(m); int hmname = mname.hashCode(); sb2.ap("${1},", hmname); } sb2.removeRight(1); String s = sb2.toString(); sb.pn(""); sb.pn(" public static NewSet CMD = NewSet.create(${1});", s); sb.pn(""); sb.pn(" // //////////////////////////////////////////////"); sb.pn(" // 逻辑分发"); sb.pn(" // //////////////////////////////////////////////"); sb.pn(""); sb.pn(" public void disp(int cmd, int succ, string msg, object attach) {"); sb.pn(" switch (cmd) {"); for (Method m : methods) { String remark = B2G.getRemark(m); String srtype = B2G.getReturnType(m); String mname = B2G.getNethodName(m); int hmname = mname.hashCode(); if (B2G.isServer(m)) { if (!srtype.equals("void")) { sb.pn(" case ${1}: { // ${2}", hmname, remark); sb.pn(" on${1}(cmd, succ, msg, attach);", upper1(mname)); sb.pn(" return;"); sb.pn(" }"); } } } sb.pn(" }"); sb.pn(" throw new Exception(\" cmd: \" + cmd + \" not found processor.\");"); sb.pn(" }"); sb.pn(""); sb.pn(""); sb.pn(" // //////////////////////////////////////////////"); sb.pn(" // 需要实现的接口"); sb.pn(" // //////////////////////////////////////////////"); sb.pn(""); sb.pn(" public abstract void OnExcept(Exception e, int stat, string msg);"); for (Method m : methods) { String remark = B2G.getRemark(m); // String oType = B2G.getOType(m); String srtype = B2G.getReturnType(m); String mname = B2G.getNethodName(m); NewList<NewMap<String, String>> params = B2G.getParameters(m); // 解析参数函数 sb.pn(" // ${1}", remark); if (B2G.isServer(m)) { if (!srtype.equals("void")) { StrBuilder msb = new StrBuilder(); for (NewMap<String, String> m1 : params) { String key = (String) m1.getKey(); String val = (String) m1.getValue(); String hval = val.hashCode() + ""; String p = B2G.getMapType(key); boolean isOut = B2G.isOut(m, val); if (isOut) { if (p.equals("getObject")) { msb.ap("${1} ${2}, ", key, val); } } } sb.pn(" public abstract void on${1}(int cmd, int succ, string msg, object attach);", upper1(mname), msb, srtype); } } sb.pn(""); } sb.pn(" }"); // sb.pn("}"); } public static String upper1(String s) { if (s == null || s.isEmpty()) return s; int len = s.length(); return s.substring(0, 1).toUpperCase() + s.substring(1, len); } public static void writeFile(String f, String str) { try (FileOutputStream out = new FileOutputStream(new File(f)); OutputStreamWriter osw = new OutputStreamWriter(out, Charset.forName("UTF8"));) { osw.write(str, 0, str.length()); osw.close(); out.close(); } catch (Exception e) { e.printStackTrace(); } } }
package com.service; import java.util.List; import com.dto.Baseinfo; public interface BaseinfoService { List<Baseinfo> getAll(Baseinfo baseinfo); int delete(Long id); boolean insert(Baseinfo baseinfo); boolean update(Baseinfo baseinfo); Baseinfo selectByPrimaryKey(Baseinfo baseinfo); }
package com.xworkz.rental.controller; import java.util.List; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.xworkz.rental.dto.CompanyRegistrationDTO; import com.xworkz.rental.entity.CompanyLoginEntity; import com.xworkz.rental.service.CompanyRegistrationService; import com.xworkz.rental.utility.response.Response; @RestController @RequestMapping("/api") @CrossOrigin(origins = {"http://localhost:4200", "http://localhost:4201","https://x-workzdev.github.io" }) public class CompanyRegistration { @Autowired private CompanyRegistrationService companyRegistrationService; private Logger logger = LoggerFactory.getLogger(getClass()); public CompanyRegistration() { logger.info("invoking ---------" + this.getClass().getSimpleName()); } @PostMapping("/companyRegistration") public ResponseEntity<Response> companyRegistration(@Valid @RequestBody CompanyRegistrationDTO registrationDTO) { logger.info("invoking registrationController.clientRegistration() "); Response response = null; try { // if (registrationDTO != null) { logger.info("registrationDto not null" + registrationDTO); response = companyRegistrationService.companyRegistration(registrationDTO); logger.info("Returning respone " + response); return new ResponseEntity<Response>(response, HttpStatus.OK); //} } catch (Exception e) { logger.error(e.getMessage(), e); return new ResponseEntity<Response>(new Response(e.getMessage(),HttpStatus.INTERNAL_SERVER_ERROR), HttpStatus.OK); } //return new ResponseEntity<Response>(response, HttpStatus.OK); } @GetMapping("/getAllCompanyAccount") public List<CompanyLoginEntity> getAllCompanyAccount(){ logger.info("invoking registrationController.getAllCompanyAccount() "); List<CompanyLoginEntity> companyLoginEntities = null; try { logger.info("getting company accounts"); companyLoginEntities = companyRegistrationService.getAllCompanyAccount(); logger.info("company account find and return list of account"); }catch (Exception e) { logger.error(e.getMessage(), e); } return companyLoginEntities; } }
package com.locadoraveiculosweb.constants; import static java.util.Arrays.stream; import com.locadoraveiculosweb.exception.NegocioException; import lombok.Getter; public class MessageConstants { public enum ViewMessages { SALVO_COM_SUCESSO("{0}: {1} salvo com Sucesso!", "SALVAR", "SUCESSO"), EXCLUIDO_COM_SUCESSO("{0}: {1} excluído com sucesso!", "EXCLUIR", "SUCESSO"), ERRO_AO_SALVAR("Erro ao salvar o {0}: {1}!", "SALVAR", "ERRO"), ERRO_AO_EXCLUIR("Erro ao excluir o {0}: {1}!", "EXCLUIR", "ERRO"); @Getter String description; @Getter String msgFor; @Getter String type; ViewMessages(String description, String msgFor, String type) { this.description = description; this.msgFor = msgFor; this.type = type; } public static String getMsgFor(String msgFor, String type) throws NegocioException { return stream(ViewMessages.values()) .filter( vMgF -> msgFor.equals(vMgF.getMsgFor()) ) .filter( vMgT -> type.equals(vMgT.getType() )) .findAny().get().getDescription(); } } public enum BusinessMessages { DESCRICAO_OBRIGATORIA("A Descrição do {0} é Obrigatório!"), NOME_OBRIGATORIO("O nome do(a) {0} é Obrigatório(a)"), CHASSI_OBRIGATORIO("O Chassi é um campo Obrigatório!"), MODELO_CARRO_OBRIGATORIO("O Modelo é um campo Obrigatório!"), PLACA_OBRIGATORIO("A Placa é um campo Obrigatório!"), COR_OBRIGATORIA("A Cor é um campo Obrigatório!"), USUARIO_SENHA_INVALIDOS("Usuário ou Senha inválidos"), USUARIO_EXISTENTE("Usuário já existe."); @Getter String description; BusinessMessages(String description) { this.description = description; } } }
/* * 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 marier.business; /** * * @author linma * */ public class Customer { String emailID; String firstName; String lastName; //default constructor public Customer () { } //custom constructor public Customer(String email, String firstName, String lastName) { this.emailID = email; this.firstName = firstName; this.lastName = lastName; } //adds email to the customer variable email public void setEmail(String email) { this.emailID=email; } //accesses the email variable and returns it. public String getEmail() { return emailID; } //sets the first name variable public void setFirstName(String firstName) { this.firstName=firstName; } //gets the first name variableand returns it public String getFirstName() { return firstName; } //sets last name variable public void setLastName(String lastName) { this.lastName= lastName; } //gets last name variable and returns it public String getLastName() { return this.lastName; } }
package com.hs.doubaobao.model.AddLoanTable.uploadMessage; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.hs.doubaobao.R; import com.hs.doubaobao.base.AppBarActivity; import com.hs.doubaobao.model.AddLoanTable.ApplyLendUtil; import com.hs.doubaobao.utils.ToastUtil; import com.zht.bottomdialog.SelectBottomDialog; import com.zht.datepicker.DateSelectUtil; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.hs.doubaobao.MyApplication.getContext; /** * 作者:zhanghaitao on 2018/1/8 13:31 * 邮箱:820159571@qq.com * * @describe: */ public class TheLoansActivity extends AppBarActivity { @BindView(R.id.loan_type_text) TextView mTypeText; @BindView(R.id.loan_type) LinearLayout mType; @BindView(R.id.loan_account) EditText mAccount; @BindView(R.id.loan_period_text) TextView mPeriodText; @BindView(R.id.loan_period) LinearLayout mPeriod; @BindView(R.id.loan_applydate_text) TextView mApplydateText; @BindView(R.id.loan_applydate) LinearLayout mApplydate; @BindView(R.id.loan_purpose) EditText mPurpose; @BindView(R.id.the_loans_save) Button mLoansSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_the_loans); ButterKnife.bind(this); setTitle("贷款事项"); isShowRightView(false); initView(); } private void initView() { ApplyLendUtil.setTheloans( mTypeText, mAccount, mPeriodText, mApplydateText, mPurpose ); } @OnClick({R.id.loan_type, R.id.loan_period, R.id.loan_applydate}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.loan_type: //01 汇民贷 02 汇商贷 03 汇业贷 04 汇车贷 06 汇房贷 05 汇农贷 SelectBottomDialog dialog = new SelectBottomDialog(); dialog.setItemStrings(getContext(), new String[]{"汇民贷", "汇商贷", "汇业贷", "汇车贷", "汇房贷", "汇农贷"}); dialog.show(getSupportFragmentManager()); dialog.setOnClickListener(new SelectBottomDialog.onItemClickListener() { @Override public void onClick(String text) { mTypeText.setText(text); } }); break; case R.id.loan_period: //申请期限,值:1:12期 2:18期 3:24期 4:36期 5:48期 6:60期 SelectBottomDialog dialog1 = new SelectBottomDialog(); dialog1.setItemStrings(getContext(), new String[]{"12期", "18期", "24期", "36期", "48期", "60期"}); dialog1.show(getSupportFragmentManager()); dialog1.setOnClickListener(new SelectBottomDialog.onItemClickListener() { @Override public void onClick(String text) { mPeriodText.setText(text); } }); break; case R.id.loan_applydate: DateSelectUtil.showSelectDateDialog(this, mApplydateText); break; } } /** * 保存数据 * * @return */ @Override public boolean savaData() { // ApplyLendUtil.changeTheloans( // mTypeText, // mAccount, // mPeriodText, // mApplydateText, // mPurpose // ); return super.savaData(); } @OnClick(R.id.the_loans_save) public void onViewClicked() { ApplyLendUtil.changeTheloans( mTypeText, mAccount, mPeriodText, mApplydateText, mPurpose ); ToastUtil.showToast("保存成功"); } }
package com.tripad.cootrack.erpCommon.ad_callouts; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.servlet.ServletException; import org.apache.log4j.Logger; import org.hibernate.criterion.Restrictions; import org.openbravo.dal.service.OBCriteria; import org.openbravo.dal.service.OBDal; import org.openbravo.erpCommon.ad_callouts.SimpleCallout; import org.openbravo.model.common.businesspartner.BusinessPartner; import com.tripad.cootrack.data.TmcCar; import com.tripad.cootrack.data.TmcDocumentUpdateLine; // the name of the class corresponds to the filename that holds it // hence, modules/modules/org.openbravo.howtos/src/org/openbravo/howtos/ad_callouts/ProductConstructSearchKey.java. // The class must extend SimpleCallout public class TMC_GetAttributeBerbayar extends SimpleCallout { private static final long serialVersionUID = 1L; private static Logger log = Logger.getLogger(TMC_GetAttributeBerbayar.class); @Override protected void execute(CalloutInfo info) throws ServletException { try { String strBusinessPartnerId = info.getStringParameter("inpcBpartnerId", null); String strCarId = info.getStringParameter("inptmcCarId", null); DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy"); TmcCar car = OBDal.getInstance().get(TmcCar.class, strCarId); BusinessPartner bp = OBDal.getInstance().get(BusinessPartner.class, strBusinessPartnerId); OBCriteria<TmcDocumentUpdateLine> tmcDocumentUpdateLineLatest = OBDal.getInstance() .createCriteria(TmcDocumentUpdateLine.class); tmcDocumentUpdateLineLatest.add(Restrictions.eq(TmcDocumentUpdateLine.PROPERTY_TMCCAR, car)); tmcDocumentUpdateLineLatest .add(Restrictions.eq(TmcDocumentUpdateLine.PROPERTY_CUSTOMERNAME, bp)); // berdasar status : Maintenance Pulsa dan Quota tmcDocumentUpdateLineLatest.add( Restrictions.eq(TmcDocumentUpdateLine.PROPERTY_STATUS, "Maintenance Pulsa atau Quota")); // order dari updated date yg paling besar tmcDocumentUpdateLineLatest.addOrderBy(TmcDocumentUpdateLine.PROPERTY_UPDATED, false); // Berdasarkan data yang sudah dibuat sales ordernya tmcDocumentUpdateLineLatest.add( Restrictions.eq(TmcDocumentUpdateLine.PROPERTY_ISSALESORDER,true)); // set maksimum data yg keluar tmcDocumentUpdateLineLatest.setMaxResults(1); for (TmcDocumentUpdateLine prevDocument : tmcDocumentUpdateLineLatest.list()) { info.addResult("inptglIsiPulsaRegSebelumnya", dateFormat.format(prevDocument.getTGLIsiPulsaReg()).toString()); info.addResult("inpnomIsiPulsaReg", prevDocument.getNOMIsiPulsaReg().toString()); info.addResult("inptglIsiPulsaQuotaSebelumnya", dateFormat.format(prevDocument.getTGLIsiPulsaQuota()).toString()); info.addResult("inpnomIsiPulsaQuota", prevDocument.getNOMIsiPulsaQuota().toString()); info.addResult("inpmaintenancedateto", dateFormat.format(prevDocument.getMaintenanceDateTo()).toString()); info.addResult("inpmaintenancedatefrom", dateFormat.format(prevDocument.getMaintenanceDateFrom()).toString()); Long pengisianKe = prevDocument.getPengisianke() + new Long("1"); info.addResult("inppengisianke", pengisianKe.toString()); info.addResult("inpbudget", prevDocument.getBudget().toString()); info.addResult("inpprofit", prevDocument.getProfit().toString()); //tambahan callout field saldo awal (credit awal) info.addResult("inpcreditAwal", prevDocument.getCreditAwal().toString()); } } catch (Exception e) { System.out.println("Error processing request: " + e.getMessage()); log.error("Error processing request: " + e.getMessage(), e); } } }
package com.aws.demo.permids.services.dynamodb; import com.aws.demo.permids.services.BatchPermIdService; import com.aws.demo.permids.services.PermIdService; import com.aws.demo.permids.services.ResetPermIdService; public interface DynamoDBService<T, A> extends ResetPermIdService, PermIdService<T, A>, BatchPermIdService<T, A> { }
package com.esc.fms.service.base; import com.esc.fms.entity.Dictionary; import java.util.List; /** * Created by tangjie on 2016/12/9. */ public interface DictionaryService { List<Dictionary> selectByDictType(String dictType); }
package ru.lember.neointegrationadapter.handler.projectA; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.ReplayProcessor; import reactor.core.publisher.FluxProcessor; import ru.lember.neointegrationadapter.handler.Handler; import ru.lember.neointegrationadapter.handler.Splitter; import ru.lember.neointegrationadapter.message.Message; import javax.annotation.PostConstruct; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Slf4j public class Splitter11 implements Splitter { private ReplayProcessor<Message> processor = ReplayProcessor.create(); private final List<Handler> nextComponents; public Splitter11(Handler... nextComponents) { this.nextComponents = Arrays.stream(nextComponents).collect(Collectors.toList()); } @PostConstruct private void postConstruct() { log.info("Splitter11 initialized"); processor.subscribe(m -> { nextComponents.forEach( next -> next.processor().onNext(m)); }, e -> { log.error("Splitter11 onError: " + e); }); } @Override public List<Handler> nextComponents() { return nextComponents; } @Override public FluxProcessor<Message, Message> processor() { return processor; } }
/** * Client side of the handshake. */ import java.net.Socket; import java.io.FileNotFoundException; import java.io.IOException; import java.security.*; import java.security.cert.*; import java.security.spec.InvalidKeySpecException; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; public class ClientHandshake { /* * The parameters below should be learned by the client * through the handshake protocol. */ /* Session host/port */ public String sessionHost; public int sessionPort; /* Security parameters key/iv should also go here. Fill in! */ public byte[] sessionKey; public byte[] sessionIV; /** * Run client handshake protocol on a handshake socket. * Here, we do nothing, for now. */ public ClientHandshake(Socket handshakeSocket) throws IOException { } public void clientHello (Socket socket, String certificatePath){ HandshakeMessage clientHelloMessage = new HandshakeMessage(); try { X509Certificate clientCertificate = VerifyCertificate.readCertificate(certificatePath); String clientCertificateString = VerifyCertificate.encodeCertificate(clientCertificate); clientHelloMessage.putParameter("MessageType","ClientHello"); clientHelloMessage.putParameter("Certificate",clientCertificateString); clientHelloMessage.send(socket); Logger.log("ClientHello message sent!"); } catch (IOException e) { e.printStackTrace(); Logger.log("Fail to send the ClientHello message!"); } catch (CertificateEncodingException e) { e.printStackTrace(); Logger.log("Fail to read the certificate file!"); } catch (CertificateException e) { e.printStackTrace(); Logger.log("Fail to encode the certificate!"); } } public void receiveServerHello (Socket socket, String caPath) { HandshakeMessage serverHelloMessage = new HandshakeMessage(); try { serverHelloMessage.recv(socket); if (serverHelloMessage.getParameter("MessageType").equals("ServerHello")) { String serverCertificateString = serverHelloMessage.getParameter("Certificate"); X509Certificate serverCertificate = VerifyCertificate.decodeCertificate(serverCertificateString); X509Certificate caCertificate = VerifyCertificate.readCertificate(caPath); VerifyCertificate.verifyCertificate(caCertificate, serverCertificate); //Ensure the validation Logger.log("Server certificate verification successful!"); } else { throw new Exception(); } } catch (IOException e) { e.printStackTrace(); Logger.log("Fail to receive the ServerHello message!"); } catch (CertificateException e) { e.printStackTrace(); Logger.log("Fail to decode the certificate!"); } catch (Exception e) { e.printStackTrace(); Logger.log("Fail to verify the server certificate!"); } } public void forward (Socket socket, String targetHost, String targetPort) { HandshakeMessage forwardMessage = new HandshakeMessage(); forwardMessage.putParameter("MessageType","Forward"); forwardMessage.putParameter("TargetHost",targetHost); forwardMessage.putParameter("TargetPort",targetPort); try { forwardMessage.send(socket); Logger.log("Forward message sent!"); } catch (IOException e) { e.printStackTrace(); Logger.log("Fail to send forward message!"); } } public void receiveSession (Socket socket, String privateKeyFile) { HandshakeMessage sessionMessage = new HandshakeMessage(); try { sessionMessage.recv(socket); if (sessionMessage.getParameter("MessageType").equals("Session")) { PrivateKey clientPrivateKey = HandshakeCrypto.getPrivateKeyFromKeyFile(privateKeyFile); sessionKey = HandshakeCrypto.decrypt(Base64.getDecoder().decode(sessionMessage.getParameter("SessionKey")), clientPrivateKey); sessionIV = HandshakeCrypto.decrypt(Base64.getDecoder().decode(sessionMessage.getParameter("SessionIV")), clientPrivateKey); sessionHost = sessionMessage.getParameter("SessionHost"); sessionPort = Integer.parseInt(sessionMessage.getParameter("SessionPort")); Logger.log("Session message received!"); } else { throw new Exception(); } } catch (IOException e) { e.printStackTrace(); Logger.log("Fail to receive the session message!"); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
package org.km.domain_model.domin; import org.km.values.MfDate; import org.km.values.Money; public class RevenueRecognition { private Money amount; private MfDate date; public RevenueRecognition(Money money, MfDate date) { this.amount = money; this.date = date; } public Money getAmount(){ return amount; } boolean isRecognizableBy(MfDate asOf){ return asOf.after(date) || asOf.equals(date); } }
package executors; import java.util.concurrent.*; public class executorMain { public static void main(String[] args) { // runs 10 at the same time ExecutorService newExec = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { Runnable worker = new threads(" " + i); newExec.execute(worker); } newExec.shutdown(); while (!newExec.isTerminated()) { } System.out.println("All of the threads have finished :)"); } }
package com.example.kcroz.joggr.RecordRoute; import android.content.Context; import android.os.AsyncTask; import com.example.kcroz.joggr.AsyncResponse; import com.example.kcroz.joggr.DatabaseHelper; import java.text.SimpleDateFormat; import java.util.Calendar; public class InsertRun extends AsyncTask<Void, Void, Integer> { private Context _context; private DatabaseHelper _dbHelper; private AsyncResponse _delegate; public InsertRun (Context context, AsyncResponse delegate){ _context = context; _delegate = delegate; } @Override protected void onPreExecute() { _dbHelper = new DatabaseHelper(_context); } @Override protected Integer doInBackground(Void... param) { long runID = _dbHelper.insertRunValues(getCurrentDate(), // Date "Run Finished!", // Title 0, // Distance 0, // Run time 0, // Total run time 0, // Warm up time 0, // Cool down time 0, // Rating ""); // Comment return (int)runID; } protected void onProgressUpdate(Void... progress) { } protected void onPostExecute(Integer result) { _delegate.processRun(result); } private String getCurrentDate() { Calendar calendar = Calendar.getInstance(); SimpleDateFormat mdformat = new SimpleDateFormat("yyyy / MM / dd "); return mdformat.format(calendar.getTime()); } }
package com.cskaoyan.mapper; import com.cskaoyan.bean.Product; import com.cskaoyan.bean.Unqualify; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @auther 芮狼Dan * @date 2019-05-17 23:46 */ public interface UnqualifyMapper { //分页查找 List<Unqualify> findList(@Param("rows") int rows, @Param("offset") int offset); //分页查找 List<Unqualify> findAllList(); //新增不合格品信息 int insert(@Param("unqualify") Unqualify unqualify); //修改不合格信息 int update_all(@Param("unqualify") Unqualify unqualify); //修改不合格备注信息 int update_note(@Param("unqualifyApplyId") String unqualifyApplyId, @Param("note") String note); //删除 int delete_batch(@Param("id") String id); //根据ID来查找不良产品/分页 List<Unqualify> searchUnqualifyByUnqualifyId(@Param("searchValue") String searchValue, @Param("rows") Integer rows,@Param("offset") int offset); //根据ID来查找不良产品/所有条目 List<Unqualify> searchAllUnqualifyByUnqualifyId(@Param("searchValue") String searchValue); //根据product的名字模糊查询product的id List<Product> findProductId(@Param("searchValue") String searchValue); //根据product的名字模糊查询--分页 List<Unqualify> searchUnqualifyByPAgeByProductName(@Param("searchValue") String searchValue, @Param("rows") Integer rows,@Param("offset") int offset); //根据product的名字模糊查询--分页 List<Unqualify> searchAllUnqualifyByProductName(@Param("searchValue")String searchValue); }
package guru.springframework.controllers.v1; import guru.springframework.api.v1.model.VendorDto; import guru.springframework.api.v1.model.VendorListDto; import guru.springframework.services.VendorService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; @Api(description = "This is the Vendor API") @Slf4j @RestController @RequestMapping("/api/v1/vendors") public class VendorController { private final VendorService vendorService; public VendorController(VendorService vendorService) { this.vendorService = vendorService; } @ApiOperation(value = "View a list of all vendors") @GetMapping @ResponseStatus(HttpStatus.OK) public VendorListDto getAllVendors() { log.info("Getting All Vendors..."); return new VendorListDto(vendorService.getAllVendors()); } @ApiOperation(value = "View a specific vendor") @GetMapping("/{id}") @ResponseStatus(HttpStatus.OK) public VendorDto getVendorById(@PathVariable Long id) { log.info("Getting Vendor: " + id); return vendorService.getVendorById(id); } @ApiOperation(value = "Create a new vendor") @PostMapping @ResponseStatus(HttpStatus.CREATED) public VendorDto createNewVendor(@RequestBody VendorDto vendorDto) { log.info("Creating Vendor " + vendorDto.getName()); return vendorService.createNewVendor(vendorDto); } @ApiOperation(value = "Overwrite an existing vendor") @PutMapping("/{id}") @ResponseStatus(HttpStatus.OK) public VendorDto overwriteVendor(@PathVariable Long id, @RequestBody VendorDto vendorDto) { log.info("Overwriting Vendor: " + id); return vendorService.overwriteVendor(id, vendorDto); } @ApiOperation(value = "Update an existing vendor's properties") @PatchMapping("/{id}") @ResponseStatus(HttpStatus.OK) public VendorDto patchVendor(@PathVariable Long id, @RequestBody VendorDto vendorDto) { log.info("Patching Vendor: " + id); return vendorService.patchVendor(id, vendorDto); } @ApiOperation(value = "Delete a vendor") @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.OK) public void deleteVendorById(@PathVariable Long id) { log.info("Deleting Vendor: " + id); vendorService.deleteVendorById(id); } }
package br.com.funcionario.system.controller; import java.net.URI; import java.util.List; import java.util.Optional; import javax.transaction.Transactional; 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 org.springframework.web.util.UriComponentsBuilder; import br.com.funcionario.system.controller.dto.DepartamentoDto; import br.com.funcionario.system.controller.form.DepartamentoForm; import br.com.funcionario.system.model.Departamento; import br.com.funcionario.system.repository.DepartamentoRepository; @RestController @RequestMapping("/departamento") public class DepartamentoController { @Autowired DepartamentoRepository repo; @PostMapping @Transactional public ResponseEntity<DepartamentoDto> cadastrar(@RequestBody DepartamentoForm form, UriComponentsBuilder uriBuilder) { Departamento departamento = form.converter(repo); repo.save(departamento); URI uri = uriBuilder.path("/departamento/{id}").buildAndExpand(departamento.getId()).toUri(); return ResponseEntity.created(uri).body(new DepartamentoDto(departamento)); } @DeleteMapping @Transactional public ResponseEntity<?> excluir(@PathVariable Long id) { Optional<Departamento> dep = repo.findById(id); if(dep.isPresent()) { repo.deleteById(id); return ResponseEntity.ok().build(); } return ResponseEntity.notFound().build(); } @GetMapping public List<DepartamentoDto> listar() { List<Departamento> departamentos; departamentos = repo.findAll(); return DepartamentoDto.converter(departamentos); } @PutMapping("/{id}") @Transactional public ResponseEntity<DepartamentoDto> alterar(@PathVariable Long id, @RequestBody DepartamentoForm form) { Optional<Departamento> optional = repo.findById(id); if(optional.isPresent()) { Departamento dep = form.atualizar(id, repo); return ResponseEntity.ok(new DepartamentoDto(dep)); } return ResponseEntity.notFound().build(); } }
package ua.kiev.doctorvera; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Locale; /** * Created by Bodun on 19.08.2014. */ public class SMS { private Integer id; private String phoneNumber; private String text; private Byte state; private Date dateSent; private Date dateChanged; private Long trackingId; private static final HashMap <String, Byte> possibleStates = new HashMap <String, Byte>(); public SMS() { setPossiblestates(); state = 1; } public static void setPossiblestates() { possibleStates.put("New",(byte)1); possibleStates.put("Template",(byte)2); possibleStates.put("Accepted",(byte)3); possibleStates.put("Enroute",(byte)3); possibleStates.put("Delivered",(byte)4); possibleStates.put("Expired",(byte)5); possibleStates.put("Deleted",(byte)5); possibleStates.put("Undeliverable",(byte)6); possibleStates.put("Rejected",(byte)6); possibleStates.put("Unknown",(byte)5); } public static HashMap<String, Byte> getPossiblestates() { return possibleStates; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Byte getState() { return state; } public void setState(Byte state) { this.state = state; } public Date getDateSent() { return dateSent; } public void setDateSent(Date dateSent) { this.dateSent = dateSent; } public Date getDateChanged() { return dateChanged; } public void setDateChanged(Date dateChanged) { this.dateChanged = dateChanged; } public Long getTrackingId() { return trackingId; } public void setTrackingId(Long trackingId) { this.trackingId = trackingId; } public void setStateString(String state) { this.state = possibleStates.get(state); } public String getStateString() { switch (this.state) { case 2: return "Черновик"; case 3: return "Отправлена"; case 4: return "Доставлена"; case 5: return "Ошибка доставки"; case 6: return "Ошибка отправки"; default: return "Новая"; } } @Override public String toString() { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.getDefault()); return phoneNumber + " " + text + " " + dateFormat.format(dateSent); } }
package com.wx.controller; import com.wx.service.RestService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestOperations; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.annotation.Resource; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.security.Principal; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * @author Ryan Heaton * @author Dave Syer */ @Controller public class IndexController { private RestService restService; @RequestMapping("/test") public String test() { RestOperations ro = restService.getRestTemplate(); InputStream photosXML = new ByteArrayInputStream(ro.getForObject( URI.create("http://localhost:8080/server/photos"), byte[].class)); final List<String> photoIds = new ArrayList<String>(); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setValidating(false); parserFactory.setXIncludeAware(false); parserFactory.setNamespaceAware(false); try { SAXParser parser = parserFactory.newSAXParser(); parser.parse(photosXML, new DefaultHandler() { @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("photo".equals(qName)) { photoIds.add(attributes.getValue("id")); } } }); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("_____________________________________________"); System.out.println(photoIds); System.out.println("_____________________________________________"); return "test"; } public RestService getRestService() { return restService; } @Resource public void setRestService(RestService restService) { this.restService = restService; } }
/* Name - Amritpal Singh Class - NYIT CSCI-860 Big Data Analysis Date - 02/27/2016 Last modified - 04-02-2016 Project Description - Implement a MapReduce program that is able to run by Hadoop on HDFS cluster or node. The program's function is to search for particular information in multiple files and process the information it finds. File name - InfoSearchDriver.java Driver Class Responsibility - The Driver class first checks the invocation of the command, It checks the count of the command-line arguments provided. It sets values for the job, including the driver, mapper, and reducer classes used. We also define the types for output key and value in the job as Text and FloatWritable respectively. */ import org.apache.hadoop.util.Tool; // https://hadoop.apache.org/docs/r2.4.1/api/org/apache/hadoop/util/Tool.html import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class InfoSearchDriver implements Tool { public static final String INP_TABLE_CONF = "custom.inp.table.file"; @Override public int run(String[] args) throws Exception { String inpDir = args[0]; // HDFS Input Directory Path String outDir = args[1]; // HDFS Output Directory Path int nmbOfReducers = Integer.parseInt(args[2]); // Also input value for number of reducers // Creates a new Job with no particular Cluster. // A Cluster will be created with a generic Configuration. Job job = Job.getInstance(); // Set the Jar by finding where a given class came from. job.setJarByClass(InfoSearchDriver.class); // Name the job so it will be easy to find in logs job.setJobName("InfoSearchDriver"); // Return the configuration for the job. Configuration config = job.getConfiguration(); config.set(INP_TABLE_CONF, inpDir); // Change the default key/value output separator by setting the property config.set("mapreduce.output.textoutputformat.separator", ":"); // Set input format and directory path FileInputFormat.addInputPath(job, new Path(inpDir)); // Set mapper and reduce classes for the mapreduce job job.setMapperClass(InfoSearchMapper.class); job.setReducerClass(InfoSearchReducer.class); // Set output format and directory path FileOutputFormat.setOutputPath(job, new Path(outDir)); // Set the key, value types expected as output from both the map and reduce phases job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); // Set number of reducers job.setNumReduceTasks(nmbOfReducers); // Execute job, wait for success or failure and return status return job.waitForCompletion(true) ? 0 : 1; } public static void main(String[] args) throws Exception { // Let ToolRunner handle generic command-line options int res = ToolRunner.run(new Configuration(), new InfoSearchDriver(), args); System.exit(res); } // setConf() and getConf() need to implemented if this driver class implements Tool. @Override public void setConf(Configuration conf) { // TODO Auto-generated method stub } @Override public Configuration getConf() { // TODO Auto-generated method stub return null; } }
package group.wnrcorp.com.navigationproject; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.TextView; import static android.content.Context.INPUT_METHOD_SERVICE; /** * A simple {@link Fragment} subclass. * Use the {@link FirstFragment1#newInstance} factory method to * create an instance of this fragment. */ public class FirstFragment1 extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; // TODO: Rename and change types of parameters private String mParam1; private String mParam2; EditText ed1,ed2; TextView submit_button; int first,second,add,sub,mul,div; InterfaceSolution addition; FirstFragment1 firstFragment1l; public FirstFragment1() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { addition = (InterfaceSolution)activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement DataPassListener"); } } public static FirstFragment1 newInstance(String param1, String param2) { FirstFragment1 fragment = new FirstFragment1(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View childview= inflater.inflate(R.layout.fragment_first_fragment1, container, false); firstFragment1l=this; ed1=(EditText) childview.findViewById(R.id.first_no); ed2=(EditText) childview.findViewById(R.id.second_no); submit_button=(TextView) childview.findViewById(R.id.submit); submit_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { first=Integer.parseInt(ed1.getText().toString()); second=Integer.parseInt(ed2.getText().toString()); add=first+second; sub=first-second; mul=first*second; div=first/second; System.out.println("fragmentCheck1..."+add); addition.sendAdditionData(add); addition.sendSubtractionData(sub); addition.sendMultiplicationData(mul); addition.senddivisionData(div); } }); return childview; } }
package com.qswy.app.utils; import android.app.ActivityManager; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import com.qswy.app.application.MyApplication; import java.util.List; /** * Created by ryl on 2016/11/1. * App相关工具类 */ public class AppUtils { /** * 获取App版本号 * * @param context 上下文 * @return App版本号 */ public static String getAppVersionName(Context context) { try { PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(MyApplication.CONTEXT.getPackageName(), 0); return pi == null ? null : pi.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return null; } } /** * 获取App版本码 * * @param context 上下文 * @return App版本码 */ public static int getAppVersionCode(Context context) { try { PackageManager pm = context.getPackageManager(); PackageInfo pi = pm.getPackageInfo(MyApplication.CONTEXT.getPackageName(), 0); return pi == null ? -1 : pi.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return -1; } } /** * 判断App是否处于前台 * * @param context 上下文 * @return {@code true}: 是<br>{@code false}: 否 */ public static boolean isAppForeground(Context context) { ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> infos = manager.getRunningAppProcesses(); if (infos == null || infos.size() == 0) return false; for (ActivityManager.RunningAppProcessInfo info : infos) { if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { return info.processName.equals(context.getPackageName()); } } return false; } }
package com.utils.util.wrapper; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data public class PageUtil { /** * The total row. 总条数 */ @ApiModelProperty(value = "总条数", name = "totalRow") private int totalRow; /** * The total page.总页数 */ @ApiModelProperty(value = "总页数", name = "totalPage") private int totalPage; /** * The start. 开始条数 */ @ApiModelProperty(value = "开始条数", name = "pageNum") private int pageNum; /** * The page size.每页条数 */ @ApiModelProperty(value = "每页条数", name = "pageSize") private int pageSize = 10; /** * Instantiates a new page util. */ public PageUtil(int total, int pageNum, int pageSize) { this.totalRow = total; this.pageNum = pageNum; this.pageSize = pageSize; this.totalPage = (total + pageSize - 1) / pageSize; } /** * Instantiates a new page util. * * @param pageNum the current page */ public PageUtil(int pageNum) { this.pageNum = pageNum; } /** * Instantiates a new page util. * * @param pageNum the current page * @param pageSize the page size */ public PageUtil(int pageNum, int pageSize) { this.pageNum = pageNum; this.pageSize = pageSize; } }
package gr.athena.innovation.fagi.specification; import java.util.HashMap; import java.util.Map; /** * Enumeration of RDF formats. * * @author nkarag */ public enum EnumRDFFormat { DEFAULT(0), NT(1), TTL(2), RDF(3), OWL(4), JSONLD(5), RJ(6), TRIG(7), TRIX(8), NQ(9); private final int value; private EnumRDFFormat(int value) { this.value = value; } public int getValue() { return this.value; } private static final Map<Integer, EnumRDFFormat> intToTypeMap = new HashMap<>(); static { for (EnumRDFFormat type : EnumRDFFormat.values()) { intToTypeMap.put(type.value, type); } } public static EnumRDFFormat fromInteger(int value) { EnumRDFFormat type = intToTypeMap.get(value); if (type == null) return EnumRDFFormat.DEFAULT; return type; } public static EnumRDFFormat fromString(String value) { for (EnumRDFFormat item : EnumRDFFormat.values()) { if (item.toString().equalsIgnoreCase(value)) { return item; } } return EnumRDFFormat.DEFAULT; } @Override public String toString() { switch(this) { case DEFAULT: return "NT"; case NT: return "NT"; case TTL: return "TTL"; case RDF: return "RDF"; case OWL: return "OWL"; case JSONLD: return "JSONLD"; case RJ: return "RJ"; case TRIG: return "TRIG"; case TRIX: return "TRIX"; case NQ: return "NQ"; default: return "NT"; } } }
package in.yuchengl.scoutui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.parse.ParseException; import com.parse.ParseUser; import com.parse.SignUpCallback; public class SignUpActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign_up); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void SignUp(View view) { EditText usernameText = (EditText) findViewById(R.id.username); EditText passwordText = (EditText) findViewById(R.id.password); EditText confirmText = (EditText) findViewById(R.id.confirmpassword); String username = usernameText.getText().toString(); String password = passwordText.getText().toString(); String confirm = confirmText.getText().toString(); if ((password.equals(confirm) && password.length() > 0) && (username.length() > 0)) { ParseUser user = new ParseUser(); user.setUsername(username); user.setPassword(password); user.signUpInBackground(new SignUpCallback() { @Override public void done(ParseException e) { if (e == null) { Toast.makeText(getApplicationContext(), "Signed up", Toast.LENGTH_SHORT).show(); Intent nextIntent = new Intent(getApplicationContext(), FriendListActivity.class); startActivity(nextIntent); } else { Toast.makeText(getApplicationContext(), e.getLocalizedMessage().toString(), Toast.LENGTH_SHORT).show(); } } }); } else { Toast.makeText(this, "Passwords must match, and all fields must not be empty", Toast.LENGTH_SHORT).show(); } } }
package com.ssgl.controller; /* * 功能:学生相关操作 * User: jiajunkang * email:jiajunkang@outlook.com * Date: 2017/12/30 0030 * Time: 23:53 */ import com.alibaba.fastjson.JSONObject; import com.ssgl.bean.Page; import com.ssgl.bean.Result; import com.ssgl.bean.Student; import com.ssgl.service.StudentService; import com.ssgl.util.FileUtils; import com.ssgl.util.StringUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller @RequestMapping("/student/") public class StudentController { @Autowired public StudentService studentService; @RequiresPermissions("managerStudent") @RequestMapping("managerStudent") public String managerStudent() { return "student"; } @RequiresPermissions("changeStudentRoom") @ResponseBody @RequestMapping(value = "changeStudentRoom") public Result changeStudentRoom(String ids) { try { return studentService.changeStudentRoom(ids); } catch (Exception e) { e.printStackTrace(); return new Result("error", "交换失败"); } } @RequiresPermissions("exportStudent") @RequestMapping(value = "exportStudent") public void exportStudent(HttpServletRequest request, HttpServletResponse response, String sid, String name, String sex, String age, String entranceTime, String graduateTime, String faculty, String roomNumber, String duty) { try { name = request.getParameter("name"); List<Student> students = studentService.exportStudent(request, response, sid, name, sex, age, entranceTime, graduateTime, faculty, roomNumber, duty); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFCellStyle cellStyle = workbook.createCellStyle(); HSSFSheet sheet = workbook.createSheet("学生信息表"); HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellValue("学生信息"); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); cell.setCellStyle(cellStyle); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 17)); HSSFRow r = sheet.createRow(1); r.createCell(0).setCellValue("主键"); r.createCell(1).setCellValue("学号"); r.createCell(2).setCellValue("学生姓名"); r.createCell(3).setCellValue("年龄"); r.createCell(4).setCellValue("性别"); r.createCell(5).setCellValue("毕业时间"); r.createCell(6).setCellValue("家庭联系电话"); r.createCell(7).setCellValue("入学时间"); r.createCell(8).setCellValue("是否是本科生"); r.createCell(9).setCellValue("是否是毕业生"); r.createCell(10).setCellValue("宿舍号"); r.createCell(11).setCellValue("楼号"); r.createCell(12).setCellValue("床号"); r.createCell(13).setCellValue("家庭住址"); r.createCell(14).setCellValue("手机号码"); r.createCell(15).setCellValue("职务"); r.createCell(16).setCellValue("院系"); r.createCell(17).setCellValue("照片"); for (Student student : students) { HSSFRow h = sheet.createRow(sheet.getLastRowNum() + 1); h.createCell(0).setCellValue(student.getId()); h.createCell(1).setCellValue(student.getSid()); h.createCell(2).setCellValue(student.getName()); h.createCell(3).setCellValue(student.getAge()); h.createCell(4).setCellValue(student.getSex()); h.createCell(5).setCellValue(student.getGraduateTime()); h.createCell(6).setCellValue(student.getHomePhone()); h.createCell(7).setCellValue(student.getEntranceTime()); h.createCell(8).setCellValue(student.getIsUndergraduate()); h.createCell(9).setCellValue(student.getIsGraduate()); h.createCell(10).setCellValue(student.getRoomNumber()); h.createCell(11).setCellValue(student.getDormitoryNo()); h.createCell(12).setCellValue(student.getBedNo()); h.createCell(13).setCellValue(student.getAddress()); h.createCell(14).setCellValue(student.getPhone()); h.createCell(15).setCellValue(student.getDuty()); h.createCell(16).setCellValue(student.getFaculty()); h.createCell(17).setCellValue(student.getIcon()); } ServletOutputStream out = response.getOutputStream(); response.setContentType("application/msexcel"); String agent = request.getHeader("User-Agent"); String filename = FileUtils.encodeDownloadFilename("学生信息表.xls", agent); response.setHeader("content-disposition", "attachment;filename=" + filename); workbook.write(out); out.flush(); } catch (Exception e) { throw new RuntimeException(e); } } @RequiresPermissions("selectStudentsPage") @ResponseBody @RequestMapping(value = "selectStudentsPage", produces = "text/json;charset=utf-8") public String selectStudentsPage(Integer page, Integer rows, HttpServletRequest request) { try { Page<Student> page1 = studentService.selectStudentsPage(page, rows, request); Map<String, Object> map = new HashMap<>(); if (null != page1) { map.put("total", page1.getTotalRecord()); map.put("rows", page1.getList()); return JSONObject.toJSONString(map); } return null; } catch (Exception e) { throw new RuntimeException(e); } } @RequiresPermissions("selectStudentInfo") @RequestMapping(value = "selectStudentInfo") public ModelAndView selectStudentInfo(String id) { try { Student student = studentService.selectStudentInfo(id); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("StudentInfo"); modelAndView.addObject("student", student); return modelAndView; } catch (Exception e) { throw new RuntimeException(e); } } @RequiresPermissions("updateStudent") @RequestMapping(value = "updateStudent") public String updateStudent( HttpServletRequest request,String id, String phone, String homePhone, String address, String bedNo, String dormitoryNo, String duty, String roomNumber, Integer age, HttpServletResponse response) { try { studentService.updateStudent(id, phone, homePhone, address, bedNo, dormitoryNo, duty, roomNumber, age); studentService.updateStudent(id,phone,homePhone,address,bedNo,dormitoryNo,duty,roomNumber,age); Page<Student> page = studentService.selectStudentsPage(1, 10, request); Map<String, Object> map = new HashMap<>(); if (null != page) { map.put("total", page.getTotalRecord()); map.put("rows", page.getList()); String s = JSONObject.toJSONString(map); response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(s); pw.flush(); pw.close(); return "student"; } return "student"; } catch (Exception e) { throw new RuntimeException(e); } } @RequiresPermissions("addStudent") @ResponseBody @RequestMapping(value = "addStudent") public Result addStudent(String sid, String name, Integer age, Boolean sex, Date graduateTime, String homePhone, String entranceTime, Boolean isUndergraduate, Boolean isGraduate, String roomNumber, String dormitoryNo, String bedNo, String province, String city, String county, String phone, String duty, String faculty, @RequestParam(value = "icon") MultipartFile icon) { try { return studentService.addStudent(sid, name, age, sex, graduateTime, homePhone, entranceTime, isUndergraduate, isGraduate, roomNumber, dormitoryNo, bedNo, province, city, county, phone, duty, faculty, icon); } catch (Exception e) { e.printStackTrace(); return new Result("error", "添加失败"); } } @RequiresPermissions("deleteStudent") @ResponseBody @RequestMapping(value = "deleteStudent") public Result deleteStudent(HttpServletRequest request){ try { return studentService.deleteStudent(StringUtils.stringConvertList(request.getParameter("ids"))); } catch (Exception e) { e.printStackTrace(); return new Result("error","删除失败"); } } @ResponseBody @RequestMapping(value = "checkStudentSid") public Boolean checkStudentSid(String sid){ Boolean aBoolean = studentService.checkStudentSid(sid); return aBoolean; } }
public class Driver { public static String displayPath(QCell[] path) { String ret = ""; if (path == null) { System.out.println("Incorrect return, Your path method should never return null. Make sure it returns an empty array if no path exists"); return ret; } if ( path.length == 0 ) { ret = "No path exists."; return ret; } else { for ( QCell c : path ) { String str = c.toString(); String [] strarr = str.split("o"); ret += (strarr[0]+"->"); } return ret; } } public static void main(String[] args) { String [] init = {"11011", "10001", "11011", "11000"}; int h = 4; int w = 5; int count = 0; String ret = ""; Maze m = new Maze (w, h, init); ret = m.toString(); if (ret.compareTo("11011\n10001\n11011\n11000")==0) { count++; System.out.println("Maze toString return SUCCESSFUL"); } else System.out.println("Maze toString return FAILED"); ret = ""; for (int row=0; row < h; row++) for (int col=0; col < w; col++) { QCell [] result = m.moves(col, row); int numMoves = result.length; ret += (Integer.toString(numMoves)+","); } if (ret.compareTo("2,1,2,1,2,2,3,0,3,2,3,2,2,1,2,2,2,1,1,1,")==0) { count++; System.out.println("Maze moves return SUCCESSFUL"); } else System.out.println("Maze moves return FAILED"); ret = displayPath(m.path(3, 0, 3, 0)); if (ret.compareTo("(3, 0) ->") == 0) { count++; System.out.println("Maze path return (when source is destination) SUCCESSFUL"); } else System.out.println("Maze path return (when source is destination) FAILED"); ret = displayPath(m.path(3, 0, 4, 3)); if (ret.compareTo("No path exists.") == 0) { count++; System.out.println("Maze path return (when no path exists) SUCCESSFUL"); } else System.out.println("Maze path return (when no path exists) FAILED"); ret = displayPath(m.path(0, 0, 3, 2)); if (ret.compareTo("No path exists.") == 0) { count++; System.out.println("Maze path return (when no path exists) SUCCESSFUL"); } else System.out.println("Maze path return (when no path exists) FAILED"); ret = displayPath(m.path(1, 0, 1, 2)); if (ret.compareTo("(1, 0) ->(0, 0) ->(0, 1) ->(0, 2) ->(1, 2) ->") == 0) { count++; System.out.println("Maze path return (when a path exists) SUCCESSFUL"); } else System.out.println("Maze path return (when a path exists) FAILED"); ret = displayPath(m.path(4, 0, 3, 2)); if (ret.compareTo("(4, 0) ->(4, 1) ->(4, 2) ->(3, 2) ->") == 0) { count++; System.out.println("Maze path return (when a path exists) SUCCESSFUL"); } else System.out.println("Maze path return (when a path exists) FAILED"); System.out.println(count+" out of 7 tests PASSED"); } }
package 문제풀이; import java.util.Scanner; public class 스트링 { public static void main(String[] args) { String[] s2 = {"java","jsp","srping"}; //s2[0] : 주소 //String 변수는 원래 주소가 들어가지만 // 내부적으로 그 주소가 가르키는 char들을 프린트되도록 조정이 되어있는 상태 String[] s = new String[3]; //배열 자동초기화 {null,null,null} Scanner sc = new Scanner(System.in); for (int i = 0; i < s.length; i++) { System.out.println("과목입력"); s[i] = sc.next(); } System.out.println(s[0] + "보다는 " + s[1]); sc.close(); } }
package problem02; public class Solution { /** * @author Jackid * JDK-version:1.8 * Problem:牛客网-剑指offer《替换空格》 * Result:已通过了所有的测试用例 */ /* 请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。 */ public String replaceSpace(StringBuffer str) { int old_length = str.length();// 字符串长度 int space_amount = 0;// 原字符串中空格的数量 for (char i : str.toString().toCharArray()) {// 遍历字符串,以获得空格的数量 if (i == ' ') { space_amount += 2; } } str.setLength(str.length() + space_amount);// 把str扩容为将空格替换成%20后的容量 int pre = old_length - 1;// 原字符串的最后一个字符的下标 int current = str.length() - 1;// 扩容后字符串的最后一个字符的下标 // 开始扫描!!! while (pre != current)// 当pre指针和current指针走不到一起时 { if (str.charAt(pre) != ' ') {// 当扫描到非空格的字符时 // 字符串current位置复制pre位置的字符,然后都向前走一步(后置减) str.setCharAt(current--, str.charAt(pre--)); } else {// 当扫描到空格时 // current指针连续替换成目标字符串"%20",每一次完成替换都向前走一步(后置减) str.setCharAt(current--, '0'); str.setCharAt(current--, '2'); str.setCharAt(current--, '%'); // 因为替换完成,所以pre往前一步 pre--; } } // 最后返回字符串 return str.toString(); } }
/////////////////////////////////////////////////////////////////////////////// // // Main Class File: Receiver.java // File: BrokenImageException.java // Semester: CS367 Data Structures Spring 2016 // // Author: David Liang dliang23@wisc.edu // CS Login: dliang // Lecturer's Name: Skrentny // ////////////////////////////////////////////////////////////////////////////// /** * This exception should be thrown whenever the received image buffer has any * broken part. * * @author zarcen (Wei-Chen Chen) */ public class BrokenImageException extends Exception { /** * Constructs a BrokenImageException with a message * * @param s * the error message */ public BrokenImageException(String s) { super(s); } /** * Constructs a BrokenImageException */ public BrokenImageException() { } }
package parsing_json; import com.google.gson.Gson; import com.google.gson.stream.JsonReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Arrays; /** * @TODO * The generate method in this class should load the JSON text (periodic_table.json) into * an ElementColletion (my period table array) * Then return the Collection (periodic table) */ public class ElementCollectionInitializer { public static ElementCollection generate() throws FileNotFoundException { Gson gson = new Gson(); //new gson object to convert from Json later JsonReader jsonReader = new JsonReader(new FileReader("/Users/kieranthomas/Dev/JavaAssessment3/src/main/resources/periodic_table.json")); //reader that reads my Json file ElementCollection periodicTable = new ElementCollection(); //new collection object Element[] table = gson.fromJson(jsonReader, Element[].class); //converting my gson to json and storing it in an element array periodicTable.addAll(Arrays.asList(table)); //adding my array as a list to my periodictable using the file that was read return periodicTable; //return the newly formatted json table as a list } } // ClassLoader classLoader = ClassLoader.getSystemClassLoader(); // File file = new File(classLoader.getResource(this.fileName).getFile()); // StringBuilder sb = new StringBuilder(""); // try (Scanner scanner = new Scanner(file)){ // while (scanner.hasNextLine()){ // String line = scanner.nextLine(); // sb.append(line).append("\n"); // } // scanner.close(); // }catch (IOException e){ // e.printStackTrace(); // } // return sb.toString();
package cloudserver; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /* * 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. */ /** * * @author Smith */ public class AppUser { Socket _s ; private String[] par = new String[Client.NUMofPAR]; public AppUser(UserInformation info) { this._s = info.getUserSocket(); } public void start() { DataInputStream inputs = null; DataOutputStream outs = null; try { inputs = new DataInputStream(_s.getInputStream()); outs = new DataOutputStream(this._s.getOutputStream()); } catch (IOException ex) { System.out.println(ex.toString()); } while(true) { try { String command = inputs.readUTF(); System.out.println(command); MissionType type = CommandParser.parse(command, par); UserTable usertable = CloudServer.userTable; ControllerSocketTable cstable = CloudServer.csTable; String returnCode=""; switch(type) { case USER_CHANGEPASSWORD: if(CloudServer.userTable.authenticate(par[0], par[1])) { returnCode = usertable.changePassword(par[0],par[2]); outs.writeUTF(returnCode); } else { outs.writeUTF("R007"); } break; case CONTROL_APPLIANCE: if(CloudServer.userTable.authenticate(par[0], par[1])) { Socket s = cstable.getControllerSocket(par[2]); if(s!=null) { returnCode = new Fowarder().send(command, s); outs.writeUTF(returnCode); } else { outs.writeUTF("R015"); } System.out.println("User: "+par[0]+" send command to MC: "+par[2]); } else { outs.writeUTF("R007"); } break; case ADD_MAINCONTROLLER: if(CloudServer.userTable.authenticate(par[0], par[1])) { Socket s = cstable.getControllerSocket(par[2]); if(s!=null) { try { CloudServer.userTable.AddMC(par[3],par[2]); outs.writeUTF("R005"); System.out.println("user: "+par[0]+" add MC: "+par[2]); } catch (Exception e) { outs.writeUTF("R006"); break; } } else { outs.writeUTF("R006"); } } else { outs.writeUTF("R007"); } break; case ADD_APPLIANCE: if(CloudServer.userTable.authenticate(par[0], par[1])) { Socket s = cstable.getControllerSocket(par[2]); if(s!=null) { try { new Fowarder().send(command,s); outs.writeUTF("R016"); System.out.println("user: "+par[0]+" add appliance: "+par[4]); } catch (Exception e) { System.out.println(e); outs.writeUTF("R017"); break; } } else { outs.writeUTF("R017"); } } else { outs.writeUTF("R007"); } break; case TIME_SETTING: if(CloudServer.userTable.authenticate(par[0], par[1])) { Socket _s = cstable.getControllerSocket(par[2]); try { new Fowarder().send(command, _s); outs.writeUTF("R016"); } catch(Exception ex) { System.out.println(ex); } } else { } break; case IR_CONTROL: Socket s = CloudServer.csTable.getControllerSocket("MC01"); //IRMC irmc = Client.irmc; command = par[0]+" "+par[1]; new Fowarder().send(command,s); outs.writeUTF("R018"); break; case None: outs.writeUTF("R999"); break; } } catch (IOException ex) { System.out.println(ex.toString()); break; } } } }
public class Publicacaow extends Publicacao{ private double taxaEntrega; public void calcularAnuidade(){ } public void calcularTaxaEntrega(){ } public void imprimirDados(){ } }
package com.tencent.mm.plugin.appbrand.wxawidget.console; import android.os.Bundle; import com.tencent.mm.ipcinvoker.d.e; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; class d$1 implements e { d$1() { } public final /* synthetic */ void at(Object obj) { Bundle bundle = (Bundle) obj; ArrayList parcelableArrayList = bundle.getParcelableArrayList("logList"); if (parcelableArrayList == null || parcelableArrayList.isEmpty()) { x.i("MicroMsg.ConsoleLogger", "logList is null or nil."); } else { d.b(bundle.getString("id"), parcelableArrayList); } } }
/* * 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 prepa4; import java.util.Scanner; /** * * @author Sony */ public class Aplicacion { private Equipo[] vec_equipo = new Equipo[2]; public Aplicacion(){ //CONSTRUCTOR VACÍO CrearEquipo(); } public void recorrerEquipo(){ for (int i = 0; i < vec_equipo.length; i++) { vec_equipo[i].MostrarEquipo(); } } public void CrearEquipo(){ Scanner sc = new Scanner(System.in); for (int i = 0; i < vec_equipo.length; i++) { System.out.println("Ingrese el nombre del equipo"); String nombre = sc.next(); vec_equipo[i] = new Equipo(nombre); vec_equipo[i].LlenarEquipo(); } } }
package com.paytechnologies.cloudacar; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class AlarmReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle extras =intent.getExtras(); String userId= extras.getString("locationTobeTake"); Log.d("cac", "Location to be tak ein receiver:"+userId); Intent notification = new Intent(context,AlarmService.class); notification.putExtra("locationTobeTake", userId); context.startService(notification); } }
package br.com.itau.dashboard.dao; import org.springframework.data.repository.CrudRepository; import br.com.itau.dashboard.model.Alarme; public interface AlarmeDAO extends CrudRepository<Alarme,Integer>{ }
package com.ibeiliao.pay.account.impl.service; import com.alibaba.dubbo.common.utils.NamedThreadFactory; import com.alibaba.fastjson.JSONObject; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.ibeiliao.pay.ServiceException; import com.ibeiliao.pay.account.api.dto.BankAccountPreEditVO; import com.ibeiliao.pay.account.api.dto.BankAccountTransLogVO; import com.ibeiliao.pay.account.api.dto.BankAccountVO; import com.ibeiliao.pay.account.api.dto.request.*; import com.ibeiliao.pay.account.api.enums.AccountType; import com.ibeiliao.pay.account.api.enums.BankAccountStatus; import com.ibeiliao.pay.account.api.enums.BankStatus; import com.ibeiliao.pay.account.api.enums.PreEditBankAccountStatus; import com.ibeiliao.pay.account.impl.Constants; import com.ibeiliao.pay.account.impl.dao.BankDao; import com.ibeiliao.pay.account.impl.dao.SchoolBankAccountDao; import com.ibeiliao.pay.account.impl.dao.SchoolBankAccountPreEditDao; import com.ibeiliao.pay.account.impl.dao.SchoolBankAccountTransLogDao; import com.ibeiliao.pay.account.impl.entity.BankPO; import com.ibeiliao.pay.account.impl.entity.SchoolBankAccountPO; import com.ibeiliao.pay.account.impl.entity.SchoolBankAccountPreEditPO; import com.ibeiliao.pay.account.impl.entity.SchoolBankAccountTransLogPO; import com.ibeiliao.pay.account.impl.utils.*; import com.ibeiliao.pay.api.ApiCode; import com.ibeiliao.pay.common.utils.*; import com.ibeiliao.pay.common.utils.encrypt.AESUtil; import com.ibeiliao.pay.idgen.api.dto.SingleId; import com.ibeiliao.pay.idgen.api.provider.IdGenProvider; import com.ibeiliao.platform.commons.utils.ParameterUtil; import com.ibeiliao.platform.context.PlatformContext; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 学校绑定银行卡业务类 * * @author jingyesi * @date 2016年7月19日 下午6:10:24 */ @Service public class BankAccountService { private static final Logger logger = LoggerFactory.getLogger(BankAccountService.class); @Autowired SchoolBankAccountDao bankAccountDao; @Autowired IdGenProvider idGenProvider; @Autowired BankDao bankDao; @Autowired SchoolBankAccountTransLogDao transLogDao; @Autowired SchoolBankAccountPreEditDao preEditDao; @Autowired private ThreadPoolTaskExecutor threadPoolTaskExecutor; /** * 绑定银行卡信息 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public long bindCard(BindCardRequest request) { logger.info("请求参数 | platformId:{}, schoolId:{}, clientIp:{}", PlatformContext.getContext().getPlatformId(), request.getSchoolId(), request.getClientIp()); // 验证 checkBindCardRequest(request); // 保存 try { SchoolBankAccountPO accountPO = saveBankAccount(request); //不保存操作日志 //发送邮件通知客服 sendEmailToService(); return accountPO.getAccountId(); } catch (Exception e) { logger.error(String.format("service#BankAccountService#bindCard | 绑定银行卡失败 msg:%s | request:%s", e.getMessage(), JsonUtil.toJSONString(request)), e); throw new ServiceException(ApiCode.FAILURE, String.format("绑定银行卡失败, msg:%s", e.getMessage())); } } /** * 根据学校id获取绑定的关键字隐藏的银行卡信息 * * @param schoolId * @return */ public BankAccountVO getHideBankAccountBySchoolId(long schoolId) { logger.info("请求参数 | platformId:{}, schoolId:{}", PlatformContext.getContext().getPlatformId(), schoolId); // 验证 SchoolBankAccountPO po = bankAccountDao.getBySchoolId(schoolId); if (po == null) { String tmp = "找不到绑定的银行卡"; logger.error("" + tmp + " | schoolId:{}", schoolId); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } // 转换po对象为 加密的vo对象 try { return convertBankAccountPO2EncryptVO(po); } catch (Exception e) { logger.error(String.format( "转换po对象为vo对象错误,msg:%s | schoolId:%d", e.getMessage(), schoolId), e); throw new ServiceException(ApiCode.FAILURE, "系统异常"); } } /** * 根据学校id获取绑定的字段透明的银行卡信息 * * @param schoolId * @return */ public BankAccountVO getTransBankAccountBySchoolId(long schoolId) { logger.info("请求参数 | platformId:{}, schoolId:{}", PlatformContext.getContext().getPlatformId(), schoolId); // 验证 SchoolBankAccountPO po = bankAccountDao.getBySchoolId(schoolId); if (po == null) { String tmp = "找不到绑定的银行卡"; logger.error("" + tmp + " | schoolId:{}", schoolId); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } // 转换po对象为 加密的vo对象 try { return convertBankAccountPO2TransVO(po); } catch (Exception e) { logger.error(String.format( "转换po对象为vo对象错误,msg:%s | schoolId:%d", e.getMessage(), schoolId), e); throw new ServiceException(ApiCode.FAILURE, "系统异常"); } } /** * 审核通过绑定的银行卡 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void auditPassBindCard(AuditPassBindCardRequest request) { ParameterUtil.assertNotNull(request, "AuditPassBindCardRequest 不能为空"); logger.info("service#BankAccountService#auditPassBindCard | 请求参数 | platformId:{}, accountId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("service#BankAccountService#auditPassBindCard | 参数不正确 | msg:{}, 请求参数, request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } // 验证 SchoolBankAccountPO po = bankAccountDao.get(request.getAccountId()); if (po == null) { String tmp = "审核通过银行卡失败, 找不到绑定的银行卡"; logger.error("service#BankAccountService#auditPassBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } //验证待审核状态, 才能通过 if (po.getStatus() != BankAccountStatus.AUDITING.getStatus()) { String tmp = "审核通过银行卡失败, 只有待审核状态才能被审核通过"; logger.error("service#BankAccountService#auditPassBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } // 更改状态 int rc = bankAccountDao.auditPass(request.getAccountId(), BankAccountStatus.PASS.getStatus(), request.getAuditOpUid(), request.getAuditOpName(), po.getStatus(), new Date()); if (rc < 1) { String tmp = "审核通过银行卡失败, 记录没有更改"; logger.error( "service#BankAccountService#auditPassBindCard | " + tmp + " | platformId:{}, accountlId:{}, status:{}, oldStatus:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId(), BankAccountStatus.PASS.getStatus(), po.getStatus()); throw new ServiceException(ApiCode.FAILURE, tmp); } //保存日志 saveBankAccountTansLog(po, "审核通过银行卡", request.getAuditOpUid(), request.getAuditOpName(), ""); } /** * 审核驳回绑定的银行卡 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void auditRejectBindCard(AuditRejectBindCardRequest request) { ParameterUtil.assertNotNull(request, "AuditRejectBindCardRequest 不能为空"); logger.info("service#BankAccountService#auditRejectBindCard | 请求参数 | platformId:{}, accountId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); // 验证 String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("service#BankAccountService#auditRejectBindCard | 参数不正确,msg:{}, 请求参数 | request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } SchoolBankAccountPO po = bankAccountDao.get(request.getAccountId()); if (po == null) { String tmp = "驳回绑定的银行卡失败, 找不到绑定的银行卡"; logger.error("service#BankAccountService#auditRejectBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } //验证待审核状态, 才能被驳回 if (po.getStatus() != BankAccountStatus.AUDITING.getStatus()) { String tmp = "驳回绑定的银行卡失败, 只有待审核状态才能被审核驳回"; logger.error("service#BankAccountService#auditPassBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } // 更改状态 int rc = bankAccountDao.auditReject(request.getAccountId(), BankAccountStatus.REJECT.getStatus(), request.getAuditComment(), request.getAuditOpUid(), request.getAuditOpName(), po.getStatus(), new Date()); if (rc < 1) { String tmp = "驳回绑定的银行卡失败, 记录没有更改"; logger.error( "service#BankAccountService#auditPassBindCard | " + tmp + " | platformId:{}, accountlId:{}, status:{}, oldStatus:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId(), BankAccountStatus.REJECT.getStatus(), po.getStatus()); throw new ServiceException(ApiCode.FAILURE, tmp); } //保存日志 saveBankAccountTansLog(po, "审核驳回银行卡", request.getAuditOpUid(), request.getAuditOpName(), ""); } /** * 审核通过预修改的银行卡 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void auditPassPreEditBindCard(AuditPassBindCardRequest request) { ParameterUtil.assertNotNull(request, "AuditPassBindCardRequest 不能为空"); logger.info("service#BankAccountService#auditPassPreEditBindCard | 请求参数 | platformId:{}, accountId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("service#BankAccountService#auditPassPreEditBindCard | 参数不正确,msg:{}, 请求参数 | request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } //检测 SchoolBankAccountPreEditPO po = preEditDao.get(request.getAccountId()); if (po == null) { String tmp = "审核通过预修改银行卡失败, 找不到预修改的银行卡"; logger.error("service#BankAccountService#auditPassPreEditBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } //待审核状态才能通过 if (po.getStatus() != PreEditBankAccountStatus.AUDITING.getStatus()) { String tmp = "审核通过预修改银行卡失败, 预修改银行不是待审核状态"; logger.error("service#BankAccountService#auditPassPreEditBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } //修改 bankAccount SchoolBankAccountPO orgPo = bankAccountDao.get(request.getAccountId()); if (po == null) { String tmp = "找不到绑定的银行卡"; logger.error("service#BankAccountService#auditPassPreEditBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } orgPo.setSchoolId(po.getSchoolId()); orgPo.setTrusteeName(po.getTrusteeName()); orgPo.setTrusteeIdcard(po.getTrusteeIdcard()); orgPo.setIdcardImg(po.getIdcardImg()); orgPo.setProtocolImg(po.getProtocolImg()); orgPo.setBusiLicenseImg(po.getBusiLicenseImg()); orgPo.setCardNo(po.getCardNo()); orgPo.setMobile(po.getMobile()); //审核通过 orgPo.setStatus(BankAccountStatus.PASS.getStatus()); orgPo.setBankId(po.getBankId()); orgPo.setBranchBankName(po.getBranchBankName()); orgPo.setBankCardOwner(po.getBankCardOwner()); orgPo.setSalt(new String(po.getSalt())); orgPo.setAuditOpUid(request.getAuditOpUid()); orgPo.setAuditOpName(request.getAuditOpName()); orgPo.setUpdateTime(new Date()); int rc = bankAccountDao.update(orgPo); if (rc < 1) { String tmp = "审核与修改银行卡失败, 记录没有更改"; logger.error("service#BankAccountService#auditPassPreEditBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } //删除预审核记录 rc = preEditDao.deleteById(request.getAccountId()); if (rc < 1) { String tmp = "审核与修改银行卡失败, 无法删除无效的记录"; logger.error("service#BankAccountService#auditPassPreEditBindCard | " + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } //记录日志 saveBankAccountTansLog(orgPo, "预修改银行卡审核通过", request.getAuditOpUid(), request.getAuditOpName(), ""); } /** * 修改银行卡信息 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void editBankAccount(EditBindCardRequest request) { ParameterUtil.assertNotNull(request, "EditBindCardRequest 不能为空"); logger.info("请求参数 | platformId:{}, accountId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); // 验证 SchoolBankAccountPO po = checkEditBindCardRequest(request); //若已审核通过的,不能直接修改 if (po.getStatus() == BankAccountStatus.PASS.getStatus()) { String tmp = "账号已审核通过,无法修改,若需要修改请联系客服"; logger.error("" + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } // 保存 try { int rc = saveEditBankAccount(request, po); if (rc < 1) { String tmp = "修改账号失败, 记录没有更改"; logger.error("" + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } //不保存银行卡修改记录 //发送邮件通知客服 sendEmailToService(); } catch (Exception e) { logger.error(String.format( "修改银行卡失败, msg:%s | platformId:%d, accountlId:%d", e.getMessage(), PlatformContext.getContext().getPlatformId(), request.getAccountId()), e); throw new ServiceException(ApiCode.FAILURE, "系统异常"); } } /** * 审核驳回预修改的银行卡 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void auditRejectPreEditBindCard(AuditRejectBindCardRequest request) { ParameterUtil.assertNotNull(request, "AuditRejectBindCardRequest 不能为空"); logger.info("请求参数 | platformId:{}, accountId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); // 验证 String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("参数不正确,msg:{}, 请求参数 | request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } SchoolBankAccountPreEditPO po = preEditDao.get(request.getAccountId()); if (po == null) { String tmp = "找不到预修改的银行卡"; logger.error("" + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } //验证状态 if (po.getStatus() != PreEditBankAccountStatus.AUDITING.getStatus()) { String tmp = "审核驳回预修改的银行卡失败, 预修改银行卡的状态不为带审核"; logger.error("" + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } // 更改状态 int rc = preEditDao.reject(request.getAccountId(), PreEditBankAccountStatus.REJECT.getStatus(), po.getStatus()); if (rc < 1) { String tmp = "审核驳回银行卡失败, 记录没有更改"; logger.error( "" + tmp + " | platformId:{}, accountlId:{}, status:{}, oldStatus:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId(), PreEditBankAccountStatus.REJECT.getStatus(), po.getStatus()); throw new ServiceException(ApiCode.FAILURE, tmp); } //保存日志 saveBankAccountTansLog(po, "审核驳回预修改银行卡", request.getAuditOpUid(), request.getAuditOpName(), "", request.getAuditComment(), ""); } /** * 预修改银行卡信息 * * @param request */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void preEditBankAccount(EditBindCardRequest request) { ParameterUtil.assertNotNull(request, "EditBankAccount 不能为空"); logger.info("请求参数 | platformId:{}, accountId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); // 验证 SchoolBankAccountPO po = checkEditBindCardRequest(request); //判读原始银行卡状态是否为通过审核 if (po.getStatus() != BankAccountStatus.PASS.getStatus()) { String tmp = "预修改银行卡信息失败, 只有通过审核的银行卡才能预修改"; logger.error("" + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } boolean isUpdate = true; SchoolBankAccountPreEditPO prePo = preEditDao.get(request.getAccountId()); if (prePo == null) { prePo = new SchoolBankAccountPreEditPO(); prePo.setAccountId(request.getAccountId()); prePo.setSalt(po.getSalt().getBytes()); prePo.setSchoolId(po.getSchoolId()); isUpdate = false; } // 保存 try { savePreEditBankAccount(request, prePo, isUpdate); //保存银行卡修改记录 saveBankAccountTansLog(prePo, "预修改银行卡信息", request.getOperatorUid(), request.getOperator(), request.getClientIp(), "", ""); } catch (Exception e) { logger.error(String.format( "预修改银行卡失败, msg:%s | platformId:%d, accountlId:%d", e.getMessage(), PlatformContext.getContext().getPlatformId(), request.getAccountId()), e); throw new ServiceException(ApiCode.FAILURE, "系统异常"); } } /** * 获取银行卡列表 , 更改时间倒序 * * @param trusteeName * @param status 必选 * @param pageNo * @param pageSize * @return */ public List<BankAccountVO> queryList(String trusteeName, BankAccountStatus status, int pageNo, int pageSize) { List<SchoolBankAccountPO> poList = bankAccountDao.queryListByTrusteeNameAndStatus(trusteeName, status.getStatus(), (pageNo - 1) * pageSize, pageSize); List<BankAccountVO> list = Lists.newArrayList(); if (CollectionUtils.isNotEmpty(poList)) { try { List<BankPO> bankList = bankDao.queryAllValidList(BankStatus.VALID.getStatus()); Map<Integer, String> bankIdMap = Maps.newHashMap(); for (BankPO po : bankList) { bankIdMap.put(po.getId(), po.getName()); } for (SchoolBankAccountPO po : poList) { BankAccountVO vo = new BankAccountVO(); VOUtil.copy(po, vo); String salt = po.getSalt(); vo.setTrusteeIdcard(AESUtil.decrypt(salt, po.getTrusteeIdcard())); vo.setCardNo(AESUtil.decrypt(salt, po.getCardNo())); vo.setMobile(AESUtil.decrypt(salt, po.getMobile())); vo.setIdcardImg(QiniuUtils.privateDownloadUrl(po.getIdcardImg())); vo.setProtocolImg(QiniuUtils.privateDownloadUrl(po.getProtocolImg())); vo.setBusiLicenseImg(QiniuUtils.privateDownloadUrl(po.getBusiLicenseImg())); vo.setStatus(BankAccountStatus.from(po.getStatus())); if (bankIdMap.containsKey(vo.getBankId())) { vo.setBankName(bankIdMap.get(vo.getBankId())); } vo.setAccountType(po.getAccountType()); list.add(vo); } } catch (Exception e) { String tmp = String.format("获取银行卡列表失败, msg:%s, trusteeName:%s, status:%d", e.getMessage(), trusteeName, status.getStatus()); logger.error(tmp, e); throw new ServiceException(ApiCode.FAILURE, tmp); } } return list; } /** * 获取银行卡总数 * * @param trusteeName * @param status 必填 * @return */ public int countBankAccountTotal(String trusteeName, BankAccountStatus status) { return bankAccountDao.countTotalByTrusteeNameAndStatus(trusteeName, status.getStatus()); } /** * 获取预修改银行卡列表, 创建时间倒序排序 * * @param status * @param pageNo * @param pageSize * @return */ public List<BankAccountPreEditVO> queryPreEditList(PreEditBankAccountStatus status, int pageNo, int pageSize) { List<BankAccountPreEditVO> list = Lists.newArrayList(); List<SchoolBankAccountPreEditPO> poList = preEditDao.queryListByStatus(status.getStatus(), (pageNo - 1) * pageSize, pageSize); if (CollectionUtils.isNotEmpty(poList)) { try { List<BankPO> bankList = bankDao.queryAllValidList(BankStatus.VALID.getStatus()); Map<Integer, String> bankIdMap = Maps.newHashMap(); for (BankPO po : bankList) { bankIdMap.put(po.getId(), po.getName()); } for (SchoolBankAccountPreEditPO po : poList) { BankAccountPreEditVO vo = new BankAccountPreEditVO(); VOUtil.copy(po, vo); String salt = new String(po.getSalt()); vo.setTrusteeIdcard(AESUtil.decrypt(salt, po.getTrusteeIdcard())); vo.setCardNo(AESUtil.decrypt(salt, po.getCardNo())); vo.setMobile(AESUtil.decrypt(salt, po.getMobile())); vo.setIdcardImg(QiniuUtils.privateDownloadUrl(po.getIdcardImg())); vo.setProtocolImg(QiniuUtils.privateDownloadUrl(po.getProtocolImg())); vo.setBusiLicenseImg(QiniuUtils.privateDownloadUrl(po.getBusiLicenseImg())); vo.setStatus(PreEditBankAccountStatus.from(po.getStatus())); if (bankIdMap.containsKey(vo.getBankId())) { vo.setBankName(bankIdMap.get(vo.getBankId())); } vo.setAccountType(po.getAccountType()); list.add(vo); } } catch (Exception e) { String tmp = String.format("service#BankAccountService#queryPreEditList | 获取预修改银行卡列表失败, msg:%s, status:%d", e.getMessage(), status.getStatus()); logger.error(tmp, e); throw new ServiceException(ApiCode.FAILURE, tmp); } } return list; } /** * 获取预修改银行卡总数 * * @param status * @return */ public int countPreEditTotalByStatus(PreEditBankAccountStatus status) { return preEditDao.countTotalByStatus(status.getStatus()); } /** * 获取预修改银行卡 (显示全字段) * * @param accountId * @return */ public BankAccountPreEditVO getTransPreEditBankAccount(long accountId) { ParameterUtil.assertTrue(accountId > 0, "银行卡id必须大于0"); SchoolBankAccountPreEditPO po = preEditDao.get(accountId); if (po == null) { logger.error("service#BankAccountService#getTransPreEditBankAccount | 找不到预修改银行卡, accountId:{} | ", accountId); throw new ServiceException(ApiCode.FAILURE, "找不到预修改银行卡"); } try { BankAccountPreEditVO vo = new BankAccountPreEditVO(); VOUtil.copy(po, vo); String salt = new String(po.getSalt()); vo.setTrusteeIdcard(AESUtil.decrypt(salt, po.getTrusteeIdcard())); vo.setCardNo(AESUtil.decrypt(salt, po.getCardNo())); vo.setMobile(AESUtil.decrypt(salt, po.getMobile())); vo.setIdcardImg(QiniuUtils.privateDownloadUrl(po.getIdcardImg())); vo.setProtocolImg(QiniuUtils.privateDownloadUrl(po.getProtocolImg())); vo.setBusiLicenseImg(QiniuUtils.privateDownloadUrl(po.getBusiLicenseImg())); vo.setStatus(PreEditBankAccountStatus.from(po.getStatus())); vo.setAccountType(po.getAccountType()); return vo; } catch (Exception e) { String tmp = String.format("service#BankAccountService#getTransPreEditBankAccount | 获取预修改银行卡失败, msg:%s, ", e.getMessage()); logger.error(tmp, e); throw new ServiceException(ApiCode.FAILURE, "获取预修改银行卡失败"); } } /** * 修改绑定的银行卡账户信息, 修复后状态会变成已审核 * 需要填入原始的银行卡账户, 并校验 * * @param request */ public void editBindCardByCheckOldCardNo(EditBindCardByCheckRequest request) { logger.info("修改账户信息 | request:{}", JsonUtil.toJSONString(request)); // 验证 SchoolBankAccountPO po = checkEditBindCardByCheckOldCardNo(request); try { po.setCardNo(AESUtil.encrypt(po.getSalt(), request.getNewCardNo())); }catch (Exception e){ logger.error("加密错误, " + e.getMessage(), e); throw new ServiceException(ApiCode.FAILURE, "加密错误"); } //保存 po.setBankId(request.getBankId()); po.setBranchBankName(request.getBranchBankName()); po.setBankCardOwner(request.getBankCardOwner()); po.setOperatorUid(request.getOperatorUid()); po.setOperator(request.getOperator()); po.setClientIp(request.getClientIp()); po.setStatus(BankAccountStatus.PASS.getStatus()); //全字段更新 bankAccountDao.update(po); //记录日志 saveBankAccountTansLog(po, "通过原始银行卡号码,修改账号信息", request.getOperatorUid(), request.getOperator(), request.getClientIp()); } /** * 校验修改绑定的银行卡 * @param request 请求 * @return 银行卡信息 */ private SchoolBankAccountPO checkEditBindCardByCheckOldCardNo(EditBindCardByCheckRequest request){ ParameterUtil.assertNotNull(request, "request 请求内容不能为空"); String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("参数不正确,msg:{}, 请求参数 | request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } SchoolBankAccountPO po = bankAccountDao.get(request.getAccountId()); if(po == null){ throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, "银行账户不存在"); } String oldEncryptCardNo = null; try { oldEncryptCardNo = AESUtil.encrypt(po.getSalt(), request.getOldCardNo().trim()); }catch (Exception e){ logger.error("机密银行卡错误, " + e.getMessage(), e); } if(!po.getCardNo().equals(oldEncryptCardNo)){ throw new ServiceException(ApiCode.OLD_BANK_CARDNO_INCORRECT, "原始银行卡号码不正确"); } if(po.getAccountType() != AccountType.CMB.getType()){ throw new ServiceException(ApiCode.FAILURE, "原始账户不为银行账号,不支持修改"); } return po; } /** * 检测验证 绑定银行卡参数是否正确 * * @param request */ private void checkBindCardRequest(BindCardRequest request) { ParameterUtil.assertNotNull(request, "参数BindCardRequest不能为空"); String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("参数不正确,msg:{}, 请求参数 | request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } // 验证身份证号码 if (!IdCardValidator.isValidatedAllIdcard(request.getTrusteeIdCard().trim())) { String tmp = "身份证号码格式不正确"; logger.error( "" + tmp + " | schoolId:{}, certificateNo:{}", request.getSchoolId(), request.getTrusteeIdCard()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } //当账户类型为空时,默认使用一网通账户类型, 并校验银行/银行卡号码 if (request.getAccountType() == null || request.getAccountType().shortValue() == AccountType.CMB.getType()) { ParameterUtil.assertTrue(request.getBankId() > 0, "银行必须大于0"); ParameterUtil.assertTrue(StringUtils.isNotEmpty(request.getBranchBankName()), "支行名称不能为空"); ParameterUtil.assertTrue(request.getBranchBankName().length() <= 45, "支行名称字符串长度不能多于45位"); ParameterUtil.assertTrue(StringUtils.isNotEmpty(request.getBankCardOwner()), "银行卡开户名字不能为空"); ParameterUtil.assertTrue(request.getBankCardOwner().length() <= 40, "银行卡开户名字字符串长度不能多于40位"); // 验证银行卡号码 if (!request.getCardNo().trim().matches("^\\d*$") || !Validator.isBankCard(request.getCardNo().trim())) { // String tmp = "银行卡号码格式不正确"; String tmp = "请输入24位数字以内的有效银行卡号"; logger.error("" + tmp + " | schoolId:{}, cardNo:{}", request.getSchoolId(), request.getCardNo()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } //验证银行 BankPO bank = bankDao.get(request.getBankId()); if (bank == null) { String tmp = "找不到银行信息"; logger.error("" + tmp + " | schoolId:{}, mobile:{}, bankId:{}", request.getSchoolId(), request.getMobile(), request.getBankId()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } //不验证银行的状态 } //校验是否京东账户 else if (request.getAccountType() != AccountType.JD.getType()) { String tmp = "账户类型不正确, 仅支持一网通/京东钱包"; logger.error("" + tmp + " | schoolId:{}, accountType:{} cardNo:{}", request.getSchoolId(), request.getAccountType(), request.getCardNo()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } // 验证手机号码 if (!Validator.isMobile(request.getMobile().trim())) { String tmp = "手机号码格式不正确"; logger.error("" + tmp + " | schoolId:{}, mobile:{}", request.getSchoolId(), request.getMobile()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } SchoolBankAccountPO po = bankAccountDao.getBySchoolId(request.getSchoolId()); if (po != null) { String tmp = "已绑定过银行,无法再次绑定"; logger.error("" + tmp + " | schoolId:{}", request.getSchoolId()); throw new ServiceException(ApiCode.BANK_CARD_HAD_BIND, tmp); } } /** * 保存绑定的银行卡信息 * * @param request * @return * @throws Exception */ private SchoolBankAccountPO saveBankAccount(BindCardRequest request) throws Exception { logger.info("service#BankAccountService#saveBankAccount | 请求参数 | platformId:{}, schoolId:{}, clientIp:{}", PlatformContext.getContext().getPlatformId(), request.getSchoolId(), request.getClientIp()); SchoolBankAccountPO po = new SchoolBankAccountPO(); //获取随机加密字符串 String salt = RandomUtil.random(RandomUtil.TYPE_ALL_MIXED, 10, null); po.setSchoolId(request.getSchoolId()); po.setTrusteeName(request.getTrusteeName().trim()); // 保存加密身份证 po.setTrusteeIdcard(AESUtil.encrypt(salt, request.getTrusteeIdCard())); po.setIdcardImg(request.getIdCardImg()); po.setProtocolImg(request.getProtocolImg()); po.setBusiLicenseImg(request.getBusiLicenseImg()); // 保存加密银行卡 po.setCardNo(AESUtil.encrypt(salt, request.getCardNo().trim())); // 保存加密手机号码 po.setMobile(AESUtil.encrypt(salt, request.getMobile().trim())); po.setStatus(BankAccountStatus.AUDITING.getStatus()); po.setOperatorUid(request.getOperatorUid()); po.setOperator(request.getOperator()); po.setClientIp(request.getClientIp()); po.setCreateTime(new Date()); po.setUpdateTime(new Date()); po.setRemark(""); po.setAuditComment(""); po.setSalt(salt); //没有传入账号类型时,默认为一网通账户 if (request.getAccountType() == null || request.getAccountType() == AccountType.CMB.getType()) { po.setAccountType(AccountType.CMB.getType()); po.setBankId(request.getBankId()); po.setBranchBankName(request.getBranchBankName()); po.setAuditOpName(""); po.setBankCardOwner(request.getBankCardOwner()); } else { po.setAccountType(request.getAccountType()); po.setBankId(0); po.setBranchBankName(""); po.setAuditOpName(""); po.setBankCardOwner(""); } SingleId singleId = idGenProvider.next(Constants.TABLE_SCHOOL_BANK_ACCOUNT_PK); if (singleId.getCode() == ApiCode.SUCCESS) { po.setAccountId(singleId.getId()); bankAccountDao.insert(po); return po; } else { throw new ServiceException(singleId.getCode(), singleId.getMessage()); } } /** * 转换 po 对象为隐藏关键字段的vo对象 * * @param po * @return */ private BankAccountVO convertBankAccountPO2EncryptVO(SchoolBankAccountPO po) throws Exception { String salt = po.getSalt(); BankAccountVO vo = new BankAccountVO(); vo.setAccountId(po.getAccountId()); vo.setSchoolId(po.getSchoolId()); vo.setTrusteeName(po.getTrusteeName()); // 身份证隐藏关键位 String trusteeIdcard = AESUtil.decrypt(salt, po.getTrusteeIdcard()); vo.setTrusteeIdcard(StringUtil.hideIdCardStr(trusteeIdcard)); // 还原有效图片地址 String idCardImg = po.getIdcardImg(); vo.setIdcardImg(QiniuUtils.privateDownloadUrl(idCardImg)); String protocalImg = po.getProtocolImg(); vo.setProtocolImg(QiniuUtils.privateDownloadUrl(protocalImg)); String busiLicenseImg = po.getBusiLicenseImg(); vo.setBusiLicenseImg(QiniuUtils.privateDownloadUrl(busiLicenseImg)); // 银行卡隐藏 String cardNo = AESUtil.decrypt(salt, po.getCardNo()); vo.setCardNo(StringUtil.hideBankCard(cardNo)); // 手机号码隐藏 String mobile = AESUtil.decrypt(salt, po.getMobile()); vo.setMobile(StringUtil.hideMobile(mobile)); vo.setStatus(BankAccountStatus.from(po.getStatus())); vo.setOperator(po.getOperator()); vo.setOperatorUid(po.getOperatorUid()); vo.setClientIp(po.getClientIp()); vo.setCreateTime(po.getCreateTime()); vo.setUpdateTime(po.getUpdateTime()); vo.setRemark(po.getRemark()); vo.setAuditComment(po.getAuditComment()); vo.setBankId(po.getBankId()); vo.setBranchBankName(po.getBranchBankName()); //获取银行名称 BankPO bankPo = bankDao.get(po.getBankId()); if (bankPo != null) { vo.setBankName(bankPo.getName()); } else { vo.setBankName(""); } vo.setBankCardOwner(po.getBankCardOwner()); vo.setAccountType(po.getAccountType()); return vo; } /** * 转换 po 对象为透明信息的vo对象 * * @param po * @return */ private BankAccountVO convertBankAccountPO2TransVO(SchoolBankAccountPO po) throws Exception { String salt = po.getSalt(); BankAccountVO vo = new BankAccountVO(); vo.setAccountId(po.getAccountId()); vo.setSchoolId(po.getSchoolId()); vo.setTrusteeName(po.getTrusteeName()); // 身份证隐藏关键位 String trusteeIdcard = AESUtil.decrypt(salt, po.getTrusteeIdcard()); vo.setTrusteeIdcard(trusteeIdcard); // 还原有效图片地址 String idCardImg = po.getIdcardImg(); vo.setIdcardImg(QiniuUtils.privateDownloadUrl(idCardImg)); String protocalImg = po.getProtocolImg(); vo.setProtocolImg(QiniuUtils.privateDownloadUrl(protocalImg)); String busiLicenseImg = po.getBusiLicenseImg(); vo.setBusiLicenseImg(QiniuUtils.privateDownloadUrl(busiLicenseImg)); // 银行卡隐藏 String cardNo = AESUtil.decrypt(salt, po.getCardNo()); vo.setCardNo(cardNo); // 手机号码隐藏 String mobile = AESUtil.decrypt(salt, po.getMobile()); vo.setMobile(mobile); vo.setStatus(BankAccountStatus.from(po.getStatus())); vo.setOperator(po.getOperator()); vo.setOperatorUid(po.getOperatorUid()); vo.setClientIp(po.getClientIp()); vo.setCreateTime(po.getCreateTime()); vo.setUpdateTime(po.getUpdateTime()); vo.setRemark(po.getRemark()); vo.setAuditComment(po.getAuditComment()); vo.setBankId(po.getBankId()); vo.setBranchBankName(po.getBranchBankName()); //获取银行名称 BankPO bankPo = bankDao.get(po.getBankId()); if (bankPo != null) { vo.setBankName(bankPo.getName()); } else { vo.setBankName(""); } vo.setBankCardOwner(po.getBankCardOwner()); vo.setAccountType(po.getAccountType()); return vo; } /** * 检测验证 修改绑定银行卡参数是否正确 * * @param request */ private SchoolBankAccountPO checkEditBindCardRequest(EditBindCardRequest request) { ParameterUtil.assertNotNull(request, "参数EditBindCardRequest不能为空"); String message = ApiParamCheckUtil.checkParam(request); if (message != null) { logger.error("参数不正确,msg:{}, 请求参数 | request:{}", message, JsonUtil.toJSONString(request)); throw new ServiceException(ApiCode.PARAMETER_ERROR, message); } //当账户类型为空时,默认使用一网通账户类型, 并校验银行/银行卡号码 if (request.getAccountType() == null || request.getAccountType().shortValue() == AccountType.CMB.getType()) { ParameterUtil.assertTrue(request.getBankId() > 0, "银行必须大于0"); ParameterUtil.assertTrue(StringUtils.isNotEmpty(request.getBranchBankName()), "支行名称不能为空"); ParameterUtil.assertTrue(request.getBranchBankName().length() <= 45, "支行名称字符串长度不能多于45位"); ParameterUtil.assertTrue(StringUtils.isNotEmpty(request.getBankCardOwner()), "银行卡开户名字不能为空"); ParameterUtil.assertTrue(request.getBankCardOwner().length() <= 40, "银行卡开户名字字符串长度不能多于40位"); // 验证银行卡号码 if (!request.getCardNo().trim().matches("^\\d*$") || !Validator.isBankCard(request.getCardNo().trim())) { // String tmp = "银行卡号码格式不正确"; String tmp = "请输入24位数字以内的有效银行卡号"; logger.error("" + tmp + " | accountId:{}, cardNo:{}", request.getAccountId(), request.getCardNo()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } //验证银行 BankPO bank = bankDao.get(request.getBankId()); if (bank == null) { String tmp = "找不到银行信息"; logger.error("" + tmp + " | accountId:{}, mobile:{}, bankId:{}", request.getAccountId(), request.getMobile(), request.getBankId()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } //不验证银行的状态 } //校验是否京东账户 else if (request.getAccountType() != AccountType.JD.getType()) { String tmp = "账户类型不正确, 仅支持一网通/京东钱包"; logger.error("" + tmp + " | accountId:{}, accountType:{} cardNo:{}", request.getAccountId(), request.getAccountType(), request.getCardNo()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } // 验证手机号码 if (!Validator.isMobile(request.getMobile().trim())) { String tmp = "手机号码格式不正确"; logger.error("" + tmp + " | accountId:{}, mobile:{}", request.getAccountId(), request.getMobile()); throw new ServiceException(ApiCode.PARAMETER_ERROR, tmp); } SchoolBankAccountPO po = bankAccountDao.get(request.getAccountId()); if (po == null) { String tmp = "找不到绑定的银行卡"; logger.error("" + tmp + " | accountId:{}", request.getAccountId()); throw new ServiceException(ApiCode.BANK_CARD_NOT_FOUND, tmp); } return po; } /** * 保存修改的绑定的银行卡信息 * * @param request */ private int saveEditBankAccount(EditBindCardRequest request, SchoolBankAccountPO po) throws Exception { logger.info("请求参数 | platformId:{}, accountId:{}, clientIp:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId(), request.getClientIp()); String salt = po.getSalt(); po.setTrusteeName(request.getTrusteeName().trim()); // 保存加密身份证 po.setTrusteeIdcard(AESUtil.encrypt(salt, request.getTrusteeIdCard())); po.setIdcardImg(request.getIdCardImg()); po.setProtocolImg(request.getProtocolImg()); po.setBusiLicenseImg(request.getBusiLicenseImg()); // 保存加密银行卡 po.setCardNo(AESUtil.encrypt(salt, request.getCardNo().trim())); // 保存加密手机号码 po.setMobile(AESUtil.encrypt(salt, request.getMobile().trim())); // 状态变成重新审核 po.setStatus(BankAccountStatus.AUDITING.getStatus()); po.setOperatorUid(request.getOperatorUid()); po.setOperator(request.getOperator()); po.setClientIp(request.getClientIp()); po.setUpdateTime(new Date()); if (request.getAccountType() == null || request.getAccountType().shortValue() == AccountType.CMB.getType()) { po.setAccountType(AccountType.CMB.getType()); po.setBankId(request.getBankId()); po.setBranchBankName(request.getBranchBankName()); po.setBankCardOwner(request.getBankCardOwner()); } else { po.setAccountType(request.getAccountType()); po.setBankId(0); po.setBranchBankName(""); po.setBankCardOwner(""); } return bankAccountDao.update(po); } /** * 保存预修改的绑定的银行卡信息 * * @param request * @param po * @param isUpdate * @throws Exception */ private void savePreEditBankAccount(EditBindCardRequest request, SchoolBankAccountPreEditPO po, boolean isUpdate) throws Exception { logger.info("请求参数 | platformId:{}, accountId:{}, clientIp:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId(), request.getClientIp()); String salt = new String(po.getSalt()); po.setTrusteeName(request.getTrusteeName().trim()); // 保存加密身份证 po.setTrusteeIdcard(AESUtil.encrypt(salt, request.getTrusteeIdCard())); po.setIdcardImg(request.getIdCardImg()); po.setProtocolImg(request.getProtocolImg()); po.setBusiLicenseImg(request.getBusiLicenseImg()); // 保存加密银行卡 po.setCardNo(AESUtil.encrypt(salt, request.getCardNo().trim())); // 保存加密手机号码 po.setMobile(AESUtil.encrypt(salt, request.getMobile().trim())); // 状态变成重新审核 po.setStatus(PreEditBankAccountStatus.AUDITING.getStatus()); po.setOperatorUid(request.getOperatorUid()); po.setOperator(request.getOperator()); po.setCreateTime(new Date()); po.setAccountType(request.getAccountType()); if (request.getAccountType() == AccountType.CMB.getType()) { po.setBankId(request.getBankId()); po.setBankCardOwner(request.getBankCardOwner()); po.setBranchBankName(request.getBranchBankName()); } else { po.setBankId(0); po.setBankCardOwner(""); po.setBranchBankName(""); } if (isUpdate) { int rc = preEditDao.update(po); if (rc < 1) { String tmp = "预修改银行卡失败, 记录没有更改"; logger.error("" + tmp + " | platformId:{}, accountlId:{}", PlatformContext.getContext().getPlatformId(), request.getAccountId()); throw new ServiceException(ApiCode.FAILURE, tmp); } } else { preEditDao.insert(po); } } /** * 保存银行卡绑定操作日志记录 * * @param po 银行卡 * @param content 操作描述 * @param operatorUid 操作人id * @param operator 操作人名字 * @param operatorIp 操作人ip */ private void saveBankAccountTansLog(SchoolBankAccountPO po, String content, long operatorUid, String operator, String operatorIp) { SchoolBankAccountTransLogPO logPo = new SchoolBankAccountTransLogPO(); BankAccountTransLogVO vo = new BankAccountTransLogVO(); logPo.setAccountId(po.getAccountId()); VOUtil.copy(po, vo); //更改操作人信息 vo.setOperatorUid(operatorUid); vo.setOperator(operator); vo.setClientIp(operatorIp); logPo.setAccountId(po.getAccountId()); logPo.setContent(content); logPo.setCreateTime(new Date()); logPo.setJson(JSONObject.toJSONString(vo)); transLogDao.insert(logPo); } /** * 保存银行卡绑定操作日志记录 * * @param po 银行卡 * @param content 操作描述 * @param operatorUid 操作人id * @param operator 操作人名字 * @param operatorIp 操作人ip */ private void saveBankAccountTansLog(SchoolBankAccountPreEditPO po, String content, long operatorUid, String operator, String operatorIp, String auditComment, String remark) { SchoolBankAccountTransLogPO logPo = new SchoolBankAccountTransLogPO(); BankAccountTransLogVO vo = new BankAccountTransLogVO(); SchoolBankAccountPO orgBA = bankAccountDao.get(po.getAccountId()); logPo.setAccountId(po.getAccountId()); VOUtil.copy(orgBA, vo); vo.setAuditComment(auditComment); vo.setRemark(remark); //更改操作人信息 vo.setOperatorUid(operatorUid); vo.setOperator(operator); vo.setClientIp(operatorIp); logPo.setAccountId(po.getAccountId()); logPo.setContent(content); logPo.setCreateTime(new Date()); logPo.setJson(JSONObject.toJSONString(vo)); transLogDao.insert(logPo); } /** * 发送邮件通知客服绑定银行卡有更改 */ private void sendEmailToService() { threadPoolTaskExecutor.submit(new Runnable() { @Override public void run() { try { EmailBuilder.sendByDefault("学校绑定银行卡通知", "有用户修改了银行卡信息,需要您审核一下哦O(∩_∩)O~"); } catch (Exception e) { logger.error("发送绑定银行卡更改通知信息给客服失败 | msg:{}", e.getMessage(), e); } } }); } }
//import java.util.*; public class Card { private String value; private char suit; private String output = ""; public Card(int value, char suit) { //kijkt eerst of de kaart naar een A K Q of J moet veranderd worden en voegt daarna de kaart definitief toe intToString(suit, value); setCard(output, suit); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public char getSuit() { return suit; } public void setSuit(char suit) { this.suit = suit; } public void setCard(String output2, char suit) { this.value = output2; this.suit = suit; } public String intToString(char suit, int value){ //dit zorgt ervoor dat een 1 een aas word 11 koning 12 koningin 13 boer. switch (value){ case 1 : output = "A"; break; case 11 : output = "K"; break; case 12 : output = "Q"; break; case 13 : output = "J"; break; default : output = "" + value; } return output; } public String toString(){ return suit + "" + value; } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.ArbeitsvorgangTypType; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BONDALIstdatenType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; public class BONDALIstdatenTypeBuilder { public static String marshal(BONDALIstdatenType bONDALIstdatenType) throws JAXBException { JAXBElement<BONDALIstdatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), BONDALIstdatenType.class , bONDALIstdatenType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private ArbeitsvorgangTypType arbeitsvorgang; private String aggregat; private XMLGregorianCalendar zeitpunktDurchsatz; public BONDALIstdatenTypeBuilder setArbeitsvorgang(ArbeitsvorgangTypType value) { this.arbeitsvorgang = value; return this; } public BONDALIstdatenTypeBuilder setAggregat(String value) { this.aggregat = value; return this; } public BONDALIstdatenTypeBuilder setZeitpunktDurchsatz(XMLGregorianCalendar value) { this.zeitpunktDurchsatz = value; return this; } public BONDALIstdatenType build() { BONDALIstdatenType result = new BONDALIstdatenType(); result.setArbeitsvorgang(arbeitsvorgang); result.setAggregat(aggregat); result.setZeitpunktDurchsatz(zeitpunktDurchsatz); return result; } }
package com.gg.example.springExample.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import com.gg.example.springExample.model.Owner; import com.gg.example.springExample.model.Person; import com.gg.example.springExample.model.Pet; import com.gg.example.springExample.model.Vet; import com.gg.example.springExample.model.Visit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; @Repository public class PetClinicDaoJdbcImpl implements PetClinicDao { @Autowired private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public PetClinicDaoJdbcImpl(){ System.out.println("PetClinicDaoJdbcImpl created"); } @Override public Collection<Vet> getVets() { return jdbcTemplate.query("SELECT p.FIRST_NAME, p.LAST_NAME, p.ID FROM PERSONS AS p JOIN VETS ON VETS.ID = p.ID", new RowMapper<Vet>() { @Override public Vet mapRow(ResultSet resultSet, int i) throws SQLException { Vet vet = new Vet(); vet.setId(resultSet.getLong("id")); vet.setFirstName(resultSet.getString("FIRST_NAME")); vet.setLastName(resultSet.getString("LAST_NAME")); return vet; } }); } @Override public Collection<Owner> findOwners(String lastName) { return Collections.EMPTY_LIST; } @Override public Collection<Visit> findVisits(long petId) { return Collections.EMPTY_LIST; } @Override public Collection<Person> findAllPersons() { return Collections.EMPTY_LIST; } @Override public Owner loadOwner(long id) { return null; } @Override public Pet loadPet(long id) { return null; } @Override public Vet loadVet(long id) { return null; } @Override public void saveOwner(Owner owner) { } @Override public void saveVet(Vet vet) { } @Override public void deleteOwner(long ownerId) { } }
package com.findthewaygame.mygdx.game; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public class WhiteCharacter { public int RealX; public int RealY; public int Speed; private Texture WhiteCircle = new Texture("WhiteCircle.png"); public DrawMap Map; private GameRunning Game; private SpriteBatch DrawPlayer = new SpriteBatch(); public WhiteCharacter(int StartX, int StartY, DrawMap Map, GameRunning Game) { this.Map = Map; this.Game = Game; this.Speed = this.Game.NormalSpeed; this.RealX = StartX*this.Map.SizeBlock; this.RealY = StartY*this.Map.SizeBlock; } public void DrawPicture() { DrawPlayer.begin(); DrawPlayer.draw(WhiteCircle,RealX,RealY); if(this.Game.CheckMap.ReadMap(this.RealX+(this.Map.SizeBlock/2), this.RealY+(this.Map.SizeBlock/2))==9) { this.Game.GameStatus = "YouWin"; this.Game.Main.StateGame = "GameResult"; this.Game.DataMap.dispose(); this.Game.Main.create(); } DrawPlayer.end(); } }
package com.yougou.merchant.api.supplier.vo; import java.util.Date; import org.apache.commons.lang.builder.ToStringBuilder; import com.yougou.merchant.api.common.UUIDGenerator; public class MerchantContractUpdateHistory { private String id; private String operator; private Date operationTime; private String processing; private String updateField; private String updateBefore; private String updateAfter; private String contractNo; private String remark; private String type; private String supplierId; public MerchantContractUpdateHistory(){ this.id = UUIDGenerator.getUUID(); this.operationTime = new Date(); } public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator == null ? null : operator.trim(); } public Date getOperationTime() { return operationTime; } public void setOperationTime(Date operationTime) { this.operationTime = operationTime; } public String getProcessing() { return processing; } public void setProcessing(String processing) { this.processing = processing == null ? null : processing.trim(); } public String getUpdateField() { return updateField; } public void setUpdateField(String updateField) { this.updateField = updateField == null ? null : updateField.trim(); } public String getUpdateBefore() { return updateBefore; } public void setUpdateBefore(String updateBefore) { this.updateBefore = updateBefore == null ? null : updateBefore.trim(); } public String getUpdateAfter() { return updateAfter; } public void setUpdateAfter(String updateAfter) { this.updateAfter = updateAfter == null ? null : updateAfter.trim(); } public String getContractNo() { return contractNo; } public void setContractNo(String contractNo) { this.contractNo = contractNo == null ? null : contractNo.trim(); } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public String getType() { return type; } public void setType(String type) { this.type = type == null ? null : type.trim(); } public String getSupplierId() { return supplierId; } public void setSupplierId(String supplierId) { this.supplierId = supplierId; } public String toString() { return ToStringBuilder.reflectionToString(this); } /** * 操作类型 * * @author yang.mq * */ public static enum ProcessingType { CREATE_CONTRACT("创建合同"),BUSINESS_AUDIT("业务审核合同"),BUSINESS_AUDIT_MERCHANT("业务审核商家"),RENEW_MERCHANT("商家续签创建合同"), UPDATE_RENEW_MERCHANT("商家续签修改合同"), FINANCE_AUDIT("财务审核合同"),FINANCE_AUDIT_MERCHANT("财务审核商家"),CONTRACT_EXPIRE("合同时间到期"),CONTRACT_EFFECTIVE("合同生效"), BUSINESS_EFFECTIVE("业务已生效"),SUBMIT_FINANCE("提交财务审核"),CREATE_SUBMIT("创建并提交财务审核"), USER_STARTUP("商家启用"),USER_STOP("商家停用"),RECALL_AUDIT("撤销审核"); private String description; private ProcessingType(String description) { this.description = description; } public String getDescription() { return description; } } }
package com.smelending.kotak; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import org.jpos.iso.ISOUtil; public class writeIntoFile { private static Logger logger = Logger.getLogger(writeIntoFile.class); public static void writeIntoFile(String location,List list){ logger.info("inside :writeIntoFile() method"); String content=null; for (Iterator iterator = list.iterator(); iterator.hasNext();) { content = (String) iterator.next(); logger.info("line size : "+content.length()); logger.info(ISOUtil.hexString(content.getBytes())); /*content=content.replace('\r','\n' ); content=content+"\n";*/ content=content; BufferedWriter writer = null; try { //file location with file name writer = new BufferedWriter(new FileWriter(location,true)); } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } try { logger.info("content : "+content); writer.write(content) ; //writer.append("\r\n"); /*byte []b=new byte[1]; b[0]=0x0D; writer.write(new String(b))*/ ; } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } try { writer.close(); } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } } } public static void writeIntoFilewithColon(String location,List list){ logger.info("inside :writeIntoFilewithColon() method"); String content=null; for (Iterator iterator = list.iterator(); iterator.hasNext();) { content = (String) iterator.next()+";"; BufferedWriter writer = null; try { //file location with file name writer = new BufferedWriter(new FileWriter(location,true)); } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } try { writer.write(content) ; } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } try { writer.close() ; } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } } } public static void writeIntoFileWithoutAppend(String location,StringBuffer dataContent){ logger.info("inside :writeIntoFileWithoutAppend() method"); String content=dataContent.toString(); logger.info("content : "+content); BufferedWriter writer = null; try { //file location with file name writer = new BufferedWriter(new FileWriter(location,false)); } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } try { writer.write(content) ; } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } try { writer.close() ; } catch (IOException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } } public static void main(String[] args) { // TODO Auto-generated method stub String str="\n"; logger.info(ISOUtil.hexString(str.getBytes())); } }
package lab3; public class String_To_Int_Test { public static void main(String[] args){ int x = 42; String s = "" + x; String s2 = "42"; int x2 = Integer.parseInt(s2); String s3 = "Hello"; int x3 = Integer.parseInt(s3); } }
package com.goldgov.dygl.module.partymember.service; import java.util.List; import java.util.Map; import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException; import com.goldgov.gtiles.module.businessfield.service.BusinessField; public interface IPartyMemberService_BA { public void addInfo(Map<String,Object> paramMap,String partyMemberID) throws NoAuthorizedFieldException; public void updateInfo(String entityID,Map<String,Object> paramMap) throws NoAuthorizedFieldException; public void deleteInfo(String[] entityIDs) throws NoAuthorizedFieldException; public List<BusinessField> findInfoById(String entityID) throws NoAuthorizedFieldException; public List<Map<String, Object>> findInfoList(PartyMemberQuery query,Map<String,Object> paramMap) throws NoAuthorizedFieldException; public List<BusinessField> preAddInfo() throws NoAuthorizedFieldException; public PartyMemberQuery findInfoPartyMenberByID(String partyMemberID) throws NoAuthorizedFieldException; }
package main; import java.io.*; import java.util.*; import main.GreenhouseControls; import tme3.Controller.ControllerException; class Restore { String filename = ""; public Restore(String filename) { this.filename = filename; } public void display() throws IOException, ClassNotFoundException, ControllerException { try { ObjectInputStream i = new ObjectInputStream(new FileInputStream(new File(filename))); GreenhouseControls g = (GreenhouseControls) i.readObject(); System.out.println("Restore error" + g.getError()); i.close(); // g.errorCode = 0; g.getFixable(g.getError()); System.out.println("##################" + g.endTime); long elapsedTime = System.currentTimeMillis() - g.endTime; Fixable fx = g.getFixable(g.getError()); System.out.println(fx); fx.fix(); fx.log(); System.out.println(g.errorCode); g.run(elapsedTime); System.exit(0); } catch (IOException f) { System.out.println(f); } } }
package chatterby.ui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Logger; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import chatterby.messages.Message; import chatterby.network.MessageManager; import chatterby.network.PayloadConsumer; /** * Top-level GUI component. * * @author scoleman * @version 1.0.0 * @since 1.0.0 */ public class ChatterbyFrame extends JFrame implements PayloadConsumer { private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger.getLogger(ChatterbyFrame.class.getName()); private final MessageManager manager; private final ReentrantLock messagesLock = new ReentrantLock(); private DefaultListModel<String> usernames = new DefaultListModel<>(); private JTextPane messagePane; private JTextField messageField; private JButton sendButton; private JList<String> knownUsernames; private JTextField usernameField; private SimpleDateFormat sendDateFormat; private SimpleAttributeSet sendDateAttributeSet; private SimpleAttributeSet usernameAttributeSet; public ChatterbyFrame(MessageManager manager) { this.manager = manager; this.setTitle("Chatterby"); this.setMinimumSize(new Dimension(768, 512)); this.initLayout(); this.initMessageComponents(); } private void initLayout() { /* Layout management */ JPanel content = new JPanel(); content.setLayout(new GridBagLayout()); this.setContentPane(content); GridBagConstraints c = new GridBagConstraints(); /* Incoming messages */ messagePane = new JTextPane(); messagePane.setEditable(false); c.gridx = 0; c.gridy = 0; c.gridheight = 2; c.gridwidth = 3; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; this.add(new JScrollPane(messagePane), c); /* User message */ messageField = new JTextField(0); messageField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ChatterbyFrame.this.sendMessage(); } }); c.gridx = 1; c.gridy = 2; c.gridheight = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.weighty = 0.0; this.add(messageField, c); /* Send button */ sendButton = new JButton("Send"); sendButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ChatterbyFrame.this.sendMessage(); } }); c.gridx = 2; c.gridy = 2; c.gridheight = 1; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; c.weightx = 0.0; c.weighty = 0.0; this.add(sendButton, c); /* Username list */ knownUsernames = new JList<String>(this.usernames); c.gridx = 3; c.gridy = 0; c.gridheight = 2; c.gridwidth = 1; c.fill = GridBagConstraints.BOTH; c.weightx = 0.0; c.weighty = 0.0; this.add(new JScrollPane(knownUsernames), c); /* Username */ usernameField = new JTextField("Chatterby User"); c.gridx = 3; c.gridy = 2; c.gridheight = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 0.0; c.weighty = 0.0; this.add(usernameField, c); } private void initMessageComponents() { this.sendDateFormat = new SimpleDateFormat("h:mm:ss a"); this.sendDateAttributeSet = new SimpleAttributeSet(); StyleConstants.setFontSize(this.sendDateAttributeSet, (int) (StyleConstants.getFontSize(this.sendDateAttributeSet) * .75)); this.usernameAttributeSet = new SimpleAttributeSet(); StyleConstants.setBold(this.usernameAttributeSet, true); SimpleAttributeSet noteAttributeSet = new SimpleAttributeSet(); StyleConstants.setItalic(noteAttributeSet, true); StyleConstants.setForeground(noteAttributeSet, Color.GRAY); try { this.messagePane.getDocument().insertString(0, "Welcome to Chatterby!\n", noteAttributeSet); } catch (BadLocationException e) { } } @Override public void consume(Message message) { this.messagesLock.lock(); if (!this.usernames.contains(message.getUsername())) this.usernames.addElement(message.getUsername()); this.appendMessage(message); this.messagesLock.unlock(); } /** * Send out a message or parse a command. * * @param message the user message */ private void sendMessage() { String message = messageField.getText(); if (message.length() == 0) return; messageField.setText(""); try { this.manager.send(new Message(usernameField.getText(), null, message)); } catch (InterruptedException e) { LOGGER.warning("Failed to send message."); } } private void appendMessage(Message message) { StyledDocument doc = messagePane.getStyledDocument(); StyleConstants.setForeground(this.usernameAttributeSet, Colorizer.colorize(message.getUsername())); try { doc.insertString(doc.getLength(), this.sendDateFormat.format(message.getSendDate()) + "\t", this.sendDateAttributeSet); doc.insertString(doc.getLength(), message.getUsername() + ":", this.usernameAttributeSet); doc.insertString(doc.getLength(), " " + message.getMessage() + "\n", null); } catch (BadLocationException e) { /* Because we're inserting at the end of the document as indicated * by the document itself, we will (presumably) never try to insert * at a bad location. */ } messagePane.setCaretPosition(messagePane.getDocument().getLength()); } }
package com.test; import com.service.impl.LenderUserServiceImpl; import org.junit.Test; import java.util.List; public class LenderUserImplTest { @Test public void getListTest(){ LenderUserServiceImpl lenderUser = new LenderUserServiceImpl(); List admin = lenderUser.getLender("admin"); System.out.println(admin); } }
public class Point { int x; int y; Point(int x,int y){ this.x=x; this.y=y; } int getX(){ return x; } int getY() { return y; } }
public class BloomFilter { private int[] bloomFilter = new int[10]; private final int m = 3; public int HashOne(int value){ return value - 1 % m; } public int HashTwo(int value){ return value * 5 % m; } public void add(int value){ int hashOneValue = HashOne(value); int hashTwoValue = HashTwo(value); if (bloomFilter[hashOneValue] == 0){ bloomFilter[hashOneValue] = 1; } if (bloomFilter[hashTwoValue] == 0){ bloomFilter[hashTwoValue] = 1; } } public String check(int value){ int hashOneValue = HashOne(value); int hashTwoValue = HashTwo(value); if (bloomFilter[hashOneValue] == 0 || bloomFilter[hashTwoValue] == 0){ return value + " was NOT present"; } return value + " was PROBABLY present"; } }
package frc.robot.controls; public class Controls { // Contoller mappings: // Buttons : // (A) button : 1 public static final int A_BUTTON = 1; // (B) button : 2 public static final int B_BUTTON = 2; // (X) button : 3 public static final int X_BUTTON = 3; // (Y) button : 4 public static final int Y_BUTTON = 4; // left bumper : 5 public static final int LEFT_BUMPER = 5; // right bumper : 6 public static final int RIGHT_BUMPER = 6; // back : 7 (?) // right stick : 10 // Axis : // Left stick : // X axis : 0 public static final int XAXIS_LEFT = 0; // Y axis : 1 public static final int YAXIS_LEFT = 1; // Right stick : // X axis : 4 public static final int XAXIS_RIGHT = 4; // Y axis : 5 public static final int YAXIS_RIGHT = 5; // Left trigger : 2 public static final int LEFT_TRIGGER = 2; // Right trigger : 3 public static final int RIGHT_TRIGGER = 3; // // Controls for the driver and operator // Driver controls public static final int DRIVE_SPEED_AXIS = 1;//unused public static final int DRIVE_TURN_AXIS = 0;//unused public static final int DRIVE_HIGHGEAR = A_BUTTON; public static final int DRIVE_SLOW = B_BUTTON; public static final int GTA_ACCEL = RIGHT_TRIGGER; public static final int GTA_DECCEL = LEFT_TRIGGER; public static final int HEADING_BUTTON = X_BUTTON; public static final int LIMELIGHT_BUTTON = Y_BUTTON; public static final int SENSITIVITY = 3; // Operator // TODO Leave this empty for now (Sarah and I will fill this out on our own) public static final int INTAKE_UP = 5; // DPAD down public static final int INTAKE_DOWN = 0; //DPAD up public static final int INTAKE_INTAKE = LEFT_BUMPER; public static final int SHOOT = RIGHT_BUMPER; public static final int LOWGOAL_SHOOT = B_BUTTON; public static final int LOAD_BALL = RIGHT_TRIGGER; public static final int MAGAZINE = Y_BUTTON; public static final int MAGAZINE_UNJAM = A_BUTTON; // public static final int SLIDE_UP = 0; // public static final int WINCH = 0; // public static final int CONTPANE_UP = 5; // public static final int CONTPANE_SPIN = 7; }
import javax.swing.*; import java.util.*; import java.util.concurrent.ConcurrentLinkedDeque; public class OrderBook { String productName; private TreeMap<Integer,ConcurrentLinkedDeque<Order>> orderBook = new TreeMap<>(); private int topBid = -1; private int bottomOffer = 0; private HashSet<Order> ordersSet = new HashSet<>(); private FrontEndOrderBook frontEnd = new FrontEndOrderBook(); private OrderBook(String productName){ this.productName = productName; JFrame frame = new JFrame(productName); frame.setContentPane(frontEnd.getOverviewPanel()); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static OrderBook generateOrderBook(String productName){ return new OrderBook(productName); } //place a bid in the orderbook public synchronized void bid(Order order){ if(order.getPrice() > bottomOffer && bottomOffer > 0){ JOptionPane.showMessageDialog(new JFrame(), "Invalid price. Crossing offer"); return; } if(orderBook.containsKey(order.getPrice())){ orderBook.get(order.getPrice()).add(order); } else{ orderBook.put(order.getPrice(), new ConcurrentLinkedDeque<>(Arrays.asList(order))); } if(order.getPrice() >= topBid){ topBid = order.getPrice(); updateBidInformation(); } ordersSet.add(order); } //place an offer in the orderbook public synchronized void offer(Order order){ if(order.getPrice() < topBid){ JOptionPane.showMessageDialog(new JFrame(), "Invalid price. Crossing bid"); return; } if(orderBook.containsKey(order.getPrice())){ orderBook.get(order.getPrice()).add(order); } else{ orderBook.put(order.getPrice(), new ConcurrentLinkedDeque<>(Arrays.asList(order))); } if(order.getPrice() <= bottomOffer || bottomOffer == 0){ bottomOffer = order.getPrice(); updateOfferInformation(); } ordersSet.add(order); } //hit the best bid public synchronized int hit(){ int toReturn = 0; if(topBid == -1){ return toReturn; } else{ updateTicker("Hit",topBid,orderBook.get(topBid).peek().getSize()); toReturn = orderBook.get(topBid).poll().getSize(); if(orderBook.get(topBid).isEmpty()){ if(orderBook.lowerKey(topBid) == null){ orderBook.remove(topBid); topBid = -1; } else{ orderBook.remove(topBid); topBid = orderBook.firstKey(); } } updateBidInformation(); return toReturn; } } //hit "size" number of lots, at most the depth of the bid stack public int hit(int size){ int toFill = size; if(topBid == -1){ return toFill; } else{ while(toFill > 0 && orderBook.get(topBid) != null){ if(toFill >= orderBook.get(topBid).peek().getSize()){ toFill = toFill - this.hit(); } else{ Order tempOrder = Order.generateOrder(topBid,orderBook.get(topBid).peek().getSize() - toFill,orderBook.get(topBid).peek().getOrderID()); updateTicker("Hit",topBid,toFill); orderBook.get(topBid).removeFirst(); orderBook.get(topBid).addFirst(tempOrder); updateBidInformation(); return 0; } } } updateBidInformation(); return toFill; } //lift the best offer public synchronized int lift(){ int toReturn = 0; if(bottomOffer == 0){ return toReturn; } else{ updateTicker("Lift",bottomOffer,orderBook.get(bottomOffer).peek().getSize()); toReturn = orderBook.get(bottomOffer).poll().getSize(); if(orderBook.get(bottomOffer).isEmpty()){ if(orderBook.higherKey(bottomOffer) == null){ orderBook.remove(bottomOffer); bottomOffer = 0; } else{ orderBook.remove(bottomOffer); bottomOffer = orderBook.lastKey(); } } updateOfferInformation(); return toReturn; } } //lift "size" number of lots, at most the depth of the offer stack public int lift(int size){ int toFill = size; if(bottomOffer == 0){ return toFill; } else{ while(toFill > 0 && orderBook.get(bottomOffer) != null){ if(toFill >= orderBook.get(bottomOffer).peek().getSize()){ toFill = toFill - this.lift(); } else{ Order tempOrder = Order.generateOrder(bottomOffer,orderBook.get(bottomOffer).peek().getSize() - toFill,orderBook.get(bottomOffer).peek().getOrderID()); updateTicker("Lift",bottomOffer,toFill); orderBook.get(bottomOffer).removeFirst(); orderBook.get(bottomOffer).addFirst(tempOrder); updateOfferInformation(); return 0; } } } updateOfferInformation(); return toFill; } //used by traders to remove outstanding bids/offers public synchronized void removeBidOrder(Order order){ if(ordersSet.contains(order)){ orderBook.get(order.getPrice()).remove(order); ordersSet.remove(order); if(orderBook.get(order.getPrice()).isEmpty()){ if(orderBook.lowerKey(topBid) == null){ topBid = -1; } else { topBid = orderBook.lowerKey(topBid); } orderBook.remove(order.getPrice()); } } updateBidInformation(); } public synchronized void removeOfferOrder(Order order){ if(ordersSet.contains(order)){ orderBook.get(order.getPrice()).remove(order); ordersSet.remove(order); if(orderBook.get(order.getPrice()).isEmpty()){ if(orderBook.higherKey(bottomOffer) == null){ bottomOffer = 0; } else { bottomOffer = orderBook.higherKey(bottomOffer); } orderBook.remove(order.getPrice()); } } updateOfferInformation(); } public int sizeAtBid(){ int sizeAtBid = 0; for(Order order : orderBook.get(topBid)){ sizeAtBid += order.getSize(); } return sizeAtBid; } public int sizeAtOffer(){ int sizeAtOffer = 0; for(Order order : orderBook.get(bottomOffer)){ sizeAtOffer += order.getSize(); } return sizeAtOffer; } public void updateBidInformation() { if (topBid == -1) { frontEnd.getBidPriceMarket().setText(" "); frontEnd.getRemainingBidAtPrice().setText(" "); frontEnd.getBidSizeMarket().setText(" "); } else { frontEnd.getBidPriceMarket().setText(Integer.toString(topBid)); frontEnd.getRemainingBidAtPrice().setText(Integer.toString(sizeAtBid())); frontEnd.getBidSizeMarket().setText(Integer.toString(orderBook.get(topBid).peek().getSize())); } } public void updateOfferInformation() { if (bottomOffer == 0) { frontEnd.getOfferPriceMarket().setText(" "); frontEnd.getRemainingOfferAtPrice().setText(" "); frontEnd.getOfferSizeMarket().setText(" "); } else { frontEnd.getOfferPriceMarket().setText(Integer.toString(bottomOffer)); frontEnd.getRemainingOfferAtPrice().setText(Integer.toString(sizeAtOffer())); frontEnd.getOfferSizeMarket().setText(Integer.toString(orderBook.get(bottomOffer).peek().getSize())); } } public void updateTicker(String direction, int price, int size){ Calendar timeKeeper = new GregorianCalendar(); frontEnd.getTicker().append(direction + ": " + size + " @ " + price + " - Time: " + timeKeeper.get(Calendar.HOUR) + ":" + timeKeeper.get(Calendar.MINUTE) + ":" + timeKeeper.get(Calendar.SECOND) + "\n"); } public synchronized void showOrderBook(){ System.out.println(orderBook); } public synchronized int getTopBid() { return topBid; } public synchronized int getBottomOffer() { return bottomOffer; } }
/* * Sonar, open source software quality management tool. * Copyright (C) 2009 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.timeline.client; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.json.client.JSONValue; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.ui.*; import com.google.gwt.visualization.client.AbstractDataTable.ColumnType; import com.google.gwt.visualization.client.DataTable; import com.google.gwt.visualization.client.VisualizationUtils; import com.google.gwt.visualization.client.visualizations.AnnotatedTimeLine; import com.google.gwt.visualization.client.visualizations.AnnotatedTimeLine.Options; import com.google.gwt.visualization.client.visualizations.AnnotatedTimeLine.ScaleType; import org.sonar.api.web.gwt.client.widgets.LoadingLabel; import org.sonar.gwt.JsonUtils; import org.sonar.gwt.ui.Page; import org.sonar.wsclient.gwt.AbstractCallback; import org.sonar.wsclient.gwt.AbstractListCallback; import org.sonar.wsclient.gwt.Sonar; import org.sonar.wsclient.services.*; import java.util.*; public class GwtTimeline extends Page { public static final String GWT_ID = "org.sonar.plugins.timeline.GwtTimeline"; public static final List<String> SUPPORTED_METRIC_TYPES = Arrays.asList("INT", "FLOAT", "PERCENT", "MILLISEC"); public static final int DEFAULT_HEIGHT = 480; public static final String DEFAULT_METRICS_KEY = "sonar.timeline.defaultmetrics"; public static final String DEFAULT_METRICS_VALUE = "ncloc,violations_density,coverage"; private SortedSet<Metric> metrics = null; private String[] defaultMetrics = null; private ListBox metricsListBox1 = new ListBox(); private ListBox metricsListBox2 = new ListBox(); private ListBox metricsListBox3 = new ListBox(); private List<ListBox> metricsListBoxes = null; private CheckBox singleScaleCheckBox = new CheckBox("Single scale"); private SimplePanel tlPanel = null; private VerticalPanel panel; private Map<String, Metric> loadedMetrics = new HashMap<String, Metric>(); private Resource resource; private DataTable dataTable; @Override protected Widget doOnResourceLoad(Resource resource) { panel = new VerticalPanel(); panel.add(new LoadingLabel()); this.resource = resource; load(); return panel; } private void load() { Sonar.getInstance().find(PropertyQuery.createForKey(DEFAULT_METRICS_KEY), new AbstractCallback<Property>() { @Override protected void doOnResponse(Property result) { defaultMetrics = result.getValue().split(","); loadMetrics(); } @Override protected void doOnError(int errorCode, String errorMessage) { defaultMetrics = DEFAULT_METRICS_VALUE.split(","); loadMetrics(); } }); } private void loadMetrics() { Sonar.getInstance().findAll(MetricQuery.all(), new AbstractListCallback<Metric>() { @Override protected void doOnResponse(List<Metric> result) { for (Metric metric : result) { if (isSupported(metric)) { loadedMetrics.put(metric.getKey(), metric); } } metrics = filterAndOrderMetrics(result); metricsListBoxes = Arrays.asList(metricsListBox1, metricsListBox2, metricsListBox3); loadListBox(metricsListBox1, defaultMetrics.length > 0 ? defaultMetrics[0] : null); loadListBox(metricsListBox2, defaultMetrics.length > 1 ? defaultMetrics[1] : null); loadListBox(metricsListBox3, defaultMetrics.length > 2 ? defaultMetrics[2] : null); ChangeHandler metricSelection = new ChangeHandler() { public void onChange(ChangeEvent event) { if (!allMetricsUnSelected() && !sameMetricsSelection()) { loadTimeline(); } } }; for (ListBox metricLb : metricsListBoxes) { metricLb.addChangeHandler(metricSelection); } singleScaleCheckBox.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { renderDataTable(dataTable); } }); loadVisualizationApi(); } private void loadListBox(ListBox metricsLb, String selectedKey) { metricsLb.setStyleName("small"); metricsLb.addItem("<none>", ""); int index = 1; for (Metric metric : metrics) { metricsLb.addItem(metric.getName(), metric.getKey()); if (selectedKey != null && metric.getKey().equals(selectedKey.trim())) { metricsLb.setSelectedIndex(index); } index++; } } private Boolean allMetricsUnSelected() { for (ListBox metricLb : metricsListBoxes) { if (getSelectedMetric(metricLb) != null) { return false; } } return true; } private boolean sameMetricsSelection() { List<Metric> selected = new ArrayList<Metric>(); for (ListBox metricLb : metricsListBoxes) { Metric metric = getSelectedMetric(metricLb); if (metric != null) { if (selected.contains(metric)) { return true; } selected.add(metric); } } return false; } }); } private void loadVisualizationApi() { Runnable onLoadCallback = new Runnable() { public void run() { render(); loadTimeline(); } }; VisualizationUtils.loadVisualizationApi(onLoadCallback, AnnotatedTimeLine.PACKAGE); } private static SortedSet<Metric> filterAndOrderMetrics(Collection<Metric> metrics) { TreeSet<Metric> ordered = new TreeSet<Metric>(new Comparator<Metric>() { public int compare(Metric o1, Metric o2) { return o1.getName().compareTo(o2.getName()); } }); for (Metric metric : metrics) { if (isSupported(metric)) { ordered.add(metric); } } return ordered; } private static boolean isSupported(Metric metric) { return SUPPORTED_METRIC_TYPES.contains(metric.getType()) && !metric.getHidden(); } private void loadTimeline() { lockMetricsList(true); tlPanel.clear(); tlPanel.add(new LoadingLabel()); new TimelineLoader(resource.getKey(), getSelectedMetrics()) { @Override void noData() { renderNoData(); } @Override void data(String[] metrics, TimeMachine timemachine, List<Event> events) { dataTable = getDataTable(metrics, timemachine, events); renderDataTable(dataTable); } }; } private void renderDataTable(DataTable table) { if (table != null && table.getNumberOfRows() > 0) { Element content = DOM.getElementById("content"); int width = content.getClientWidth() > 0 ? content.getClientWidth() : 800; Widget toRender = new AnnotatedTimeLine(table, createOptions(), width + "px", GwtTimeline.DEFAULT_HEIGHT + "px"); renderTimeline(toRender); } else { renderNoData(); } } private void renderNoData() { renderTimeline(new HTML("<p>No data</p>")); } private void renderTimeline(Widget toRender) { lockMetricsList(false); tlPanel.clear(); tlPanel.add(toRender); } private DataTable getDataTable(String[] metrics, TimeMachine timeMachine, List<Event> events) { DataTable table = DataTable.create(); table.addColumn(ColumnType.DATE, "d", "Date"); for (String metric : metrics) { table.addColumn(ColumnType.NUMBER, loadedMetrics.get(metric).getName(), metric); } table.addColumn(ColumnType.STRING, "e", "Event"); for (TimeMachineCell cell : timeMachine.getCells()) { int rowIndex = table.addRow(); table.setValue(rowIndex, 0, cell.getDate()); for (int i = 0; i < metrics.length; i++) { Double value = JsonUtils.getAsDouble((JSONValue) cell.getValues()[i]); if (value != null) { table.setValue(rowIndex, i + 1, value); } } } for (Event event : events) { int rowIndex = table.addRow(); String eventStr = event.getName(); if (event.getDescription() != null) { eventStr += " : " + event.getDescription(); } table.setValue(rowIndex, 0, event.getDate()); table.setValue(rowIndex, metrics.length + 1, eventStr); } return table; } private void lockMetricsList(boolean locked) { for (ListBox metricLb : metricsListBoxes) { metricLb.setEnabled(!locked); } } private String[] getSelectedMetrics() { List<String> metrics = new ArrayList<String>(); for (ListBox metricLb : metricsListBoxes) { Metric metric = getSelectedMetric(metricLb); if (metric != null) { // inverting metrics metrics.add(0, metric.getKey()); } } return metrics.toArray(new String[metrics.size()]); } private Metric getSelectedMetric(ListBox metricsLb) { String selected = metricsLb.getValue(metricsLb.getSelectedIndex()); return selected.length() > 0 ? loadedMetrics.get(selected) : null; } private void render() { HorizontalPanel hPanel = new HorizontalPanel(); Label label = new Label("Metrics:"); label.setStyleName("note"); hPanel.add(label); for (ListBox metricLb : metricsListBoxes) { hPanel.add(new HTML("&nbsp;")); hPanel.add(metricLb); } hPanel.add(singleScaleCheckBox); VerticalPanel vPanel = new VerticalPanel(); vPanel.add(hPanel); tlPanel = new SimplePanel(); vPanel.add(tlPanel); displayView(vPanel); } private void displayView(Widget widget) { panel.clear(); panel.add(widget); } private Options createOptions() { Options options = Options.create(); options.setAllowHtml(true); options.setDisplayAnnotations(true); options.setDisplayAnnotationsFilter(true); options.setAnnotationsWidth(15); options.setOption("fill", 15); options.setOption("thickness", 2); resetNumberFormats(); int selectedCols = 0; for (ListBox metricLb : metricsListBoxes) { if (getSelectedMetric(metricLb) != null) { setNumberFormats(selectedCols++, getNumberFormat(getSelectedMetric(metricLb))); } } options.setOption("numberFormats", getNumberFormats()); if (!singleScaleCheckBox.getValue()) { int[] scaledCols = new int[selectedCols]; for (int i = 0; i < selectedCols; i++) { scaledCols[i] = i; } options.setScaleType(ScaleType.ALLFIXED); options.setScaleColumns(scaledCols); } return options; } private String getNumberFormat(Metric metric) { return metric.getType().equals("PERCENT") ? "0.0" : "0.##"; } private native JavaScriptObject getNumberFormats() /*-{ return this.numberFormats; }-*/; private native void resetNumberFormats() /*-{ this.numberFormats = {}; }-*/; private native void setNumberFormats(int key, String numberFormat) /*-{ this.numberFormats[key] = numberFormat; }-*/; }
package com.ydl.iec.iec104.server; import com.ydl.iec.iec104.config.Iec104Config; import com.ydl.iec.iec104.server.handler.DataHandler; /** * 从站抽象类 */ public interface Iec104Slave { /** * * @Title: run * @Description: 启动主机 * @throws Exception */ void run() throws Exception; /** * * @Title: setDataHandler * @Description: 设置数据处理类 * @param dataHandler */ Iec104Slave setDataHandler(DataHandler dataHandler); /** * 设置配置文件 * @param iec104Config * @return */ Iec104Slave setConfig(Iec104Config iec104Config); }
package Lab11.Zad2; public abstract class State { public abstract String onOffState(); public abstract String onOnState(); public abstract String onNextState(); public abstract String onPrevState(); public abstract String showChannel(); }
package com.locadoraveiculosweb.modelo.dtos; import static java.math.BigDecimal.ZERO; import static java.math.BigDecimal.valueOf; import static java.util.Optional.ofNullable; import java.io.Serializable; import java.math.BigDecimal; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class AluguelDto implements Serializable { private static final long serialVersionUID = 1L; private Long codigo; private BigDecimal valorTotal; private CarroDto carro; private ApoliceSeguroDto apoliceSeguro; private Integer numeroDiarias; public void calculateValorTotal() { carro = ofNullable(carro).orElse(new CarroDto()); valorTotal = ofNullable(valorTotal).orElse(ZERO); numeroDiarias = ofNullable(numeroDiarias).orElse(0); BigDecimal partial = (ofNullable(carro.getValorDiaria()).orElse(ZERO).multiply(valueOf(numeroDiarias))); valorTotal = valorTotal.add(partial); } public BigDecimal getValorTota() { return ofNullable(valorTotal).orElse(BigDecimal.valueOf(0.00)); } }
package edu.uci.ics.sdcl.firefly.util.mturk; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; /** * Replaces workerIDs with consolidated workerIDs * This is done in order to guarantee that a same Mechanical Turk worker has the same * worker ID among different log files. * * @author adrianoc */ public class ReplaceWorkerID { StringBuffer buffer = new StringBuffer(); MTurkSessions checker; ReplaceQuitSessionID quitReplacer; LogReadWriter logReadWriter; public ReplaceWorkerID(){ checker = new MTurkSessions(); this.quitReplacer = new ReplaceQuitSessionID(); this.logReadWriter = new LogReadWriter(); } public void replace(HashMap<String, Turker> hitsMapAll){ this.replaceIDSessionLogs(hitsMapAll); this.replaceIDConsentLogs(hitsMapAll); } private void replaceIDSessionLogs(HashMap<String, Turker> hitsMapAll){ for(int i=0; i<8;i++){ HashMap<String,String> queryReplace = this.obtainTurkersInRunSession(new Integer (i+1).toString(),hitsMapAll); String sessionLogFile = this.checker.crowddebugLogs[i]; ArrayList<String> buffer = logReadWriter.readToBuffer(3,sessionLogFile); System.out.println("replacing at:" +i+": buffer size: "+buffer.size() + ": replace list: "+queryReplace.size()); ArrayList<String> newBuffer = replace(buffer,queryReplace); String destFileName = sessionLogFile.substring(0,sessionLogFile.indexOf(".")); destFileName = destFileName+"_curated.txt"; logReadWriter.writeBackToBuffer(newBuffer, 3, destFileName); } } private ArrayList<String> replace(ArrayList<String> buffer,HashMap<String,String> queryReplace ){ ArrayList<String> newBuffer = (ArrayList<String>) buffer.clone(); for(String originalID:queryReplace.keySet()){ String finalID = queryReplace.get(originalID); for(int i=0; i<buffer.size(); i++){ String line = buffer.get(i); if(line.contains(originalID)){ line = line.replaceAll(originalID,finalID); newBuffer.set(i, line); } } } return newBuffer; } private HashMap<String,String> obtainTurkersInRunSession(String runSessionNumber, HashMap<String, Turker> hitsMapAll){ //Index is the ID to query and the value is the replace HashMap<String,String> queryReplace = new HashMap<String,String>(); System.out.println("hitsMapAll.size():"+hitsMapAll.size()); for(String turkerStr : hitsMapAll.keySet()){ Turker turker = hitsMapAll.get(turkerStr); String workerID = turker.runWorkerIDMap.get(runSessionNumber); if(workerID!=null){ queryReplace.put(workerID, turker.turkerFinalWorkerID); } } return queryReplace; } private void replaceIDConsentLogs(HashMap<String, Turker> hitsMapAll){ for(int i=0; i<8;i++){ HashMap<String,String> queryReplace = this.obtainTurkersInRunSession(new Integer (i+1).toString(),hitsMapAll); String consentLogFile = this.checker.crowddebugConsentLogs[i]; ArrayList<String> buffer = logReadWriter.readToBuffer(3,consentLogFile); System.out.println("replacing at:" +i+": buffer size: "+buffer.size() + ": replace list: "+queryReplace.size()); ArrayList<String> newBuffer = replace(buffer,queryReplace); String destFileName = consentLogFile.substring(0,consentLogFile.indexOf(".")); destFileName = destFileName+"_curated.txt"; logReadWriter.writeBackToBuffer(newBuffer, 3, destFileName); } } //------------------------------------------------------------------------------- public static void main(String[] args){ ReplaceWorkerID replacer = new ReplaceWorkerID(); TurkerWorkerMatcher matcher = new TurkerWorkerMatcher(); HashMap<String, Turker> hitsMapAll = matcher.listTurkersRunSessions(); replacer.replace(hitsMapAll); } }
package com.altimetrik.demo.model; import java.util.List; public class Album { private String name; private float playcount; private String mbid; private String url; // Getter Methods public String getName() { return name; } public float getPlaycount() { return playcount; } public String getMbid() { return mbid; } public String getUrl() { return url; } // Setter Methods public void setName(String name) { this.name = name; } public void setPlaycount(float playcount) { this.playcount = playcount; } public void setMbid(String mbid) { this.mbid = mbid; } public void setUrl(String url) { this.url = url; } }
package fpt.fis.Controller; import fpt.fis.Service.UserService; import fpt.fis.dto.UserDto; import fpt.fis.model.User; import fpt.fis.repository.UserResponsitory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping(value = "/user") public class UserController { @Autowired private UserService userService; @GetMapping(value = "/getAll") public List<UserDto> getAll(){ return userService.getAll(); } @PostMapping(value = "/updatedUser") public ResponseEntity<?> updateUser(@RequestBody User user){ User user1=userService.Updated(user); return new ResponseEntity<>(user1, HttpStatus.OK); } @PostMapping(value = "/AddUser") public ResponseEntity <?>AddUser(@RequestBody User user){ User user1=userService.Add(user); return new ResponseEntity<>(user1, HttpStatus.OK); } @PostMapping(value = "/deletedUser") public ResponseEntity<?>deleted(@RequestBody User user){ User user1=userService.Deleted(user); return new ResponseEntity<>(user1, HttpStatus.OK); } }
package com; /** * Created by wangxin on 2017/4/7. */ import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.glassfish.jersey.servlet.ServletContainer; public class RestServer{ public static void main(String[] args) { Server server=new Server(8086); ServletHolder servlet = new ServletHolder(ServletContainer.class); servlet.setInitParameter("jersey.config.server.provider.packages", "com"); //Rest所在的包 ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); //start server context.setContextPath("/"); context.addServlet(servlet, "/*"); server.setHandler(context); try{ server.start(); System.out.println("start...in 8086"); }catch (Exception e){ e.printStackTrace(); } } }
package ByteDance; public class TrappingRainWater { public int trap(int[] height) { if (height.length == 0) return 0; int sum = 0; int maxIndex = 0; for (int i = 1; i < height.length; i ++) { if (height[i] > height[maxIndex]) maxIndex = i; } int front = maxIndex; while (front > 0) { int index = 0; for (int i = 0;i < front; i ++) { if (height[i] > height[index]) index = i; } int s = 0; for (int i = index + 1; i <= front - 1; i ++) s += height[i]; sum += height[index] * (front - index - 1) - s; front = index; } int behind = maxIndex; while (behind < height.length - 1) { int index = height.length - 1; for (int i = height.length - 1; i > behind; i --){ if (height[i] > height[index]) index = i; } int s = 0; for (int i = behind + 1; i <= index - 1; i ++) s += height[i]; sum += height[index] * (index - behind - 1) - s; behind = index; } return sum; } }
package ialogistica; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.Random; import aima.basic.Agent; import aima.search.framework.HeuristicFunction; import aima.search.framework.Problem; import aima.search.framework.Search; import aima.search.framework.SearchAgent; import aima.search.informed.HillClimbingSearch; import aima.search.informed.SimulatedAnnealingSearch; public class ProbLogistica { public int heur; public static final double P = 0.8; public static int tipo_heur; private static BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); private static PrintStream out = System.out; public static void main(String[] args) throws Exception { out.println("All your base are belong to us!"); out.println("Introduzca el número de peticiones:"); int numPeticiones = Integer.parseInt(in.readLine()); int[] camiones = new int[3]; int numCamiones = 0; while (numCamiones != 60) { out.println("Introduzca el número de camiones de las siguientes cargas:"); out.print("500 kg:"); camiones[0] = Integer.parseInt(in.readLine()); numCamiones = camiones[0]; out.print("1000 kg:"); camiones[1] = Integer.parseInt(in.readLine()); numCamiones += camiones[1]; out.print("2000 kg:"); camiones[2] = Integer.parseInt(in.readLine()); numCamiones += camiones[2]; if (numCamiones != 60) out.println("Cantidad de camiones incorrecta, por favor introduzca una cantidad de camiones TOTAL igual a 60, solo ha introducido " + numCamiones); } out.println("Creando Mundo..."); EntregasWorld world = new EntregasWorld(numPeticiones, camiones); out.println("Hello World!"); out.println(); int solucion = 0; while (solucion != 1 && solucion != 2) { out.println("Elija la solución inicial:"); out.println("1. Solución simple"); out.println("2. Solucion mejor"); solucion = Integer.parseInt(in.readLine()); if (solucion != 1 && solucion != 2) out.println("Tiene que escoger una de las dos opciones!!!"); } out.println("Generando solución inicial..."); switch (solucion) { case 1: world.generateSimpleSolution(); break; case 2: world.generateBestSolution(); break; default: break; } out.println("Solución inicial generada..."); out.println(); int funcHeur = 0; while (funcHeur != 1 && funcHeur != 2) { out.println("Elija la heurística:"); out.println("1. Maximizar beneficio"); out.println("2. Minimizar valor absoluto del tiempo de entrega"); funcHeur = Integer.parseInt(in.readLine()); tipo_heur = funcHeur; if (funcHeur != 1 && funcHeur != 2) out.println("Tiene que escoger una de las dos opciones!!!"); } out.println(world); out.println(tipo_heur == 1 ? world.getMaximizedBenefit() : world .getMinimizedDeliverTime()); out.println(); int alg = 0; while (alg != 1 && alg != 2) { out.println("Elija el algoritmo:"); out.println("1. Hill Climbing"); out.println("2. Simulated Annealing"); alg = Integer.parseInt(in.readLine()); if (alg != 1 && alg != 2) out.println("Tiene que escoger una de las dos opciones!!!"); } switch (alg) { case 1: BusquedaHC(world, funcHeur); break; case 2: BusquedaSA(world, funcHeur); break; default: break; } } /** * Algoritmo Hill Climbing */ private static void BusquedaHC(EntregasWorld world, int funcion_heuristica) { long start = System.currentTimeMillis(); System.out.println("Hill Climbing"); System.out.println("-------------"); try { Problem problem; HeuristicFunction heuristica = null; // Funcion heuristica segun el parametro introducido if (funcion_heuristica == 1) { // Main.tipo_heur = 1; heuristica = new MaximizedBenefitHeur(); } else if (funcion_heuristica == 2) { // Main.tipo_heur = 2; heuristica = new MinimizedDeliverTimeHeur(); } else { throw new IllegalArgumentException("Parametros incorrectos."); } problem = new Problem(world, new SucesorHC(), new EntregasGoalTest(), heuristica); // Iniciamos la clase AIMA Search search = new HillClimbingSearch(); SearchAgent agent = new SearchAgent(problem, search); // Imprimimos los resultados long end = System.currentTimeMillis(); System.out.println(); printActions(agent.getActions()); printInstrumentation(agent.getInstrumentation()); System.out.println("Tiempo: " + ((long) (end - start) / 1000.0) + " segundos"); } catch (Exception e) { e.printStackTrace(); } } /** * Algoritmo Simulated Annealing */ private static void BusquedaSA(EntregasWorld world, int funcion_heuristica) throws Exception { out.println("Introduzca iteraciones:"); int iteraciones = Integer.parseInt(in.readLine()); out.println("Introduzca las iteraciones por paso:"); int iteraciones_por_paso = Integer.parseInt(in.readLine()); ; out.println("Introduzca el factor K:"); int k = Integer.parseInt(in.readLine()); out.println("Introduzca el valor lambda:"); double lambda = Double.parseDouble(in.readLine()); long start = System.currentTimeMillis(); System.out.println("Simulated Annealing"); System.out.println("-------------------"); try { Problem problem; HeuristicFunction heuristica = null; // Funcion heuristica segun el parametro introducido if (funcion_heuristica == 1) { heuristica = new MaximizedBenefitHeur(); } else if (funcion_heuristica == 2) { heuristica = new MinimizedDeliverTimeHeur(); } else { throw new IllegalArgumentException("Parametros incorrectos."); } problem = new Problem(world, new SucesorSA(), new EntregasGoalTest(), heuristica); // Iniciamos la clase AIMA con los parametros especificos del // Simulated Annealing SimulatedAnnealingSearch search = new SimulatedAnnealingSearch( iteraciones, iteraciones_por_paso, k, lambda); // search.traceOn(); SearchAgent agent = new SearchAgent(problem, search); // Imprimimos los resultados long end = System.currentTimeMillis(); System.out.println(); printActions(agent.getActions()); printInstrumentation(agent.getInstrumentation()); System.out.println("Tiempo: " + ((long) (end - start) / 1000.0) + " segundos"); } catch (Exception e) { e.printStackTrace(); } } private static void printInstrumentation(Properties properties) { Iterator keys = properties.keySet().iterator(); while (keys.hasNext()) { String key = (String) keys.next(); String property = properties.getProperty(key); System.out.println(key + " : " + property); } } private static void printActions(List actions) { for (int i = 0; i < actions.size(); i++) { String action = (String) actions.get(i); System.out.println(action); } } }
package again_again; public class Class28_breakVsContinue { public static void main (String [] args){ for(int n =1;n <=5 ;n++){ System.out.println(n); if (n == 3){ break; } } for(int i =1 ; i <=5; i++){ if(i == 4 || i == 2){ continue; } System.out.print(i); } } }
package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; public final class ProyectoFinalizado_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent { private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory(); private static java.util.List<String> _jspx_dependants; private org.glassfish.jsp.api.ResourceInjector _jspx_resourceInjector; public java.util.List<String> getDependants() { return _jspx_dependants; } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; JspWriter _jspx_out = null; PageContext _jspx_page_context = null; try { response.setContentType("text/html;charset=UTF-8"); pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out; _jspx_resourceInjector = (org.glassfish.jsp.api.ResourceInjector) application.getAttribute("com.sun.appserv.jsp.resource.injector"); out.write("\n"); out.write("\n"); out.write("\n"); out.write("<!doctype html>\n"); out.write("<html lang=\"en\">\n"); out.write("<head>\n"); out.write("\t<meta charset=\"utf-8\" />\n"); out.write("\t<link rel=\"icon\" type=\"image/png\" href=\"Assets/img/favicon.ico\">\n"); out.write("\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\" />\n"); out.write("\n"); out.write("\t<title>Proyectos</title>\n"); out.write("\n"); out.write("\t<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />\n"); out.write(" <meta name=\"viewport\" content=\"width=device-width\" />\n"); out.write("\n"); out.write("\n"); out.write(" <!-- Bootstrap core CSS -->\n"); out.write(" <link href=\"Assets/css/bootstrap.min.css\" rel=\"stylesheet\" />\n"); out.write("\n"); out.write(" <!-- Animation library for notifications -->\n"); out.write(" <link href=\"Assets/css/animate.min.css\" rel=\"stylesheet\"/>\n"); out.write("\n"); out.write(" <!-- Light Bootstrap Table core CSS -->\n"); out.write(" <link href=\"Assets/css/light-bootstrap-dashboard.css?v=1.4.0\" rel=\"stylesheet\"/>\n"); out.write("\n"); out.write(" <!-- Fonts and icons -->\n"); out.write(" <link href=\"http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n"); out.write(" <link href='http://fonts.googleapis.com/css?family=Roboto:400,700,300' rel='stylesheet' type='text/css'>\n"); out.write(" <link href=\"Assets/css/pe-icon-7-stroke.css\" rel=\"stylesheet\" />\n"); out.write("</head>\n"); out.write("<body>\n"); out.write("\n"); out.write("<div class=\"wrapper\">\n"); out.write(" <div class=\"sidebar\" data-color=\"purple\" data-image=\"Assets/img/sidebar-5.jpg\">\n"); out.write(" \t<div class=\"sidebar-wrapper\">\n"); out.write(" <div class=\"logo\">\n"); out.write(" <a href=\"index.html\" class=\"simple-text\">\n"); out.write(" MicroUniverse\n"); out.write(" </a>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <ul class=\"nav\">\n"); out.write(" <li class=\"active\">\n"); out.write(" <a href=\"dashboard.html\">\n"); out.write(" <i class=\"pe-7s-graph\"></i>\n"); out.write(" <p>Vista General</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"user.html\">\n"); out.write(" <i class=\"pe-7s-user\"></i>\n"); out.write(" <p>Datos de la cuenta</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"table.html\">\n"); out.write(" <i class=\"pe-7s-note2\"></i>\n"); out.write(" <p>Proyectos</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"typography.html\">\n"); out.write(" <i class=\"pe-7s-tools\"></i>\n"); out.write(" <p>Herramientas</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"icons.html\">\n"); out.write(" <i class=\"pe-7s-users\"></i>\n"); out.write(" <p>Usuarios *Admin</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write(" \t</div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div class=\"main-panel\">\n"); out.write("\t\t<nav class=\"navbar navbar-default navbar-fixed\">\n"); out.write(" <div class=\"container-fluid\">\n"); out.write(" <div class=\"navbar-header\">\n"); out.write(" <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\"#navigation-example-2\">\n"); out.write(" <span class=\"sr-only\">Toggle navigation</span>\n"); out.write(" <span class=\"icon-bar\"></span>\n"); out.write(" <span class=\"icon-bar\"></span>\n"); out.write(" <span class=\"icon-bar\"></span>\n"); out.write(" </button>\n"); out.write(" <a class=\"navbar-brand\" href=\"#\">Proyecto n - Finalizado</a>\n"); out.write(" </div>\n"); out.write(" <div class=\"collapse navbar-collapse\">\n"); out.write(" <ul class=\"nav navbar-nav navbar-left\">\n"); out.write(" <li style=\"padding-top:10px;padding-left: 30px;;display:flex;\">\n"); out.write(" <div class=\"form-group\"><input type=\"text\" placeholder=\"Buscar poblacion\" name=\"search-pry\" class=\"form-control\"></div>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"\"> \n"); out.write(" <i class=\"fa fa-search\"></i>\n"); out.write("\t\t\t\t\t\t\t\t<p class=\"hidden-lg hidden-md\">Buscar poblacion</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" </ul>\n"); out.write("\n"); out.write(" <ul class=\"nav navbar-nav navbar-right\">\n"); out.write(" <li>\n"); out.write(" <a href=\"\">\n"); out.write(" <p>Cuenta</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write(" <li>\n"); out.write(" <a href=\"#\">\n"); out.write(" <p>Cerrar Sesion</p>\n"); out.write(" </a>\n"); out.write(" </li>\n"); out.write("\t\t\t\t\t\t<li class=\"separator hidden-lg hidden-md\"></li>\n"); out.write(" </ul>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </nav>\n"); out.write("\n"); out.write(" <div class=\"content\">\n"); out.write(" <div class=\"container-fluid\">\n"); out.write("\n"); out.write(" <div class=\"row\" style=\"margin-bottom:20px;\">\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <h5>Fecha de inicio:</h5>\n"); out.write(" <input type=\"text\" readonly class=\"form-control\">\n"); out.write(" </div>\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <h5>Fecha de finalizacion:</h5>\n"); out.write(" <input type=\"text\" readonly class=\"form-control\">\n"); out.write("\n"); out.write(" </div>\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <h5>Bacteria:</h5>\n"); out.write(" <input type=\"text\" readonly class=\"form-control\">\n"); out.write("\n"); out.write(" </div>\n"); out.write(" <div class=\"col-md-3\">\n"); out.write(" <h5>No de poblaciones:</h5>\n"); out.write(" <input type=\"text\" readonly class=\"form-control\">\n"); out.write("\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div class=\"row\">\n"); out.write(" <div class=\"col-md-12\">\n"); out.write(" <div class=\"card\">\n"); out.write(" <div class=\"header\">\n"); out.write(" <h4 class=\"title\">Poblaciones\n"); out.write(" </h4>\n"); out.write(" <p class=\"category\"></p></p>\n"); out.write(" </div>\n"); out.write(" <div class=\"content table-responsive table-full-width\">\n"); out.write(" <table class=\"table table-hover table-striped\">\n"); out.write(" <thead>\n"); out.write(" <th>No Poblacion</th>\n"); out.write(" <th>Ver poblacion</th>\n"); out.write(" \t<th>Poblacion inicial</th>\n"); out.write(" \t<th>Poblacion final</th>\n"); out.write(" \t<th>Dias transcurridos</th>\n"); out.write(" </thead>\n"); out.write(" <tbody>\n"); out.write(" <tr>\n"); out.write(" \t<td>\n"); out.write(" 1</td>\n"); out.write(" \t<td><a href=\"\">Poblacion</a></td>\n"); out.write(" \t<td>Numero poblacion</td>\n"); out.write(" \t<td>Poblacion final</td>\n"); out.write(" \t<td>Dias transcurridos </td>\n"); out.write(" </tr>\n"); out.write(" </tbody>\n"); out.write(" </table>\n"); out.write("\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <div class=\"row\" style=\"margin-bottom:20px;\">\n"); out.write(" <div class=\"col-md-6\">\n"); out.write(" <button class=\"btn btn-primary\">Ver Resultados</button>\n"); out.write("\n"); out.write(" </div>\n"); out.write(" </div>\n"); out.write(" <div class=\"clearfix\"></div>\n"); out.write(" </div>\n"); out.write("\n"); out.write(" <footer class=\"footer\">\n"); out.write(" <div class=\"container-fluid\">\n"); out.write(" \n"); out.write(" <p class=\"copyright pull-right\">\n"); out.write(" &copy; <script>document.write(new Date().getFullYear())</script> <a href=\"index.html\">Coatl - MicroUniverse</a>\n"); out.write(" </p>\n"); out.write(" </div>\n"); out.write(" </footer>\n"); out.write("\n"); out.write("\n"); out.write(" </div>\n"); out.write("</div>\n"); out.write("\n"); out.write("\n"); out.write("</body>\n"); out.write("\n"); out.write(" <!-- Core JS Files -->\n"); out.write(" <script src=\"Assets/js/jquery.3.2.1.min.js\" type=\"text/javascript\"></script>\n"); out.write("\t<script src=\"Assets/js/bootstrap.min.js\" type=\"text/javascript\"></script>\n"); out.write("\n"); out.write("\t<!-- Charts Plugin -->\n"); out.write("\t<script src=\"Assets/js/chartist.min.js\"></script>\n"); out.write("\n"); out.write(" <!-- Notifications Plugin -->\n"); out.write(" <script src=\"Assets/js/bootstrap-notify.js\"></script>\n"); out.write("\n"); out.write(" <!-- Google Maps Plugin -->\n"); out.write(" <script type=\"text/javascript\" src=\"https://maps.googleapis.com/maps/api/js?key=YOUR_KEY_HERE\"></script>\n"); out.write("\n"); out.write(" <!-- Light Bootstrap Table Core javascript and methods for Demo purpose -->\n"); out.write("\t<script src=\"Assets/js/light-bootstrap-dashboard.js?v=1.4.0\"></script>\n"); out.write("\n"); out.write("\t<!-- Light Bootstrap Table DEMO methods, don't include it in your project! -->\n"); out.write("\t<script src=\"Assets/js/demo.js\"></script>\n"); out.write(" <script src=\"path/to/anime.min.js\"></script>\n"); out.write("\n"); out.write("</html>\n"); } catch (Throwable t) { if (!(t instanceof SkipPageException)){ out = _jspx_out; if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (_jspx_page_context != null) _jspx_page_context.handlePageException(t); else throw new ServletException(t); } } finally { _jspxFactory.releasePageContext(_jspx_page_context); } } }
package database.entity; import javax.persistence.*; import javax.xml.parsers.DocumentBuilderFactory; import java.util.Date; import java.util.LinkedList; import java.util.List; /** * Created by csvanefalk on 18/11/14. */ @Entity public class Project implements IEntity { @Id private int id; public int getId() { return id; } public void setId(int id) { this.id = id; } private String name; @Lob private String description; @Column(length = 2500) private String htmlUrl; @Column(length = 2500) private String homepageUrl; @Column(length = 2500) private String downloadUrl; @Column(length = 2500) private String mediumLogoUrl; @Column(length = 2500) private String smallLogoUrl; @Temporal(TemporalType.TIMESTAMP) private Date createdAt; @Temporal(TemporalType.TIMESTAMP) private Date updatedAt; private int userCount; private int ratingCount; private int reviewCount; private int analysisID; private float averageRating; private boolean isManuallyInserted; @ManyToMany(cascade = {CascadeType.REFRESH}) List<Tag> tags = new LinkedList<>(); @ManyToMany(cascade = {CascadeType.REFRESH}) List<License> licenses = new LinkedList<>(); @ManyToMany(cascade = {CascadeType.REFRESH}) List<Link> links = new LinkedList<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public String getHtmlUrl() { return htmlUrl; } public void setHtmlUrl(String htmlUrl) { this.htmlUrl = htmlUrl; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getHomepageUrl() { return homepageUrl; } public void setHomepageUrl(String homepageUrl) { this.homepageUrl = homepageUrl; } public String getDownloadUrl() { return downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getMediumLogoUrl() { return mediumLogoUrl; } public void setMediumLogoUrl(String mediumLogoUrl) { this.mediumLogoUrl = mediumLogoUrl; } public String getSmallLogoUrl() { return smallLogoUrl; } public void setSmallLogoUrl(String smallLogoUrl) { this.smallLogoUrl = smallLogoUrl; } public int getUserCount() { return userCount; } public void setUserCount(int userCount) { this.userCount = userCount; } public float getAverageRating() { return averageRating; } public void setAverageRating(float averageRating) { this.averageRating = averageRating; } public int getRatingCount() { return ratingCount; } public void setRatingCount(int ratingCount) { this.ratingCount = ratingCount; } public int getReviewCount() { return reviewCount; } public void setReviewCount(int reviewCount) { this.reviewCount = reviewCount; } public int getAnalysisID() { return analysisID; } public void setAnalysisID(int analysisID) { this.analysisID = analysisID; } public List<Tag> getTags() { return tags; } public void setTags(List<Tag> tags) { this.tags = tags; } public List<License> getLicenses() { return licenses; } public void setLicenses(List<License> licenses) { this.licenses = licenses; } public List<Link> getLinks() { return links; } public void setLinks(List<Link> links) { this.links = links; } public void addLink(Link link) { this.links.add(link); } public void addLicense(License license) { this.licenses.add(license); } public void addTag(Tag tag) { this.tags.add(tag); } public boolean isManuallyInserted() { return isManuallyInserted; } public void setManuallyInserted(boolean isManuallyInserted) { this.isManuallyInserted = isManuallyInserted; } }
package com.tencent.mm.plugin.soter.b; import com.tencent.mm.protocal.c.bvg; import com.tencent.mm.protocal.k; import com.tencent.mm.protocal.k.c; import com.tencent.mm.protocal.k.e; public class c$b extends e implements c { public bvg onw = new bvg(); public final int G(byte[] bArr) { this.onw = (bvg) new bvg().aG(bArr); k.a(this, this.onw.six); return this.onw.six.rfn; } public final int getCmdId() { return 0; } }
package com.mycom.config; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; //인증에 실패한 사용자의 response에 HttpServletResponse.SC_UNAUTHORIZED를 담는다. @Component public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "접근 권한 없음"); } }
import java.util.Arrays; import java.util.Scanner; public class Anagram2 { static boolean isAnagram(String a, String b) { if(a.length() != b.length()) return false; boolean isAnagram = true; char[] aArray = a.toCharArray(); char[] bArray = b.toCharArray(); Arrays.sort(aArray); Arrays.sort(bArray); for(int i=0; i<a.length(); i++) { if(aArray[i] != bArray[i]) { isAnagram = false; break; } } return isAnagram; } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String a = scan.next(); String b = scan.next(); scan.close(); boolean ret = isAnagram(a, b); System.out.println((ret) ? "Anagrams" : "Not Anagrams"); } }
package com.goldgov.gtiles.module.attachment.web; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageTypeSpecifier; import javax.imageio.metadata.IIOMetadata; import javax.imageio.stream.ImageOutputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import com.goldgov.dygl.cache.SpyMemcachedImpl; import com.goldgov.dygl.utils.AttachmentSaveAsFileUtils; import com.goldgov.dygl.utils.FileConstants; import com.goldgov.gtiles.module.attachment.service.Attachment; import com.goldgov.gtiles.module.attachment.service.IAttachmentService; import com.sun.imageio.plugins.jpeg.JPEGImageWriter; @Controller("attachmentController") @RequestMapping("/module/attachment") public class AttachmentController { @Autowired @Qualifier("attachmentService") private IAttachmentService attachmentService; @RequestMapping("/upload") public String upload(HttpServletRequest request){ String groupID = request.getParameter("groupID"); Map<String, MultipartFile> fileMap = ((MultipartHttpServletRequest)request).getFileMap();; attachmentService.saveAttachment(groupID, fileMap, false); return ""; } @RequestMapping("/download") public void download(HttpServletRequest request,HttpServletResponse response){ String groupID = request.getParameter("groupID"); String attachmentID = request.getParameter("attachmentID"); String openType = request.getParameter("openType"); Attachment attachment = null; Boolean iscached=false; if(attachmentID != null){ attachment = attachmentService.findAttachmentByID(attachmentID); }else if(groupID != null){ if(groupID.indexOf(".jpg")!=-1){ iscached=true; groupID=groupID.replace(".jpg", ""); } List<Attachment> attachmentList = attachmentService.findAttachmentByGroupID(groupID); if(attachmentList != null && attachmentList.size() > 0){ attachment = attachmentList.get(0); } } if(attachment == null){ return; } try { //如果走缓存 则固定 header if(iscached){ response.setContentType("image/jpeg"); Calendar curDate=Calendar.getInstance(); response.setHeader("Last-Modified",getHtmlHeaderDate(curDate.getTime())); response.setHeader("Cache-Control","max-age=7200, public"); curDate.add(Calendar.HOUR, 2); response.setHeader("Expires",getHtmlHeaderDate(curDate.getTime())); }else{ response.setContentType(attachment.getMimeType()); if(openType == null || "".equals(openType)){ openType = "attachment"; } response.setHeader("content-disposition", openType + ";filename=" + URLEncoder.encode(attachment.getFileName(), "UTF-8")); } try { ServletOutputStream outputStream = response.getOutputStream(); InputStream content = attachmentService.findContentByID(attachment); FileCopyUtils.copy(content, outputStream); } catch (Exception e) { // throw new RuntimeException("文件读取异常:" + e); } } catch (Exception e) { throw new RuntimeException("文件名编码异常:" + e); } } @RequestMapping("/downloadBySmail") public void downloadBySmail(HttpServletRequest request,HttpServletResponse response) throws IOException{ //走缓存 则固定 header response.setContentType("image/jpeg"); Calendar curDate=Calendar.getInstance(); response.setHeader("Last-Modified",getHtmlHeaderDate(curDate.getTime())); response.setHeader("Cache-Control","max-age=7200, public"); curDate.add(Calendar.HOUR, 2); response.setHeader("Expires",getHtmlHeaderDate(curDate.getTime())); String groupID = request.getParameter("groupID"); if(groupID.indexOf(".jpg")!=-1){ groupID=groupID.replace(".jpg", ""); } Map<String,byte[]> imgMap=(Map<String, byte[]>) SpyMemcachedImpl.get("downloadBySmail"); imgMap=imgMap==null?new HashMap<String, byte[]>():imgMap; if(imgMap.get(groupID)!=null){ ServletOutputStream outputStream=null; try { outputStream = response.getOutputStream(); outputStream.write(imgMap.get(groupID)); outputStream.flush(); return ; } catch (Exception e) { e.printStackTrace(); }finally{ if(outputStream!=null)outputStream.close(); } } Attachment attachment = null; if(groupID != null){ List<Attachment> attachmentList = attachmentService.findAttachmentByGroupID(groupID); if(attachmentList != null && attachmentList.size() > 0){ attachment = attachmentList.get(0); } } if(attachment == null){ return; } InputStream content=null; ServletOutputStream outputStream =null; try { outputStream = response.getOutputStream(); content = attachmentService.findContentByID(attachment); if(content!=null) { //获取最大宽高 Integer maxHeight=200; Integer maxWidth=296; BufferedImage img=ImageIO.read(content); Integer curHeight=img.getHeight(); Integer curWidth=img.getWidth(); //如果当前图片高度大于最大高度 if(curHeight>maxHeight){ //按照比例计算宽 curWidth=(int) (curWidth*(new Double(maxHeight.intValue())/curHeight)); //低昂前高等于最大高度 curHeight=maxHeight.intValue(); } if(curWidth>maxWidth){ curHeight=(int) (curHeight*(new Double(maxWidth.intValue())/curWidth)); curWidth=maxWidth.intValue(); } BufferedImage image = new BufferedImage(curWidth,curHeight ,BufferedImage.TYPE_INT_RGB ); image.getGraphics().drawImage(img, 0, 0, curWidth, curHeight, null); // 绘制缩小后的图 JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpg").next(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); ImageOutputStream ios = ImageIO.createImageOutputStream(baos); imageWriter.setOutput(ios); IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(image), null); //new Write and clean up imageWriter.write(imageMetaData, new IIOImage(image, null, null), null); ios.close(); imageWriter.dispose(); byte[] imgbyte=baos.toByteArray(); baos.close(); outputStream.write(imgbyte); imgMap.put(groupID, imgbyte); SpyMemcachedImpl.put("downloadBySmail",imgMap,3600*12); } // FileCopyUtils.copy(content, outputStream); } catch (Exception e) { e.printStackTrace(); }finally{ if(outputStream!=null)outputStream.close(); if(content!=null)content.close(); } } public static String getHtmlHeaderDate(Date date){ //Fri, 06 May 2016 11:54:19 GMT String rel=""; String curDate[]=date.toString().split(" "); rel+=curDate[0]+", "; rel+=curDate[2]+" "; rel+=curDate[1]+" "; rel+=curDate[5]+" "; rel+=curDate[3]+" GMT"; return rel; } /** * @param request groupIDs或 ids */ @RequestMapping("/deleteAttachment") public String deleteAttachment(HttpServletRequest request){ String[] ids = request.getParameterValues("ids"); if(ids != null && ids.length > 0){ attachmentService.deleteAttachment(ids); }else{ String[] groupIDs = request.getParameterValues("groupIDs"); if(groupIDs != null && groupIDs.length > 0){ attachmentService.deleteAttachmentByGroupIDs(groupIDs); } } return ""; } @RequestMapping("/downloadFLV") public void downloadFLV(HttpServletRequest request,HttpServletResponse response){ String attachmentId = request.getParameter("attachmentId"); Attachment a = attachmentService.findAttachmentByID(attachmentId); AttachmentSaveAsFileUtils.downloadFLV(a, FileConstants.DEFAULT_MODULE_NAME, FileConstants.TYPE_VIDEO, request, response); } }
package com.neo.test.curator; import java.util.concurrent.TimeUnit; import org.apache.curator.RetryPolicy; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.locks.InterProcessMutex; import org.apache.curator.retry.ExponentialBackoffRetry; public class TestMain { //public final static String ZK_HOST = "172.19.253.121:2181,172.19.253.122:2181,172.19.253.123:2181"; public final static String ZK_HOST = "127.0.0.1:2181"; public static void main(String[] args) { try { RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); CuratorFramework client = CuratorFrameworkFactory.newClient(ZK_HOST, retryPolicy); client.start(); //client.create().forPath("/test_curator","00".getBytes()); InterProcessMutex lock = new InterProcessMutex(client, "/test_curator"); if (lock.acquire(15, TimeUnit.SECONDS)) { try { System.out.println("do something"); } finally { lock.release(); } } } catch (Exception e) { e.printStackTrace(); } } }
package ager; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; public class Waller { static boolean[] GO_THRU = new boolean[1024]; static { GO_THRU[Types.Air + 1] = true; GO_THRU[Types.Tall_Grass + 1] = true; GO_THRU[Types.Dead_Bush + 1] = true; GO_THRU[Types.Rose + 1] = true; GO_THRU[Types.Dandelion + 1] = true; } public static void main(String[] args) throws FileNotFoundException, IOException { MCMap map = new MCMap(new File(args[0]), 10); for (MCAFile f : map.files) { for (int cz = 0; cz < 32; cz++) { for (int cx = 0; cx < 32; cx++) { Chunk ch = f.chunks[cz][cx]; if (ch != null) { ch.prepare(); for (int y = 0; y < 256; y++) { for (int z = 0; z < 16; z++) { for (int x = 0; x < 16; x++) { if (ch.getBlockType(x, y, z) == Types.Wool && ch.getData(x, y, z) == Types.Wool_Dark_Green) { int Y = y; do { ch.setBlockType((byte) Types.Cobblestone, x, Y, z); Y--; } while (Y > 0 && GO_THRU[ch.getBlockType(x, Y, z) + 1]); } }}} } } } } map.writeAndClose(); } }
package com.tencent.mm.plugin.collect.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class CollectBillListUI$1 implements OnMenuItemClickListener { final /* synthetic */ CollectBillListUI hXk; CollectBillListUI$1(CollectBillListUI collectBillListUI) { this.hXk = collectBillListUI; } public final boolean onMenuItemClick(MenuItem menuItem) { CollectBillListUI.a(this.hXk); return false; } }
package level1; import java.util.ArrayList; import java.util.Arrays; public class 나누어_떨어지는_숫자_배열 { class Solution { public int[] solution(int[] arr, int divisor) { ArrayList<Integer> list = new ArrayList<>(); for (int i : arr) if (i % divisor == 0) list.add(i); if(list.size() == 0){ return new int[]{-1}; }else{ return list.stream().sorted() .mapToInt(Integer::intValue) .toArray(); } } public int[] solution2(int[] arr, int divisor) { int[] answer = Arrays.stream(arr).filter(factor -> factor % divisor == 0).sorted().toArray(); if (answer.length == 0) { return new int[]{-1}; }else{ return answer; } } } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Class for the help menu * * @author Saksham Ghimire and Densai Moua * @version 12/15/2010 */ public class helpImage extends Actor { /** * Act - do whatever the helpImage wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { // Add your action code here. } }
package ladder.DynamicProgrammingII; /** * A message containing letters from A-Z is being encoded to numbers using the following mapping: * 'A' -> 1 * 'B' -> 2 * ... * 'Z' -> 26 * Given an encoded message containing digits, determine the total number of ways to decode it. * * Given encoded message 12, it could be decoded as AB (1 2) or L (12). * The number of ways decoding 12 is 2. */ public class DecodeWays { /** * @param s a string, encoded message * @return an integer, the number of ways decoding */ public int numDecodings(String s) { if (s == null || s.length() == 0) { return 0; } // f[i]: 前i个字符一共多少种解码方式 int[] f = new int[s.length() + 1]; f[0] = 1; f[1] = (s.charAt(0) == '0') ? 0 : 1; // input "0" output 0 for (int i = 2; i <= s.length(); i++) { if (s.charAt(i - 1) != '0') { f[i] = f[i - 1]; } int twoDigit = (s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0'); if (twoDigit >= 10 && twoDigit <= 26) { f[i] = f[i] + f[i - 2]; } } return f[s.length()]; } public static void main(String[] args) { String s = "12215"; DecodeWays sol = new DecodeWays(); System.out.println(sol.numDecodings(s)); } }
package com.dahlstore.dnote5; import android.view.View; import android.widget.ImageView; public class Memo { public String header, bodyText; public ImageView imageView; public Memo(String header, String bodyText, ImageView imageView){ this.header = header; this.bodyText = bodyText; this.imageView = imageView; } }
package com.cmpickle.volumize.view.alerts; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.support.annotation.StringRes; import android.support.v4.content.ContextCompat; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.TextView; import com.cmpickle.volumize.R; import com.cmpickle.volumize.view.util.ViewUtil; import javax.inject.Inject; import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT; import static android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND; /** * @author Cameron Pickle * Copyright (C) Cameron Pickle (cmpickle) on 4/11/2017. */ public class Alerts { private static final int DEFAULT_WIDTH = 300; private ViewUtil viewUtil; @Inject public Alerts(ViewUtil viewUtil) { this.viewUtil = viewUtil; } AlertDialog showAlert(Context context, final AlertListener alertListener, final AlertDialogParams params) { final AlertDialog.Builder helpBuilder = new AlertDialog.Builder(context); @SuppressLint("InflateParams") //no parent for AlertDialog final View alertView = LayoutInflater.from(context).inflate(R.layout.alert, null); helpBuilder.setView(alertView); final AlertDialog alertDialog = helpBuilder.create(); alertDialog.getWindow().setDimAmount(0.6f); alertDialog.getWindow().addFlags(FLAG_DIM_BEHIND); alertDialog.setCanceledOnTouchOutside(params.isCancelOnTapOutside()); alertDialog.setCancelable(params.isCancelable()); TextView title = (TextView) alertView.findViewById(R.id.tv_alert_title); TextView subtitle = (TextView) alertView.findViewById(R.id.tv_alert_subtitle); TextView btnLeft = (TextView) alertView.findViewById(R.id.btn_left); TextView btnRight = (TextView) alertView.findViewById(R.id.btn_right); //Title String titleText = null; if(params.getTitleResourceId() != null) { titleText = context.getString(params.getTitleResourceId()); } viewUtil.setTextOrHide(title, titleText); //Subtitle String subTitleText = null; if(params.getSubTitleResourceId() != null) { subTitleText = context.getString(params.getSubTitleResourceId()); } viewUtil.setTextOrHide(subtitle, subTitleText); //Right button always show btnRight.setVisibility(View.VISIBLE); if(params.getRightButtonTextResourceId() != null) { btnRight.setText(context.getString(params.getRightButtonTextResourceId())); } if(params.getRightButtonColorResourceId() != null) { btnRight.setTextColor(ContextCompat.getColor(context, params.getRightButtonColorResourceId())); } btnRight.setOnClickListener(v -> { alertDialog.cancel(); alertListener.onAlertRightButton(params); }); //Left button if(params.getLeftButtonTextResourceId() != null) { btnLeft.setText(context.getString(params.getLeftButtonTextResourceId())); if (params.getLeftButtonColorResourceId() != null) { btnRight.setTextColor(ContextCompat.getColor(context, params.getLeftButtonColorResourceId())); } btnLeft.setVisibility(View.VISIBLE); btnLeft.setOnClickListener(v -> { alertDialog.cancel(); alertListener.onAlertLeftButton(params); }); } else { btnLeft.setVisibility(View.INVISIBLE); } //Dismiss listener alertDialog.setOnDismissListener(dialogInterface -> alertListener.onAlertDismissed(params)); //The use of metrics.density is to convert the DP to PX. SetAttributes only accepts PX. DisplayMetrics metrics = new DisplayMetrics(); alertDialog.getWindow().getWindowManager().getDefaultDisplay().getMetrics(metrics); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(alertDialog.getWindow().getAttributes()); if(params.getWidth() == null) { lp.width = (int) (DEFAULT_WIDTH * metrics.density); } else { lp.width = (int) (params.getWidth() * metrics.density); } if(params.getHeight() == null) { lp.height = WRAP_CONTENT; } else { lp.height = (int) (params.getHeight() * metrics.density); } alertDialog.show(); alertDialog.getWindow().setAttributes(lp); return alertDialog; } AlertDialog showError(Context context, AlertListener alertListener, @StringRes int errorTextResourceId) { AlertDialogParams alertDialogParams = new AlertDialogParams(R.string.common_error, errorTextResourceId); return showAlert(context, alertListener, alertDialogParams); } }
package algo_basic.day1; import java.util.Scanner; public class SWEA_2050_D1_알파벳 { public static void main(String[] args) { Scanner s = new Scanner(System.in); StringBuilder sb = new StringBuilder(); String StringName = s.next(); for (int i = 0; i < StringName.length(); i++) { sb.append(StringName.charAt(i)- 64).append(" "); } System.out.println(sb); } }
package advance.dev; import java.util.*; public class MainApp { public static void input(Person[] persons) { Scanner sc = new Scanner(System.in); Person[] tc = new Teacher[1]; for (int i = 0; i < tc.length; i++) { System.out.println("Nhap ten gv: "); String tengv = sc.next(); System.out.println("Nhap sdt: "); String sdt = sc.next(); System.out.println("Nhap ma gv: "); String magv = sc.next(); System.out.println("Nhap tuoi gv: "); int tuoigv = sc.nextInt(); System.out.println("Nhap He so luong: "); double hsLuong = sc.nextDouble(); persons[i] = new Teacher(tengv, sdt, tuoigv, magv, hsLuong); } Person[] sv = new Student[2]; for (int i = 0; i < sv.length; i++) { System.out.println("Nhap ten sv: "); String tensv = sc.next(); System.out.println("Nhap sdt"); String sdtsv = sc.next(); System.out.println("Nhap tuoi sv: "); int tuoi = sc.nextInt(); System.out.println("Nhap diem toan: "); double toan = sc.nextDouble(); System.out.println("Nhap diem ly: "); double ly = sc.nextDouble(); System.out.println("Nhap diem hoa: "); double hoa = sc.nextDouble(); System.out.println("Nhap ma sv: "); String masv = sc.next(); System.out.println("Nhap lop: "); String lop = sc.next(); persons[i] = new Student(tensv, sdtsv, tuoi, toan, ly, hoa, masv, lop); } } public static void print(Person[] persons) { for (int i = 0; i < persons.length; i++) { System.out.println(persons[i]); } } public static void main(String[] args) { Person[] persons = new Person[3]; input(persons); print(persons); } }
public class Rectangle extends Shape implements Spatial { private double length; private double width; public double getLength() { return this.length; } public double getWidth() { return this.width; } public void setWidth(double width) { this.width=width; } public void setLength(double length) { this.length=length; } public double volume() { return -1; } public double area() { return length*width; } }
package com.encore.spring.model; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.encore.spring.domain.Item; @Service public class ItemCatalogImpl implements ItemCatalog { @Autowired private ItemDAO itemDAO; @Override public List<Item> getItemList() throws Exception { return itemDAO.getItemList(); } @Override public Item getItem(Integer itemId) throws Exception { return itemDAO.getItem(itemId); } }
package com.fordprog.matrix.interpreter.execution; import com.fordprog.matrix.interpreter.type.BuiltinFunction; import com.fordprog.matrix.interpreter.type.UserDefinedFunction; public interface FunctionVisitor { void visit(UserDefinedFunction userDefinedFunction); void visit(BuiltinFunction builtinFunction); }