text
stringlengths
10
2.72M
/** * */ package com.shubhendu.javaworld; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.Map; /** * @author ssingh * */ public class LFUCache { private int maxCapacity; private Map<Integer, Integer> valuesMap; private Map<Integer, Integer> frequencyMap; private Map<Integer, LinkedHashSet<Integer>> frequencyKeys; int minFrequency; public LFUCache(int capacity) { maxCapacity = capacity; valuesMap = new HashMap<Integer, Integer>(); frequencyMap = new HashMap<Integer, Integer>(); frequencyKeys = new HashMap<Integer, LinkedHashSet<Integer>>(); minFrequency = 0; } public int get(int key) { if (!valuesMap.containsKey(key)) { return -1; } int value = valuesMap.get(key); incrementFrequency(key); return value; } private void incrementFrequency(int key) { int frequency = frequencyMap.get(key); removeFromFrequencyKeys(frequency, key); frequencyMap.put(key, frequency + 1); if (!frequencyKeys.containsKey(frequency + 1)) { frequencyKeys.put(frequency + 1, new LinkedHashSet<Integer>()); } frequencyKeys.get(frequency + 1).add(key); } private void removeFromFrequencyKeys(int frequency, int key) { frequencyKeys.get(frequency).remove(key); if (frequencyKeys.get(frequency).isEmpty()) { frequencyKeys.remove(frequency); if (frequency == minFrequency) { minFrequency = frequency + 1; } } } public void put(int key, int value) { if (maxCapacity <= 0) { return; } if (valuesMap.containsKey(key)) { valuesMap.put(key, value); incrementFrequency(key); } else { if (valuesMap.size() >= maxCapacity) { evictLFUKey(); valuesMap.put(key, value); setFrequency(key); } else { valuesMap.put(key, value); setFrequency(key); } incrementFrequency(key); minFrequency = 1; } } private void setFrequency(int key) { frequencyMap.put(key, 0); if (!frequencyKeys.containsKey(0)) { frequencyKeys.put(0, new LinkedHashSet<Integer>()); } frequencyKeys.get(0).add(key); } private void evictLFUKey() { int keyToEvict = frequencyKeys.get(minFrequency).iterator().next(); frequencyKeys.get(minFrequency).remove(keyToEvict); valuesMap.remove(keyToEvict); frequencyMap.remove(keyToEvict); } /** * @param args */ public static void main(String[] args) { // LFUCache lfuCache = new LFUCache(4); // lfuCache.put(10, 1); // lfuCache.put(20, 2); // System.out.println(lfuCache.get(10)); // lfuCache.put(20, 3); // lfuCache.put(30, 4); // lfuCache.put(40, 5); // System.out.println(lfuCache.get(20)); // lfuCache.put(50, 6); // System.out.println(lfuCache.get(30)); LFUCache cache = new LFUCache(2); cache.put(1, 1); cache.put(2, 2); System.out.println(cache.get(1)); cache.put(3, 3); System.out.println(cache.get(2)); System.out.println(cache.get(3)); cache.put(4, 4); System.out.println(cache.get(1)); System.out.println(cache.get(3)); System.out.println(cache.get(4)); } }
package com.tencent.mm.plugin.sns.model; import com.tencent.mm.bt.h.d; import com.tencent.mm.plugin.sns.storage.o; class af$36 implements d { af$36() { } public final String[] xb() { return o.diD; } }
package com.uptc.prg.maze.model.data.mazegraphlist; import com.uptc.prg.maze.model.data.graphlist.EdgeType; public class MazeEdge { private MazeVertex mTargetVertex; private int mEdgeWeight; private EdgeType mEdgeType; public MazeEdge(MazeVertex targetVertex, int edgeWeight, EdgeType edgeType) { this.mTargetVertex = targetVertex; this.mEdgeWeight = edgeWeight; this.mEdgeType = edgeType; } /** * @return The label of this edge. */ public final int getEdgeWeight() { return this.mEdgeWeight; } public final MazeVertex getTargetVertex() { return this.mTargetVertex; } public final EdgeType getEdgeType() { return this.mEdgeType; } }
package udacity.project.lynsychin.popularmovies.database; import androidx.lifecycle.LiveData; import androidx.room.Dao; import androidx.room.Delete; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; import androidx.room.Update; import java.util.List; @Dao public interface MoviesDao { @Query("SELECT * FROM movie ORDER BY popularity") LiveData<List<MovieEntry>> loadAllMovies(); @Insert void insertMovie(MovieEntry movieEntry); @Update(onConflict = OnConflictStrategy.REPLACE) void updateMovie(MovieEntry movieEntry); // Using this to verify if movie is already in DB @Query("SELECT * FROM movie WHERE id = :id") MovieEntry loadMovieById(int id); @Query("SELECT * FROM movie WHERE id = :id") LiveData<MovieEntry> getMovieById(int id); }
package filters; public class EmptyFilter implements Filter { @Override public String execute(String password) throws Exception { return password; } }
package com.hqb.patshop.mbg.model; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * ums_member * @author */ @Data public class UmsMember implements Serializable { private Long id; private Long memberLevelId; /** * 用户名 */ private String username; /** * 密码 */ private String password; /** * 昵称 */ private String nickname; /** * 手机号码 */ private String phone; /** * 帐号启用状态:0->禁用;1->启用 */ private Integer status; /** * 注册时间 */ private Date createTime; /** * 头像 */ private String icon; /** * 性别:0->未知;1->男;2->女 */ private Integer gender; /** * 生日 */ private Date birthday; /** * 所在城市 */ private String city; /** * 职业 */ private String job; /** * 个性签名 */ private String personalizedSignature; /** * 拍拍币 */ private Integer patCoin; /** * 成长值 */ private Integer growth; /** * 登陆状态 */ private Boolean loginStatus; /** * 盐 */ private String salt; /** * 权限管理 0普通用户、 1商家 */ private Integer manager; private static final long serialVersionUID = 1L; @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } UmsMember other = (UmsMember) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getMemberLevelId() == null ? other.getMemberLevelId() == null : this.getMemberLevelId().equals(other.getMemberLevelId())) && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername())) && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword())) && (this.getNickname() == null ? other.getNickname() == null : this.getNickname().equals(other.getNickname())) && (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone())) && (this.getStatus() == null ? other.getStatus() == null : this.getStatus().equals(other.getStatus())) && (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime())) && (this.getIcon() == null ? other.getIcon() == null : this.getIcon().equals(other.getIcon())) && (this.getGender() == null ? other.getGender() == null : this.getGender().equals(other.getGender())) && (this.getBirthday() == null ? other.getBirthday() == null : this.getBirthday().equals(other.getBirthday())) && (this.getCity() == null ? other.getCity() == null : this.getCity().equals(other.getCity())) && (this.getJob() == null ? other.getJob() == null : this.getJob().equals(other.getJob())) && (this.getPersonalizedSignature() == null ? other.getPersonalizedSignature() == null : this.getPersonalizedSignature().equals(other.getPersonalizedSignature())) && (this.getPatCoin() == null ? other.getPatCoin() == null : this.getPatCoin().equals(other.getPatCoin())) && (this.getGrowth() == null ? other.getGrowth() == null : this.getGrowth().equals(other.getGrowth())) && (this.getLoginStatus() == null ? other.getLoginStatus() == null : this.getLoginStatus().equals(other.getLoginStatus())) && (this.getSalt() == null ? other.getSalt() == null : this.getSalt().equals(other.getSalt())) && (this.getManager() == null ? other.getManager() == null : this.getManager().equals(other.getManager())); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getMemberLevelId() == null) ? 0 : getMemberLevelId().hashCode()); result = prime * result + ((getUsername() == null) ? 0 : getUsername().hashCode()); result = prime * result + ((getPassword() == null) ? 0 : getPassword().hashCode()); result = prime * result + ((getNickname() == null) ? 0 : getNickname().hashCode()); result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode()); result = prime * result + ((getStatus() == null) ? 0 : getStatus().hashCode()); result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode()); result = prime * result + ((getIcon() == null) ? 0 : getIcon().hashCode()); result = prime * result + ((getGender() == null) ? 0 : getGender().hashCode()); result = prime * result + ((getBirthday() == null) ? 0 : getBirthday().hashCode()); result = prime * result + ((getCity() == null) ? 0 : getCity().hashCode()); result = prime * result + ((getJob() == null) ? 0 : getJob().hashCode()); result = prime * result + ((getPersonalizedSignature() == null) ? 0 : getPersonalizedSignature().hashCode()); result = prime * result + ((getPatCoin() == null) ? 0 : getPatCoin().hashCode()); result = prime * result + ((getGrowth() == null) ? 0 : getGrowth().hashCode()); result = prime * result + ((getLoginStatus() == null) ? 0 : getLoginStatus().hashCode()); result = prime * result + ((getSalt() == null) ? 0 : getSalt().hashCode()); result = prime * result + ((getManager() == null) ? 0 : getManager().hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberLevelId=").append(memberLevelId); sb.append(", username=").append(username); sb.append(", password=").append(password); sb.append(", nickname=").append(nickname); sb.append(", phone=").append(phone); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", icon=").append(icon); sb.append(", gender=").append(gender); sb.append(", birthday=").append(birthday); sb.append(", city=").append(city); sb.append(", job=").append(job); sb.append(", personalizedSignature=").append(personalizedSignature); sb.append(", patCoin=").append(patCoin); sb.append(", growth=").append(growth); sb.append(", loginStatus=").append(loginStatus); sb.append(", salt=").append(salt); sb.append(", manager=").append(manager); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
package lesson29.Ex5; import java.util.Date; public class Manager extends Employee { private Date startDay; private Date endDay; public Manager() { } public Manager(Date startDay, Date endDay) { this.startDay = startDay; this.endDay = endDay; } public Manager(Employee employee, Date start, Date end) { super(employee.getIdCard(), employee.getFullName(), employee.getAddress(), employee.getDayOfBirth(), employee.getEmail(), employee.getPhoneNumber(), employee.getIdEmp(), employee.getPosition(), employee.getBasicWages(), employee.getExperience(), employee.getDayOntheMonth()); startDay = start; endDay = end; } public Manager(String idCard, String fullName, String address, Date dayOfBirth, String email, String phoneNumber, String idEmp, String position, float basicWages, float experience, int dayOntheMonth, float receiveWages, float bonus, Date startDay, Date endDay) { super(idCard, fullName, address, dayOfBirth, email, phoneNumber, idEmp, position, basicWages, experience, dayOntheMonth, receiveWages, bonus); this.startDay = startDay; this.endDay = endDay; } public final Date getStartDay() { return startDay; } public final void setStartDay(Date startDay) { this.startDay = startDay; } public final Date getEndDay() { return endDay; } public final void setEndDay(Date endDay) { this.endDay = endDay; } @Override public void calcularWages() { setWages((getBasicWages() / 22) * getDayOntheMonth() + getBonus()); } @Override public void receiveWages() { System.out.println("Giám đốc " + getFullName() + " đã nhận " + getWages() + " tiền lương"); } @Override public void calcularBonus() { if (getDayOntheMonth() >= 22) { setBonus(getBasicWages() * 0.25f); } else { setBonus(0); } } @Override public void receiveBonus() { System.out.println("Giám đốc " + getFullName() + " đã nhận " + getBonus() + " tiền thưởng"); } }
/* * Copyright 2015 Eduard Scarlat * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.futuretechnology.util; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Handler; import android.os.StrictMode; import me.futuretechnology.blops.BuildConfig; /** * Copyright 2015 Eduard Scarlat */ public class Utils { private static final String TAG = "UTILS"; /** * @return Application's version name from the {@code PackageManager}. */ public static String getAppVersionName(Context context) { try { // noinspection ConstantConditions PackageInfo packageInfo = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); return packageInfo.versionName; } catch (PackageManager.NameNotFoundException e) { // should never happen Log.printStackTrace(TAG, e); return "0.0"; } } public static void setStrictMode(final boolean enable) { if (!BuildConfig.DEBUG) { return; } doSetStrictMode(enable); // fix for http://code.google.com/p/android/issues/detail?id=35298 // restore strict mode after onCreate() returns. new Handler().postAtFrontOfQueue(new Runnable() { @Override public void run() { doSetStrictMode(enable); } }); } private static void doSetStrictMode(boolean enable) { if (enable) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll() .penaltyLog().build()); // .penaltyDialog() StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog() .build()); } else { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().penaltyLog().build()); } } }
package com.example.demo.services; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import com.example.demo.dao.EmployeeRepo; import com.example.demo.exception.UserBlockedException; import com.example.demo.model.Employee; @Service public class EmployeeServices { public static final Integer LOGIN_STATUS_ACVTIVE=1; public static final Integer LOGIN_STATUS_BLOCKED=2; public static final Integer ROLE_ADMIN=1; public static final Integer ROLE_USER=2; @Autowired JdbcTemplate temp; public Employee loginEmail(String username, String password) throws UserBlockedException { String sql="SELECT eid, e_email, e_department, e_firstname, e_password, e_lastname, e_phone, erole, e_img FROM employee WHERE e_email=? AND " + "e_password=?"; Map m= new HashMap(); m.put("e_email",username); m.put("e_password",password); try { Employee e= (Employee) temp.queryForObject(sql, m.values().toArray(), new EmployeeRowMapper()); return e; }catch(EmptyResultDataAccessException e) { return null; } } public Employee loginphone(String phone, String password) throws UserBlockedException { String sql="SELECT eid, e_email, e_department, e_firstname, e_password, e_lastname, e_phone, erole, e_img FROM employee WHERE e_phone=? AND " + "e_password=?"; Map m= new HashMap(); m.put("e_phone",phone); m.put("e_password",password); try { Employee e= (Employee) temp.queryForObject(sql, m.values().toArray(), new EmployeeRowMapper()); return e; }catch(EmptyResultDataAccessException e) { return null; } } }
/** * @Title: ListUtils.java * @package com.rofour.baseball.tools * @Project: axp-tools * @Description: (用一句话描述该文件做什么) * @author wjj * @date 2016年4月2日 下午10:38:14 * @version V1.0 * ────────────────────────────────── * Copyright (c) 2016, 指端科技. */ package com.rofour.baseball.common; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @ClassName: ListUtils * @Description: TODO(这里用一句话描述这个类的作用) * @author wjj * @date 2016年4月2日 下午10:38:14 * */ public class ListUtils { /** * 分組依据接口,用于集合分组时,获取分組依据 */ public interface GroupBy<T> { T groupby(Object obj); } /** * * 分组 */ public static final <T extends Comparable<T>, D> Map<T, List<D>> group(Collection<D> colls, GroupBy<T> gb) { if (colls == null || colls.isEmpty()) { System.out.println("分组集合不能为空!"); return null; } if (gb == null) { System.out.println("分组依据接口不能为Null!"); return null; } Iterator<D> iter = colls.iterator(); Map<T, List<D>> map = new HashMap<T, List<D>>(); while (iter.hasNext()) { D d = iter.next(); T t = gb.groupby(d); if (map.containsKey(t)) { map.get(t).add(d); } else { List<D> list = new ArrayList<D>(); list.add(d); map.put(t, list); } } return map; } /** * 深层拷贝 - 需要类继承序列化接口 * @param <T> * @param obj * @return * @throws Exception */ // @SuppressWarnings("unchecked") // public static <T> T copyImplSerializable(T obj) throws Exception { // ByteArrayOutputStream baos = null; // ObjectOutputStream oos = null; // // ByteArrayInputStream bais = null; // ObjectInputStream ois = null; // // Object o = null; // //如果子类没有继承该接口,这一步会报错 // try { // baos = new ByteArrayOutputStream(); // oos = new ObjectOutputStream(baos); // oos.writeObject(obj); // bais = new ByteArrayInputStream(baos.toByteArray()); // ois = new ObjectInputStream(bais); // // o = ois.readObject(); // return (T) o; // } catch (Exception e) { // throw new Exception("对象中包含没有继承序列化的对象"); // } finally{ // try { // baos.close(); // oos.close(); // bais.close(); // ois.close(); // } catch (Exception e2) { // //这里报错不需要处理 // } // } // } }
/******************************************************************************* * Besiege * by Kyle Dhillon * Source Code available under a read-only license. Do not copy, modify, or distribute. ******************************************************************************/ package kyle.game.besiege.party; import kyle.game.besiege.panels.BottomPanel; import com.badlogic.gdx.utils.Array; import static kyle.game.besiege.party.OldArmor.*; public enum OldWeapon { // also have a default armor // Tier 0 (Best total = 1) PITCHFORK (0, "Pitchfork", "Farmer", 1, 0, -1, false, false, CLOTHES), // Tier 2? MILITARY_FORK (2, "Military Fork", "Militia", 1, 1, -1, false, false, CLOTHES), // Tier 4 (Best total = 2) SPEAR (4, "Spear", "Spearman", 2, 1, -1, false, false, LEATHER), HATCHET (4, "Hatchet", "Axeman", 2, 0, 0, true, false, LEATHER), CLUB (4, "Cudgel", "Clubman", 2, 0, 0, true, true, LEATHER), // Tier 4 Ranged SHORTBOW (4, "Dagger", "Archer", -1, -2, 0, true, false, CLOTHES), // Tier 6 Mounted (Best total = 2) CAVALRY_SPEAR (6, "Cavalry Spear", "Horseman", 3, 0, -1, false, false, LEATHER), CAVALRY_AXE (6, "Cavalry Axe", "Horseman", 2, 0, 0, true, false, LEATHER), CAVALRY_PICK (6, "Cavalry Pick", "Horseman", 3, -1, 0, true, false, LEATHER), // Tier 6 (Best total = 3) PIKE (6, "Pike", "Pikeman", 2, 3, -2, false, false, LIGHTPLATE), HALBERD (6, "Halberd", "Poleman", 3, 2, -2, false, false, LIGHTPLATE), LONGSWORD (6, "Longsword", "Swordsman", 2, 2, -1, false, false, CHAINMAIL), BATTLE_AXE (6, "Battle Axe", "Axeman", 3, 1, -1, false, false, CHAINMAIL), SHORTSWORD (6, "Shortsword", "Swordsman", 2, 1, 0, true, false, STUDDED), WAR_HAMMER (6, "War Hammer", "Hammerman", 3, 0, 0, true, true, STUDDED), MACE (6, "Mace", "Maceman", 2, 1, 0, true, true, STUDDED), // Tier 6 Ranged CROSSBOW (6, "Dagger", "Crossbowman", 0, -1, 0, true, false, LEATHER), RECURVE (6, "Dagger", "Bowman", 0, -1, 0, true, false, LEATHER), LONGBOW (6, "Dagger", "Longbowman", 0, -1, 0, true, false, LEATHER), // Tier 8 Mounted (Tier '7') LANCE (8, "Lance", "Lancer", 4, 1, -1, false, false, CHAINMAIL), ARMING_SWORD (8, "Arming Sword", "Slicer", 3, 1, 0, true, false, LIGHTPLATE), FLAIL (8, "Flail", "Flailer", 4, 0, 0, true, false, LIGHTPLATE), // Tier 8 (Best total = 4) GUISARME (8, "Guisarme", "Pikemaster", 3, 3, -2, false, false, HEAVYPLATE), VOULGE (8, "Voulge", "Blademaster", 4, 2, -2, false, false, HEAVYPLATE), GREATSWORD (8, "Claymore", "Swordmaster", 3, 2, -1, false, false, HEAVYPLATE), GLAIVE (8, "Glaive", "Axemaster", 4, 1, -1, false, false, HEAVYPLATE), FALCHION (8, "Falchion", "Sabermaster", 3, 1, 0, true, false, HEAVYPLATE), MAUL (8, "Maul", "Hammermaster", 4, 1, -1, false, true, HEAVYPLATE), MORNINGSTAR (8, "Morningstar", "Macemaster", 3, 1, 0, true, true, HEAVYPLATE), // Tier 8 Ranged ADV_CROSSBOW (8, "Shortsword", "Crossbow Master", -1, -2, 0, true, false, CHAINMAIL), ADV_RECURVE (8, "Shortsword", "Bowmaster", -1, -2, 0, true, false, STUDDED), ADV_LONGBOW (8, "Shortsword", "Longbow Master", -1, -2, 0, true, false, LEATHER); // 0 1, 2, 3, 4, 5, 6, 7, 8, 9 public static final int[] TIER_COST = {0, 0, 5, 10, 15, 25, 40, 60, 80, 120}; //public static final int[] UPG_COST = {0, 0, 5, 0, 10, 0, 15, 0, 25, 0}; public final int tier; public final String name; public final String troopName; public final int atkMod; public final int defMod; public final int spdMod; public final boolean oneHand; public final boolean blunt; public final OldArmor oldArmor; public static Array<OldWeapon> all; public static Array<OldWeapon> bandit; public static Array<OldWeapon> city; //public final int cost; // cost to purchase private OldWeapon(int tier, String name, String troopName, int atkMod, int defMod, int spdMod, boolean oneHand, boolean blunt, OldArmor oldArmor) { this.tier = tier; this.name = name; this.troopName = troopName; this.atkMod = atkMod; this.defMod = defMod; this.spdMod = spdMod; this.oneHand = oneHand; this.blunt = blunt; this.oldArmor = oldArmor; } public static RangedWeapon getRanged(OldWeapon oldWeapon) { if (oldWeapon == OldWeapon.SHORTBOW) return RangedWeapon.SHORTBOW; if (oldWeapon == OldWeapon.LONGBOW) return RangedWeapon.LONGBOW; if (oldWeapon == OldWeapon.CROSSBOW)return RangedWeapon.CROSSBOW; if (oldWeapon == OldWeapon.RECURVE) return RangedWeapon.RECURVE; if (oldWeapon == OldWeapon.ADV_LONGBOW) return RangedWeapon.ADV_LONGBOW; if (oldWeapon == OldWeapon.ADV_CROSSBOW) return RangedWeapon.ADV_CROSSBOW; if (oldWeapon == OldWeapon.ADV_RECURVE) return RangedWeapon.ADV_RECURVE; else return null; } public static void load() { OldWeapon[] banditArray = {PITCHFORK, SPEAR, MACE, CLUB, HATCHET}; bandit = new Array<OldWeapon>(banditArray); } // public static int getUpgradeCost(int tier) { // if (tier == TIER_COST.length) return 999999; // return (TIER_COST[tier]-TIER_COST[tier-1]); // } public static Array<OldWeapon> upgrade(OldWeapon oldWeapon) { Array<OldWeapon> upgrades = new Array<OldWeapon>(); switch (oldWeapon) { case PITCHFORK : upgrades.add(MILITARY_FORK); break; case MILITARY_FORK : upgrades.add(SPEAR); upgrades.add(HATCHET); upgrades.add(CLUB); break; case SPEAR : upgrades.add(PIKE); upgrades.add(HALBERD); upgrades.add(LONGSWORD); break; case HATCHET : upgrades.add(LONGSWORD); upgrades.add(BATTLE_AXE); upgrades.add(SHORTSWORD); break; case CLUB : upgrades.add(SHORTSWORD); upgrades.add(WAR_HAMMER); upgrades.add(MACE); break; case PIKE : upgrades.add(GUISARME); break; case HALBERD : upgrades.add(GLAIVE); break; case LONGSWORD : upgrades.add(GREATSWORD); break; case BATTLE_AXE : upgrades.add(VOULGE); break; case SHORTSWORD : upgrades.add(FALCHION); break; case WAR_HAMMER : upgrades.add(MAUL); break; case MACE : upgrades.add(MORNINGSTAR); break; case CAVALRY_SPEAR : upgrades.add(LANCE); break; case CAVALRY_AXE : upgrades.add(ARMING_SWORD); break; case CAVALRY_PICK : upgrades.add(FLAIL); break; // ranged case SHORTBOW : upgrades.add(CROSSBOW); upgrades.add(RECURVE); upgrades.add(LONGBOW); break; case CROSSBOW : upgrades.add(ADV_CROSSBOW); break; case RECURVE : upgrades.add(ADV_RECURVE); break; case LONGBOW : upgrades.add(ADV_LONGBOW); break; default : BottomPanel.log("Upgrade for \"" + oldWeapon.name + "\" not found!"); } return upgrades; } public int getCost() { return TIER_COST[this.tier]; } }
package com.demo.controller; import com.demo.entity.Weather; import com.demo.model.WeatherSummary; import com.demo.repository.IWeatherRepository; import com.demo.service.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/weather") public class WeatherController { @Value("${api.key}") private String apiId; @Autowired private RestTemplate restTemplate; @Autowired Service service; @Autowired IWeatherRepository weatherRepository; @GetMapping("/{cityName}") public void getWeatherInfo(@PathVariable String cityName) { WeatherSummary weatherSummary = restTemplate.getForObject("https://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&api_key=" + apiId, WeatherSummary.class); Weather weather = new Weather(weatherSummary); weatherRepository.save(weather); } @GetMapping("/palindrome") public ResponseEntity<Boolean> getPalindrome(@RequestParam String s) { boolean b = service.getPalindrome(s); return new ResponseEntity<>(b, HttpStatus.OK); } }
package com.sysh.mapper; import com.sysh.entity.helpmea.EcologicalPovertyDD; public interface EcologicalPovertyDDMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table TBL_ECOLOGICAL_POVERTY * * @mbg.generated */ int deleteByPrimaryKey(Short id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table TBL_ECOLOGICAL_POVERTY * * @mbg.generated */ int insert(EcologicalPovertyDD record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table TBL_ECOLOGICAL_POVERTY * * @mbg.generated */ int insertSelective(EcologicalPovertyDD record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table TBL_ECOLOGICAL_POVERTY * * @mbg.generated */ EcologicalPovertyDD selectByPrimaryKey(Short id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table TBL_ECOLOGICAL_POVERTY * * @mbg.generated */ int updateByPrimaryKeySelective(EcologicalPovertyDD record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table TBL_ECOLOGICAL_POVERTY * * @mbg.generated */ int updateByPrimaryKey(EcologicalPovertyDD record); EcologicalPovertyDD findEcologicalPovertyByID(String idNumber); EcologicalPovertyDD findEcologicalPovertyByID1(String idNumber); }
package com.jk.jkproject.net.im; import android.util.Log; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; public class MessageEncoder extends OneToOneEncoder { protected Object encode(ChannelHandlerContext channelHandlerContext, Channel channel, Object obj) throws Exception { if (!(obj instanceof RequestPacket)) return obj; byte[] arrayOfByte = ((RequestPacket)obj).produceByteArray(); Log.e("===encode=", obj.toString()); ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer(); channelBuffer.writeBytes(arrayOfByte); return channelBuffer; } }
package com.example.administrator.hyxdmvp.ui.presenter.login; import com.example.administrator.hyxdmvp.bean.LoginBean; public interface ILoginPresenter { void success(LoginBean bean); void fail(String s); void goRequest(String userName , String pws ); void onDestroy(); }
/* * 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 sketchit; import javafx.scene.shape.Line; import javafx.scene.shape.Shape; /** * * @author Mason */ public class LineBrush extends Brush { Line line; @Override public Shape startBrush(double x, double y) { line = new Line(); line.setStroke(color); line.setStrokeWidth(stroke); line.setStartX(x); line.setStartY(y); line.setEndX(x); line.setEndY(y); return line; } @Override public Shape brush(double x, double y) { line.setEndX(x); line.setEndY(y); return line; } @Override public Shape stopBrush(double x, double y) { brush(x, y); return line; } }
import javax.swing.*; public class Main extends JFrame implements Constans { public Main(){ setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); setSize(BOARD_HEIGHT, BOARD_WIDTH); setResizable(false); add(new Board()); } public static void main(String[] args) { new Main(); } }
package skiplist; import java.lang.reflect.Array; import java.lang.IllegalStateException; import java.util.AbstractList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Random; /** * Implements the List interface as a skiplist so that all the * standard operations take O(log n) time */ public class FastDefaultList<T> extends AbstractList<T> { class Node { T x; Node[] next; int[] length; @SuppressWarnings("unchecked") public Node(T ix, int h) { x = ix; next = (Node[])Array.newInstance(Node.class, h+1); length = new int[h+1]; } public int height() { return next.length - 1; } } /** * This node sits on the left side of the skiplist */ protected Node sentinel; /** * The maximum height of any element */ int h; /** * The number of elements stored in the skiplist */ //int n; //don't need this anymore /** * A source of random numbers */ Random rand; public FastDefaultList() { //n = 0; sentinel = new Node(null, 32); h = 0; rand = new Random(0); } /** * Represents a node/index Pair */ protected class Pair { Node u; int i; Pair(Node u, int i) { this.u = u; this.i = i; } } /** * Find the node that precedes list index i in the skiplist. * @param x - the value to search for * @return the predecessor of the node at index i or the final * node if i exceeds size() - 1. */ protected Pair findPred(int i) { // It's not enough to know u, you also need the value j, // maybe change the return type to Pair and return the pair (u,j) Node u = sentinel; int r = h; int j = -1; // index of the current node in list 0 while (r >= 0) { while (u.next[r] != null && j + u.length[r] < i) { j += u.length[r]; u = u.next[r]; } r--; } return new Pair (u,j); } public T get(int i) { // this is too restrictive any non-negative i is allowed if (i < 0) throw new IndexOutOfBoundsException(); //removed n as don't need this anymore Pair p = findPred(i); if(p.u.next[0] != null){ if(p.i + p.u.length[0] == i){ return p.u.next[0].x; } } return null; } public T set(int i, T x) { // this is too restrictive any non-negative i is allowed if (i < 0) throw new IndexOutOfBoundsException(); // Node u = findPred(i).next[0]; Pair p = findPred(i); // T y = p.u.x; // p.u.x = x; // return y; if (p.u.next[0] != null) { if (p.i + p.u.length[0] == i) { Node u = p.u.next[0]; T y = u.x; u.x = x; return y; } } // A new Node Node w = new Node(x, pickHeight()); if (w.height() > h) { h = w.height(); } // reset high if w next() array is higher than sentinel setter(i, w); //add new node without pushing other Node forward return null; } //simply copy the add() method protected Node setter(int i, Node w) { Node u = sentinel; int k = w.height(); int r = h; int j = -1; // index of u while (r >= 0) { while (u.next[r] != null && j+u.length[r] < i) { j += u.length[r]; u = u.next[r]; } //u.length[r]++; // accounts for new node in list 0 // since we just set the current index with new datae // we don't have to increase the length as we are not pushing node forward if (r <= k) { w.next[r] = u.next[r]; u.next[r] = w; w.length[r] = u.length[r] - (i - j); u.length[r] = i - j; } r--; } //n++; //removed n as Hint: You don't need this anymore! return u; } /** * Insert a new node into the skiplist * @param i the index of the new node * @param w the node to insert * @return the node u that precedes v in the skiplist */ protected Node add(int i, Node w) { Node u = sentinel; int k = w.height(); int r = h; int j = -1; // index of u while (r >= 0) { while (u.next[r] != null && j+u.length[r] < i) { j += u.length[r]; u = u.next[r]; } u.length[r]++; // accounts for new node in list 0 if (r <= k) { w.next[r] = u.next[r]; u.next[r] = w; w.length[r] = u.length[r] - (i - j); u.length[r] = i - j; } r--; } //n++; //removed n as Hint: You don't need this anymore! return u; } /** * Simulate repeatedly tossing a coin until it comes up tails. * Note, this code will never generate a height greater than 32 * @return the number of coin tosses - 1 */ protected int pickHeight() { int z = rand.nextInt(); int k = 0; int m = 1; while ((z & m) != 0) { k++; m <<= 1; } return k; } public void add(int i, T x) { // Hint: bounds checking again! if (i < 0) throw new IndexOutOfBoundsException(); Node w = new Node(x, pickHeight()); if (w.height() > h) h = w.height(); add(i, w); } public T remove(int i) { if (i < 0) throw new IndexOutOfBoundsException(); T x = null; Node u = sentinel; int r = h; int j = -1; // index of node u while (r >= 0) { while (u.next[r] != null && j+u.length[r] < i) { j += u.length[r]; u = u.next[r]; } u.length[r]--; // for the node we are removing if (j + u.length[r] + 1 == i && u.next[r] != null) { x = u.next[r].x; u.length[r] += u.next[r].length[r]; u.next[r] = u.next[r].next[r]; if (u == sentinel && u.next[r] == null) h--; } r--; } //n--; //removed n as Hint: You don't need this anymore! return x; } public int size() { return Integer.MAX_VALUE; } public String toString() { // This is just here to help you a bit with debugging StringBuilder sb = new StringBuilder(); int i = -1; Node u = sentinel; while (u.next[0] != null) { i += u.length[0]; u = u.next[0]; sb.append(" " + i + " => " + u.x); } return sb.toString(); } public static void main(String[] args) { // put your test code here if you like List<String> list = new FastDefaultList<String>(); System.out.println("Call get 1000: " + list.get(1000)); list.add(1000, "Angle"); System.out.println("Call get 1000 after add(): " + list.get(1000)); System.out.println("==========================="); list.add(25, "Stacee"); System.out.println("Call get 1000 after add on idx 25: " + list.get(1000)); System.out.println("Call get 25: " + list.get(25)); System.out.println("Call get 1001: " + list.get(1001)); System.out.println("==========================="); list.remove(1001); System.out.println("Remove index 1001 after remove(): " + list.get(1001)); System.out.println("==========================="); list.add(0,"Rent"); list.add(1,"Mark"); list.set(25,"Collins"); list.set(50,"Mimi"); System.out.println("Added Rent at index 0 and Mark at index 1."); System.out.println("Set index 25 as Collins and 50 as Mimi."); System.out.println("Now the list contain: " + list); } }
package searchcodej.util; import static org.junit.Assert.*; import org.junit.Test; public class RegexMatchTest { @Test public void testMatchInsideOtherMatch() throws Exception { //when both are equals RegexMatch match1 = new RegexMatch(1, 2); RegexMatch match2 = new RegexMatch(1, 2); assertTrue(match1.isInside(match2)); assertTrue(match2.isInside(match1)); //when match2 is smaller and inside match1 match1 = new RegexMatch(0, 3); match2 = new RegexMatch(1, 2); assertTrue(match2.isInside(match1)); assertFalse(match1.isInside(match2)); //when match1 is smaller and inside match2 match1 = new RegexMatch(1, 2); match2 = new RegexMatch(0, 3); assertTrue(match1.isInside(match2)); assertFalse(match2.isInside(match1)); } @Test public void testMatchAfterOtherMatch() throws Exception { RegexMatch match1 = new RegexMatch(1, 2); RegexMatch match2 = new RegexMatch(0, 1); assertTrue(match1.isAfter(match2)); assertFalse(match2.isAfter(match1)); } @Test public void testMatchBeforeOtherMatch() throws Exception { RegexMatch match1 = new RegexMatch(0, 1); RegexMatch match2 = new RegexMatch(1, 2); assertTrue(match1.isBefore(match2)); assertFalse(match2.isBefore(match1)); } @Test public void testNoConflictMatchesDontTouchBorders() throws Exception { //case = |match1| |match2| RegexMatch match1 = new RegexMatch(0, 1); RegexMatch match2 = new RegexMatch(4, 5); assertNotEquals(match1, match2); assertFalse(match1.testConflict(match2)); //case = |match2| |match1| match1 = new RegexMatch(4, 5); match2 = new RegexMatch(0, 1); assertNotEquals(match1, match2); assertFalse(match1.testConflict(match2)); } @Test public void testNoConflictMatchesTouchingBorders() throws Exception { //case = |match1||match2| RegexMatch match1 = new RegexMatch(0, 1); RegexMatch match2 = new RegexMatch(1, 2); assertNotEquals(match1, match2); assertFalse(match1.testConflict(match2)); //case = |match2||match1| match1 = new RegexMatch(1, 2); match2 = new RegexMatch(0, 1); assertNotEquals(match1, match2); assertFalse(match1.testConflict(match2)); } @Test public void testConflictMatchesEquals() throws Exception { RegexMatch match = new RegexMatch(0, 1); RegexMatch sameMatch = new RegexMatch(0, 1); assertEquals(match, sameMatch); assertTrue(match.testConflict(sameMatch)); } @Test(expected = IllegalArgumentException.class) public void testMatchWithEndLowerThanBegin() { int begin = 0; int end = -1; RegexMatch m = new RegexMatch(begin, end); } @Test(expected = IllegalArgumentException.class) public void testMatchWithBeginEqualsEnd() { int begin = 0; int end = 0; RegexMatch m = new RegexMatch(begin, end); } @Test public void testToString() throws Exception { int begin = 0; int end = 1; RegexMatch m = new RegexMatch(begin, end); assertEquals("[0,1]", m.toString()); } }
package pl.edu.pw.mini.gapso.optimizer.move; import org.junit.Assert; import org.junit.Test; import pl.edu.pw.mini.gapso.configuration.MoveConfiguration; import pl.edu.pw.mini.gapso.function.ConvexSquareFunction; import pl.edu.pw.mini.gapso.function.Function; import pl.edu.pw.mini.gapso.function.FunctionWhiteBox; import pl.edu.pw.mini.gapso.initializer.RandomInitializer; import pl.edu.pw.mini.gapso.model.FullSquareModel; import pl.edu.pw.mini.gapso.optimizer.MySamplingOptimizer; import pl.edu.pw.mini.gapso.optimizer.Particle; import pl.edu.pw.mini.gapso.optimizer.Swarm; import java.util.ArrayList; import java.util.List; public class GlobalModelTest { @Test public void getNext() { List<ModelMove.ModelParameters> parameters = new ArrayList<>(); parameters.add(new ModelMove.ModelParameters( FullSquareModel.NAME, 2 )); MoveConfiguration moveConfigurationModel = new MoveConfiguration( LocalBestModel.NAME, 0.0, 1, false, new ModelMove.ModelSequenceParameters( parameters, SamplesClusteringType.NONE ) ); MySamplingOptimizer samplingOptimizer = new MySamplingOptimizer(); GlobalModel globalModel = new GlobalModel(moveConfigurationModel); FunctionWhiteBox function = new ConvexSquareFunction(); RandomInitializer generator = new RandomInitializer(); globalModel.registerObjectsWithOptimizer(samplingOptimizer); Function wrappedFunction = samplingOptimizer.wrapFunction(function); for (int i = 0; i < 100; ++i) { Assert.assertEquals(i, samplingOptimizer.samplerList.get(0).getSamplesCount()); double[] sample = generator.getNextSample(wrappedFunction.getBounds()); wrappedFunction.getValue(sample); } Swarm swarm = new Swarm(); double[] sample = generator.getNextSample(wrappedFunction.getBounds()); Particle p = new Particle(sample, wrappedFunction, swarm); double[] modelResult = globalModel.getNext(p, swarm.getParticles()); Assert.assertNotEquals(function.getOptimumLocation()[0], modelResult[0], 1e-8); Assert.assertNotEquals(function.getOptimumLocation()[1], modelResult[1], 1e-8); modelResult = globalModel.getNext(p, swarm.getParticles()); Assert.assertArrayEquals(function.getOptimumLocation(), modelResult, 1e-8); modelResult = globalModel.getNext(p, swarm.getParticles()); Assert.assertNotEquals(function.getOptimumLocation()[0], modelResult[0], 1e-8); Assert.assertNotEquals(function.getOptimumLocation()[1], modelResult[1], 1e-8); modelResult = globalModel.getNext(p, swarm.getParticles()); Assert.assertArrayEquals(function.getOptimumLocation(), modelResult, 1e-8); } }
package pl.java.scalatech.lifecycle.handler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ResourceLoaderAware; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; @Component public class ResourceAwareHandler implements ResourceLoaderAware { private ResourceLoader resourceLoader; public void showFileContent() throws IOException { Resource banner = resourceLoader.getResource("classpath:text.txt"); try (InputStream in = banner.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { while (true) { String line = reader.readLine(); if (line == null) break; System.out.println(line); } } } public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } }
package com.tencent.mm.g.a; public final class kf$a { public int type; }
package io.fab.connector.processors; import org.springframework.stereotype.Component; import io.fab.connector.data.CatalogEventMessage; @Component public class OrderDelayEventProcessorStrategy implements CatalogEventProcessorStrategy { @Override public void processCatalogEvent(final CatalogEventMessage message) { // TODO Auto-generated method stub } }
package com.tencent.mm.protocal; import com.tencent.mm.protocal.c.awe; import com.tencent.mm.protocal.k.c; import com.tencent.mm.protocal.k.e; public final class s { public static class b extends e implements c { public awe qWX = new awe(); public final int G(byte[] bArr) { this.qWX = (awe) new awe().aG(bArr); return this.qWX.rfn; } public final int getCmdId() { return 1000000121; } } }
package edu.uci.ics.sdcl.firefly.storage; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import edu.uci.ics.sdcl.firefly.report.analysis.FilterContent; import edu.uci.ics.sdcl.firefly.report.voting.AnalysisPath; /** * Class used in the data analysis process * * @author Christian Adriano * */ public class FilterContentStorage { private String persistentFileName = "filtercontent.ser"; public FilterContentStorage(){} public void write(ArrayList<FilterContent> filterContentList){ try{ //PropertyManager manager = PropertyManager.initializeSingleton(); AnalysisPath analysisPath = AnalysisPath.getInstance(); String path = analysisPath.analysisTypePath; this.persistentFileName = path + this.persistentFileName; ObjectOutputStream objOutputStream = new ObjectOutputStream( new FileOutputStream(new File(this.persistentFileName))); objOutputStream.writeObject( filterContentList ); objOutputStream.close(); } catch(IOException exception){ exception.printStackTrace(); } catch(Exception exception){ exception.printStackTrace(); } } public ArrayList<FilterContent> read(){ try{ AnalysisPath analysisPath = AnalysisPath.getInstance(); String path = analysisPath.analysisTypePath; this.persistentFileName = path + this.persistentFileName; ObjectInputStream objInputStream = new ObjectInputStream( new FileInputStream(new File(this.persistentFileName))); ArrayList<FilterContent> filterContentList = (ArrayList<FilterContent>) objInputStream.readObject(); objInputStream.close(); return filterContentList; } catch(IOException exception){ exception.printStackTrace(); return null; } catch(Exception exception){ exception.printStackTrace(); return null; } } }
package info.rothem.sales.salesbackend.controller; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedHashMap; import java.util.Map; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class LoginController { @Autowired private DataSource datasource; @CrossOrigin(origins = "http://localhost:7000") @RequestMapping("/login") public Map<String, Integer> auth(@RequestParam String username, @RequestParam String password) { Map<String, Integer> data = new LinkedHashMap<>(); try { Connection con = datasource.getConnection(); PreparedStatement ps = con.prepareStatement("SELECT * FROM user WHERE username = ?"); ps.setString(1, username); ResultSet rs = ps.executeQuery(); if(rs.next()) { if(password.equals(rs.getString("password"))) { data.put("status", 1); } else { data.put("status", 0); } } else { data.put("status", 0); } rs.close(); ps.close(); con.close(); }catch(SQLException sqle) { sqle.printStackTrace(); } return data; } }
/* -*- Mode:jde; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /** * Copyright (c) 2015 Regents of the University of California * * This file is part of NFD (Named Data Networking Forwarding Daemon) Android. * See AUTHORS.md for complete list of NFD Android authors and contributors. * * NFD Android is free software: you can redistribute it and/or modify it under the terms * of the GNU General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * NFD Android 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along with * NFD Android, e.g., in COPYING.md file. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.ucl.umobile.ui.fragments; import android.app.Activity; import android.app.ActivityManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.Messenger; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.Switch; import android.widget.TextView; import uk.ac.ucl.umobile.R; import uk.ac.ucl.umobile.data.UmobileService; import uk.ac.ucl.umobile.utils.G; import java.util.ArrayList; //import android.support.v7.app.ActionBarActivity; /** * DrawerFragment that provides navigation for MainActivity. */ public class DrawerFragment extends Fragment { public static DrawerFragment newInstance(ArrayList<DrawerItem> items) { Bundle drawerParams = new Bundle(); drawerParams.putParcelableArrayList(DrawerFragment.BUNDLE_PARAMETERS, items); DrawerFragment fragment = new DrawerFragment(); fragment.setArguments(drawerParams); return fragment; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { // Register callback m_callbacks = (DrawerCallbacks)activity; } catch (ClassCastException e) { throw new ClassCastException("Host activity must implement DrawerFragment.DrawerCallbacks."); } } @Override public void onDetach() { super.onDetach(); m_callbacks = null; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Read in the flag indicating whether or not the user has demonstrated awareness of the // drawer. See PREF_DRAWER_SHOWN_TO_USER_FOR_THE_FIRST_TIME for details. SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity()); m_hasUserSeenDrawer = sp.getBoolean(PREF_DRAWER_SHOWN_TO_USER_FOR_THE_FIRST_TIME, false); if (savedInstanceState != null) { m_drawerSelectedPosition = savedInstanceState.getInt(DRAWER_SELECTED_POSITION_BUNDLE_KEY); m_restoredFromSavedInstanceState = true; } m_drawerItems = getArguments().getParcelableArrayList(BUNDLE_PARAMETERS); //bindService(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View drawer = inflater.inflate( R.layout.activity_main_drawer_listview, container, false); m_drawerListView = drawer.findViewById(R.id.drawer_listview); // m_drawerListView = (ListView)inflater.inflate( // R.layout.activity_main_drawer_listview, container, false); m_drawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Update UI updateSelection(position); } }); m_drawerListView.setAdapter(new DrawerListAdapter(getContext(),m_drawerItems)); m_drawerListView.setItemChecked(m_drawerSelectedPosition, true); m_serviceStartStopSwitch = drawer.findViewById(R.id.serviceSwitch); m_serviceStartStopSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isOn) { if (isOn) { // isSource.setEnabled(false); startUbiCDNService(); } else { // isSource.setEnabled(true); stopUbiCDNService(); } } }); return drawer; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Fragment influences action bar setHasOptionsMenu(true); // Initialize and set up the navigation drawer UI initializeDrawerFragment(getActivity().findViewById(R.id.navigation_drawer), (DrawerLayout)getActivity().findViewById(R.id.drawer_layout)); if (savedInstanceState == null) { // when restoring (e.g., after rotation), rely on system to restore previous state of // fragments updateSelection(m_drawerSelectedPosition); } } /** * Initialize drawer fragment after being attached to the host activity. * * @param drawerFragmentViewContainer View container that holds the navigation drawer * @param drawerLayout DrawerLayout of the drawer in the host Activity */ private void initializeDrawerFragment(View drawerFragmentViewContainer, DrawerLayout drawerLayout) { m_drawerFragmentViewContainer = drawerFragmentViewContainer; m_drawerLayout = drawerLayout; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(DRAWER_SELECTED_POSITION_BUNDLE_KEY, m_drawerSelectedPosition); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Forward the new configuration the drawer toggle component. //m_drawerToggle.onConfigurationChanged(newConfig); } @Override public void onResume() { bindService(); super.onResume(); } @Override public void onPause() { unbindService(); super.onPause(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); // Update menu UI when the drawer is open. This gives the user a better // contextual perception of the application. if (isDrawerOpen()) { // Inflate drawer specific menu here (if any) showGlobalContextActionBar(); } } @Override public void onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // Remove option menu items when drawer is sliding out if (m_shouldHideOptionsMenu) { for (int i = 0; i < menu.size(); i++) { menu.getItem(i).setVisible(false); } } } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle drawer selection events /* if (m_drawerToggle.onOptionsItemSelected(item)) { return true; }*/ // Handle other menu items switch (item.getItemId()) { // Handle activity menu item here (if any) default: return super.onOptionsItemSelected(item); } } public boolean shouldHideOptionsMenu() { return m_shouldHideOptionsMenu; } /** * Convenience method that updates the UI and callbacks the host activity. * * @param position Position of the selected item within the Drawer's ListView. */ private void updateSelection(int position) { // Update Position m_drawerSelectedPosition = position; // Update UI of selected position if (m_drawerListView != null) { m_drawerListView.setItemChecked(position, true); } // Close drawer if (m_drawerLayout != null) { m_drawerLayout.closeDrawer(m_drawerFragmentViewContainer); } // Invoke host activity callback if (m_callbacks != null) { DrawerItem item = m_drawerItems.get(position); m_callbacks.onDrawerItemSelected(item.getItemCode(), item.getItemName()); } } /** * Safe convenience method to determine if drawer is open. * * @return True if drawer is present and in an open state; false otherwise */ private boolean isDrawerOpen() { return m_drawerLayout != null && m_drawerLayout.isDrawerOpen(m_drawerFragmentViewContainer); } /** * Convenience method to update host activity action bar so that the user is informed of * the app's "current context" of the fragment. */ private void showGlobalContextActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); } /** * Convenience method to get host activity's ActionBar. This makes for easy updates * in a single location when upgrading to use >= HONEYCOMB (API 11) ActionBar. * * @return Host activity's ActionBar. */ private ActionBar getActionBar() { return ((AppCompatActivity)getActivity()).getSupportActionBar(); } ////////////////////////////////////////////////////////////////////////////// /** * DrawerItem represents a single selection option in the Drawer, complete * with the ability to set a Drawable resource icon for display along * with the drawer item name. */ public static class DrawerItem implements Parcelable { @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeInt(m_itemNameId); parcel.writeInt(m_iconResId); parcel.writeInt(m_itemCode); } public static final Creator<DrawerItem> CREATOR = new Creator<DrawerItem>() { public DrawerItem createFromParcel(Parcel in) { return new DrawerItem(in.readInt(), in.readInt(), in.readInt()); } public DrawerItem[] newArray(int size) { return new DrawerItem[size]; } }; public DrawerItem(int itemNameId, int resIconId, int itemCode) { m_itemNameId = itemNameId; m_iconResId = resIconId; m_itemCode = itemCode; } public int getItemName() { return m_itemNameId; } public int getIconResId() { return m_iconResId; } public int getItemCode() { return m_itemCode; } /////////////////////////////////////////////////////////////////////////// /** Drawer item name */ private final int m_itemNameId; /** Resource ID of a drawable to be shown as the item's icon */ private final int m_iconResId; /** Item code for feedback to the host activity's implemented callback. */ private final int m_itemCode; } /** * Customized DrawerListAdapter to furnishes the Drawer with DrawerItem * information. */ private static class DrawerListAdapter extends ArrayAdapter<DrawerItem> { public DrawerListAdapter(Context context, ArrayList<DrawerItem> drawerItems) { super(context, 0, drawerItems); m_layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); m_resources = context.getResources(); } @Override public View getView(int position, View convertView, ViewGroup parent) { DrawerItemHolder holder; if (convertView == null) { holder = new DrawerItemHolder(); convertView = m_layoutInflater.inflate(R.layout.list_item_drawer_item, null); convertView.setTag(holder); holder.m_icon = (ImageView) convertView.findViewById(R.id.drawer_item_icon); holder.m_text = (TextView) convertView.findViewById(R.id.drawer_item_text); } else { holder = (DrawerItemHolder)convertView.getTag(); } // Update items in holder DrawerItem item = getItem(position); if (item.getIconResId() != 0) { holder.m_icon.setImageDrawable(m_resources.getDrawable(item.getIconResId())); } holder.m_text.setText(item.getItemName()); return convertView; } private static class DrawerItemHolder { private ImageView m_icon; private TextView m_text; } /** Layout inflater for use */ private final LayoutInflater m_layoutInflater; /** Reference to get context's resources */ private final Resources m_resources; } ////////////////////////////////////////////////////////////////////////////// /** Callback that host activity must implement */ public static interface DrawerCallbacks { /** Callback to host activity when a drawer item is selected */ void onDrawerItemSelected(int itemCode, int itemNameId); } ////////////////////////////////////////////////////////////////////////////// private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } /** * Method that binds the current activity to the UbiCDN Service. */ private void bindService() { if (!m_isServiceConnected) { // Bind to Service getActivity().bindService(new Intent(getActivity(), UmobileService.class), m_ServiceConnection, Context.BIND_AUTO_CREATE); G.Log("ServiceFragment::bindUbiCDNService()"); } } /** * Method that unbinds the current activity from the UbiCDN Service. */ private void unbindService() { if (m_isServiceConnected) { // Unbind from Service getActivity().unbindService(m_ServiceConnection); m_isServiceConnected = false; G.Log("ServiceFragment::unbindUbiCDNService()"); } } /** * Client ServiceConnection to UbiCDN Service. */ public final ServiceConnection m_ServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { // Establish Messenger to the Service m_serviceMessenger = new Messenger(service); m_isServiceConnected = true; // onServiceConnected runs on the main thread // Check if UbiCDN Service is running try { Message msg = Message.obtain(null, UmobileService.CHECK_SERVICE); msg.replyTo = m_clientMessenger; m_serviceMessenger.send(msg); } catch (RemoteException e) { // If Service crashes, nothing to do here G.Log("onServiceConnected(): " + e); } G.Log("m_ServiceConnection::onServiceConnected()"); } @Override public void onServiceDisconnected(ComponentName componentName) { // In event of unexpected disconnection with the Service; Not expecting to get here. G.Log("m_ServiceConnection::onServiceDisconnected()"); m_isServiceConnected = false; // onServiceDisconnected runs on the main thread } }; public void startUbiCDNService() { assert m_isServiceConnected; m_serviceStartStopSwitch.setText(R.string.starting_service); Intent myService = new Intent(getActivity(), UmobileService.class); getActivity().startService(myService); sendServiceMessage(UmobileService.CHECK_SERVICE); } public void stopUbiCDNService() { assert m_isServiceConnected; m_serviceStartStopSwitch.setText(R.string.stopping_service); sendServiceMessage(UmobileService.STOP_UBICDN_SERVICE); } /** * Convenience method to send a message to the UbiCDN Service * through a Messenger. * * @param message Message from a set of predefined UbiCDN Service messages. */ private void sendServiceMessage(int message) { if (m_serviceMessenger == null) { G.Log("UbiCDN Service not yet connected"); return; } try { Message msg = Message.obtain(null, message); msg.replyTo = m_clientMessenger; m_serviceMessenger.send(msg); } catch (RemoteException e) { // If Service crashes, nothing to do here G.Log("UbiCDN service Disconnected: " + e); } } private void setServiceRunning() { m_serviceStartStopSwitch.setEnabled(true); m_serviceStartStopSwitch.setText(R.string.service_started); m_serviceStartStopSwitch.setChecked(true); } private void setServiceStopped() { m_serviceStartStopSwitch.setEnabled(true); m_serviceStartStopSwitch.setText(R.string.service_stopped); m_serviceStartStopSwitch.setChecked(false); } private class ClientHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case UmobileService.UBICDN_SERVICE_RUNNING: setServiceRunning(); G.Log("ClientHandler: UbiCDN is Running."); //m_handler.postDelayed(m_statusUpdateRunnable, 500); break; case UmobileService.UBICDN_SERVICE_STOPPED: setServiceStopped(); Intent myService = new Intent(getActivity(), UmobileService.class); getActivity().stopService(myService); G.Log("ClientHandler: UbiCDN is Stopped."); break; default: super.handleMessage(msg); break; } } } /** Flag that marks that application is connected to the UbiCDN Service */ private boolean m_isServiceConnected = false; /** Client Message Handler */ private final Messenger m_clientMessenger = new Messenger(new ClientHandler()); /** Messenger connection to UbiCDN Service */ private Messenger m_serviceMessenger = null; /** SharedPreference: Display drawer when drawer loads for the very first time */ private static final String PREF_DRAWER_SHOWN_TO_USER_FOR_THE_FIRST_TIME = "DRAWER_PRESENTED_TO_USER_ON_FIRST_LOAD"; /** Bundle key used to (re)store position of selected drawer item */ private static final String DRAWER_SELECTED_POSITION_BUNDLE_KEY = "DRAWER_SELECTED_POSITION"; /** Bundle argument key for bundle parameters */ private static final String BUNDLE_PARAMETERS = "net.named_data.nfd.drawer_fragment_parameters"; /** Callback to parent activity */ private DrawerCallbacks m_callbacks; /** DrawerToggle for interacting with drawer and action bar app icon */ //private ActionBarDrawerToggle m_drawerToggle; /** Reference to DrawerLayout fragment in host activity */ private DrawerLayout m_drawerLayout; /** Reference to drawer's ListView */ private ListView m_drawerListView; /** Drawer's fragment container in the host activity */ private View m_drawerFragmentViewContainer; /** Current position of the Drawer's selection */ private int m_drawerSelectedPosition = 0; /** Flag that denotes if the fragment is restored from an instance state */ private boolean m_restoredFromSavedInstanceState; /** Flag that denotes if the user has seen the Drawer when the app loads for the first time */ private boolean m_hasUserSeenDrawer; /** ArrayList of DrawerItems to be displayed in the Drawer */ private ArrayList<DrawerItem> m_drawerItems; /** Flag that marks if drawer is sliding outwards and being displayed */ private boolean m_shouldHideOptionsMenu = false; private Switch m_serviceStartStopSwitch; }
package sosis.AndroidApps.HoManager; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.OperationApplicationException; import android.graphics.Color; import android.os.Bundle; import android.os.RemoteException; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.RatingBar; import android.widget.Toast; import java.util.ArrayList; import database.HoTable; import sosis.AndroidApps.Provider.HoProvider; public class AddActivity extends AppCompatActivity { private EditText firstNameView; private EditText lastNameView; private EditText phoneNumberView; private RatingBar faceBar; private RatingBar bodyBar; private RatingBar personalityBar; private RatingBar humorBar; private RatingBar intellectBar; public static final String BAR_BUDDIES = "BarBuddies"; public static final String CANCEL = "Cancel"; public static final String SAVE = "Save"; private static final String HO_ADDED_TEXT = "A Buddy has been added!"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_buddy); final Toolbar toolbar = (Toolbar) this.findViewById(R.id.toolbar); toolbar.setTitleTextColor(Color.WHITE); this.setSupportActionBar(toolbar); setMemberViews(); } @Override public void onSaveInstanceState(Bundle out) { super.onSaveInstanceState(out); } private void setMemberViews() { firstNameView = (EditText) findViewById(R.id.firstName); lastNameView = (EditText) findViewById(R.id.lastName); phoneNumberView = (EditText) findViewById(R.id.telephone_number); faceBar = (RatingBar) findViewById(R.id.face_rating_bar); bodyBar = (RatingBar) findViewById(R.id.body_rating_bar); personalityBar = (RatingBar) findViewById(R.id.personality_rating_bar); humorBar = (RatingBar) findViewById(R.id.humor_rating_bar); intellectBar = (RatingBar) findViewById(R.id.bitch_rating_bar); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.edit_ho_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent intent = new Intent(this, MainHoActivity.class); ContentValues contentValues = new ContentValues(); String itemTitle = (String) item.getTitle(); if (itemTitle.equals(CANCEL)) { hideSoftKeyboard(); startActivity(intent); } else if (itemTitle.equals(SAVE)) { if (!areTextFieldsEmpty(firstNameView) && !areTextFieldsEmpty(phoneNumberView)) { String firstName = firstNameView.getText().toString().trim(); if (Character.isLowerCase(firstName.charAt(0))) { firstName = firstName.substring(0, 1).toUpperCase() + firstName.substring(1); } String lastName = lastNameView.getText().toString().trim(); if (!lastName.equals("") && lastName.length() > 2 && Character.isLowerCase(lastName.charAt(0))) { lastName = lastName.substring(0, 1).toUpperCase() + lastName.substring(1); } contentValues.put(HoTable.COLUMN_NAME, firstName + " " + lastName); String phoneNumber = phoneNumberView.getText().toString().trim(); contentValues.put(HoTable.COLUMN_NUMBER, phoneNumber); ContentProviderResult[] res = addToExternalContactList(firstName, lastName, phoneNumber); if (3 == res.length) { String rawContactID = res[0].uri.getLastPathSegment(); contentValues.put(HoTable.COLUMN_CONTACTS_ID, rawContactID); String phoneDataID = res[1].uri.getLastPathSegment(); contentValues.put(HoTable.COLUMN_CONTACTS_NUMBER_ID, phoneDataID); String nameDataID = res[2].uri.getLastPathSegment(); contentValues.put(HoTable.COLUMN_CONTACTS_DISPLAY_ID, nameDataID); } float faceRating = faceBar.getRating(); contentValues.put(HoTable.COLUMN_FACE_RATING, faceRating); float bodyRating = bodyBar.getRating(); contentValues.put(HoTable.COLUMN_BODY_RATING, bodyRating); float personalityRating = personalityBar.getRating(); contentValues.put(HoTable.COLUMN_PERSONALITY_RATING, personalityRating); float humorRating = humorBar.getRating(); contentValues.put(HoTable.COLUMN_HUMOR_RATING, humorRating); float intellectRating = intellectBar.getRating(); contentValues.put(HoTable.COLUMN_INTELLECT_RATING, intellectRating); getContentResolver(). insert(HoProvider.CONTENT_URI, contentValues); clearFields(); hideSoftKeyboard(); startActivity(intent); //getPager().setCurrentItem(2, true); Toast.makeText(this, HO_ADDED_TEXT, Toast.LENGTH_LONG).show(); } return true; } return super.onOptionsItemSelected(item); } private void clearFields () { firstNameView.getText().clear(); lastNameView.getText().clear(); phoneNumberView.getText().clear(); faceBar.setRating(0); bodyBar.setRating(0); personalityBar.setRating(0); humorBar.setRating(0); intellectBar.setRating(0); } // Update the phone's default contact DB private ContentProviderResult[] addToExternalContactList (String firstName, String lastName, String phoneNumber){ ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); int rawContactInsertIndex = ops.size(); ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, BAR_BUDDIES) .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, BAR_BUDDIES) .build()); ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber) .build()); ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex) .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, firstName + " " + lastName) .build()); try { return getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); } catch (OperationApplicationException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } return null; } private void hideEditTextWindow(int editTextID){ EditText editText = (EditText) findViewById(editTextID); if (null != editText) { InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(editText.getWindowToken(), 0); } } private void hideSoftKeyboard() { hideEditTextWindow(R.id.firstNameEdit); hideEditTextWindow(R.id.lastNameEdit); hideEditTextWindow(R.id.telephone_numberEdit); } private boolean areTextFieldsEmpty (EditText mandatoryTextField){ boolean isEmpty = (mandatoryTextField.getText().toString().trim()).equals(""); if (isEmpty) { mandatoryTextField.setError("This field is required!"); } return isEmpty; } }
package com.advancetopics.testcases; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.testng.annotations.Test; import com.opencsv.CSVReader; public class ReadCSVFile { @Test public void readCSVData() throws Exception{ CSVReader reader = new CSVReader(new FileReader("E:\\synerzip_workspace\\synerzip\\jexcel\\csvreader.csv")); List<String[]> li = reader.readAll(); System.out.println("Total rows which we have is "+li.size()); Iterator<String[]>i1= li.iterator(); while(i1.hasNext()){ String[] str=i1.next(); System.out.print(" Values are "); for(int i=0;i<str.length;i++) { System.out.print(" "+str[i]); } System.out.println(" "); } } }
package com.starry.mandarine.biz.domain; import java.io.Serializable; import java.util.List; import lombok.Data; @Data public class FileBrowser implements Serializable { private static final long serialVersionUID = -7973229445635808764L; List<ViewDirectory> viewDirectoryList; List<ViewFile> viewFileList; }
package Lab02.Zad2; public class DolbyProLogic implements Codec{ public void codec(){ System.out.println("DolbyProLogic sound"); } }
package gretig.datastructuur; /** * Created by brent on 10/8/16. */ public class Boog { private int id; private Top t1; private Top t2; public Boog(int id, Top t1){ this.id=id; this.t1 = t1; } /**Notify beide partijen dat ze er een buur bijhebben. * @param t2: buurman */ public void addBoog(Top t2){ this.t2=t2; t1.addBuur(t2); t2.addBuur(t1); } }
package com.kenan; //interface (Product) public interface Logger { public void log( String message ); }
package org.codejudge.sb.enums; public enum Location_type { country,city,zip; }
package com.example.network; import java.util.ArrayList; import com.example.network.adapter.FriendExpandAdapter; import com.example.network.bean.Friend; import com.example.network.bean.FriendGroup; import com.example.network.bean.FriendResp; import com.example.network.task.QueryFriendTask; import com.example.network.task.QueryFriendTask.OnQueryFriendListener; import com.example.network.thread.ClientThread; import com.google.gson.Gson; import android.annotation.SuppressLint; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.ExpandableListView; import android.widget.Toast; /** * Created by ouyangshen on 2017/11/11. */ @SuppressLint("StaticFieldLeak") public class QQContactActivity extends AppCompatActivity implements OnClickListener, OnQueryFriendListener { private final static String TAG = "QQContactActivity"; private static Context mContext; private static ExpandableListView elv_friend; // 声明一个可折叠列表视图对象 private static ArrayList<FriendGroup> mGroupList = new ArrayList<FriendGroup>(); // 好友分组队列 private static FriendGroup mGroupOnline = new FriendGroup(); // 在线好友分组 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qq_contact); // 从布局文件中获取名叫tl_head的工具栏 Toolbar tl_head = findViewById(R.id.tl_head); // 设置工具栏的标题文本 tl_head.setTitle(getResources().getString(R.string.menu_second)); // 使用tl_head替换系统自带的ActionBar setSupportActionBar(tl_head); // 给tl_head设置导航图标的点击监听器 // setNavigationOnClickListener必须放到setSupportActionBar之后,不然不起作用 tl_head.setNavigationOnClickListener(new OnClickListener() { @Override public void onClick(View view) { finish(); } }); mContext = getApplicationContext(); mGroupOnline.title = "在线好友"; // 从布局文件中获取名叫elv_friend的可折叠列表视图 elv_friend = findViewById(R.id.elv_friend); findViewById(R.id.btn_refresh).setOnClickListener(this); // 创建好友查询线程 QueryFriendTask queryTask = new QueryFriendTask(); // 设置好友查询监听器 queryTask.setOnQueryFriendListener(this); // 把好友查询线程加入到处理队列 queryTask.execute(); } // 在好友查询结束时触发 public void onQueryFriend(String resp) { try { // 下面手工解析json串 // JSONObject obj = new JSONObject(resp); // JSONArray groupArray = obj.getJSONArray("group_list"); // for (int i = 0; i < groupArray.length(); i++) { // JSONObject groupObj = groupArray.getJSONObject(i); // FriendGroup group = new FriendGroup(); // group.title = groupObj.getString("title"); // JSONArray friendArray = groupObj.getJSONArray("friend_list"); // for (int j = 0; j < friendArray.length(); j++) { // JSONObject friendObj = friendArray.getJSONObject(j); // Friend friend = new Friend("", friendObj.getString("nick_name"), ""); // group.friend_list.add(friend); // } // mGroupList.add(group); // } // 下面利用gson库自动解析json串 FriendResp packageResp = new Gson().fromJson(resp, FriendResp.class); mGroupList = packageResp.group_list; showAllFriend(); // 显示所有好友分组 } catch (Exception e) { e.printStackTrace(); Toast.makeText(this, "获取全部好友列表出错:" + e.getMessage(), Toast.LENGTH_SHORT).show(); } } @Override protected void onResume() { // 延迟500毫秒后启动分组刷新任务 mHandler.postDelayed(mRefresh, 500); super.onResume(); } @Override protected void onDestroy() { // 向后端服务器发送注销请求 MainApplication.getInstance().sendAction(ClientThread.LOGOUT, "", ""); super.onDestroy(); } private Handler mHandler = new Handler(); // 声明一个处理器对象 // 定义一个分组刷新任务 private Runnable mRefresh = new Runnable() { @Override public void run() { // 向后端服务器发送获取在线好友的请求 MainApplication.getInstance().sendAction(ClientThread.GETLIST, "", ""); } }; @Override public void onClick(View v) { if (v.getId() == R.id.btn_refresh) { mHandler.post(mRefresh); // 立即启动分组刷新任务 } } // 定义一个得到在线好友的广播接收器 public static class GetListReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent != null) { Log.d(TAG, "onReceive"); // 从意图中解包得到在线好友的消息内容 String content = intent.getStringExtra(ClientThread.CONTENT); if (mContext != null && content != null && content.length() > 0) { showFriendOnline(content); // 显示在线好友列表 } } } } // 显示在线好友列表 private static void showFriendOnline(String content) { int pos = content.indexOf(ClientThread.SPLIT_LINE); String head = content.substring(0, pos); // 消息头部 String body = content.substring(pos + 1); // 消息主体 String[] splitArray = head.split(ClientThread.SPLIT_ITEM); if (splitArray[0].equals(ClientThread.GETLIST)) { // 是获取好友列表 String[] bodyArray = body.split("\\|"); // 每条好友记录之间以竖线分隔 ArrayList<Friend> friendList = new ArrayList<Friend>(); for (String oneBody : bodyArray) { String[] itemArray = oneBody.split(ClientThread.SPLIT_ITEM); if (oneBody.length() > 0 && itemArray.length >= 3) { // itemArray数组内容依次为:设备编号、好友昵称、登录时间 friendList.add(new Friend(itemArray[0], itemArray[1], itemArray[2])); } } mGroupOnline.friend_list = friendList; showAllFriend(); // 显示所有好友分组 } else { // 不是获取好友列表 String hint = String.format("%s\n%s", splitArray[0], body); Toast.makeText(mContext, hint, Toast.LENGTH_SHORT).show(); } } // 显示所有好友分组 private static void showAllFriend() { ArrayList<FriendGroup> all_group = new ArrayList<FriendGroup>(); all_group.add(mGroupOnline); // 先往好友队列添加在线好友 all_group.addAll(mGroupList); // 再往好友队列添加各好友分组 // 构建一个好友分组的可折叠列表适配器 FriendExpandAdapter adapter = new FriendExpandAdapter(mContext, all_group); // 给elv_friend设置好友分组可折叠列表适配器 elv_friend.setAdapter(adapter); // 给elv_friend设置孙子项的点击监听器 elv_friend.setOnChildClickListener(adapter); // 给elv_friend设置分组的点击监听器 elv_friend.setOnGroupClickListener(adapter); // 默认展开第一个好友分组,即在线好友分组 elv_friend.expandGroup(0); } // 适配Android9.0开始 @Override public void onStart() { super.onStart(); // 从Android9.0开始,系统不再支持静态广播,应用广播只能通过动态注册 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 创建一个好友列表的广播接收器 listReceiver = new GetListReceiver(); // 注册广播接收器,注册之后才能正常接收广播 registerReceiver(listReceiver, new IntentFilter(ClientThread.ACTION_GET_LIST)); } } @Override public void onStop() { super.onStop(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // 注销广播接收器,注销之后就不再接收广播 unregisterReceiver(listReceiver); } } // 声明一个好友列表的广播接收器 private GetListReceiver listReceiver; // 适配Android9.0结束 }
package LC200_400.LC350_400; import LeetCodeUtils.MyGraph; import org.junit.Test; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; /** * 2020-09-28 10:11 AM at Hangzhou */ public class LC399_Evaluate_Division { public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) { HashMap<String, MyGraph.GNode> allNodeMap = MyGraph.createGraph(equations, values); double[] result = new double[queries.size()]; int i = 0; for (List<String> ls : queries) { double dis = MyGraph.calDistanceOf2Node(ls.get(0), ls.get(1)); result[i++] = dis; } return result; } @Test public void test() { List<List<String>> ls = new ArrayList<>(); List<String> l1 = new ArrayList<>(); l1.add("a"); l1.add("b"); ls.add(l1); List<String> l2 = new ArrayList<>(); l2.add("b"); l2.add("c"); ls.add(l2); List<String> l3 = new ArrayList<>(); l3.add("bc"); l3.add("cd"); ls.add(l3); List<List<String>> query = new ArrayList<>(); List<String> l = new ArrayList<>(); l.add("bc"); l.add("cd"); query.add(l); double[] arr = (calcEquation(ls, new double[]{1.5, 2.5, 5.0}, query)); for (double jj : arr) System.out.println(jj); } /** * You are given equations in the format A / B = k, where A and B are variables represented as strings, * and k is a real number (floating-point number). Given some queries, return the answers. * If the answer does not exist, return -1.0. * * The input is always valid. You may assume that evaluating the queries will result in no division by zero * and there is no contradiction. * * Example 1: * * Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]] * Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000] * Explanation: * Given: a / b = 2.0, b / c = 3.0 * queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? * return: [6.0, 0.5, -1.0, 1.0, -1.0 ] * Example 2: * * Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]] * Output: [3.75000,0.40000,5.00000,0.20000] * * * [["a","e"],["b","e"]] * [4.0,3.0] * [["a","b"],["e","e"],["x","x"]] */ }
package gov.virginia.dmas.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import gov.virginia.dmas.entity.AssignmentEntity; import gov.virginia.dmas.entity.RequestorInternalEntity; public interface AssignmentRepository extends JpaRepository<AssignmentEntity, Long>{ public List<AssignmentEntity> findByEmailAndActive(String email, boolean active); public List<AssignmentEntity> findByEmailAndStatus(String email, String status); public List<AssignmentEntity> findByRequestorInternalEntityAndActive(RequestorInternalEntity requestorInternalEntity, boolean active); List<AssignmentEntity> findByRequestorInternalEntity(RequestorInternalEntity requestorInternalEntity); public List<AssignmentEntity> findByRequestorInternalEntityAndEmailAndActive( RequestorInternalEntity requestorInternalEntity, String email, boolean b); }
package tema13.estrutura; import tema13.estrutura.contatoDependencies.Email; import tema13.estrutura.contatoDependencies.SMS; import tema13.interfaces.IContato; import java.util.Optional; public class Contato implements IContato { private String nome; private Optional<SMS> telefone; private Email email; public Contato(String nome, String email) throws Exception { this.setNome(nome); this.setEmail(email); } public Contato(String nome, String telefone, String email) throws Exception { this.setNome(nome); this.setTelefone(telefone); this.setEmail(email); } public void setNome(String nome) { if (nome.isEmpty()) { throw new NullPointerException("O nome não pode ser nulo."); } this.nome = nome; } public void setTelefone(String telefone) throws Exception { this.telefone = Optional.of(new SMS(telefone)); } public void setEmail(String email) throws Exception { this.email = new Email(email); } @Override public String getEmail() { return this.email.getContato().get(); } @Override public boolean temTelefone() { if (this.telefone != null) { return this.telefone.get().isPresente(); } return false; } @Override public String getNome() { return this.nome; } @Override public Optional<String> getTelefone() { if(this.telefone.isPresent()) { return this.telefone.get().getContato(); } return Optional.empty(); } }
package zystudio.cases.javabase.clsload.case3; import zystudio.mylib.utils.LogUtil; /** * Created by zylab on 2017/12/3. */ public class BaseClass { private int num=1; public BaseClass(){ print(); } public void print(){ //是0额,是0额,父类的构造函数调用时,子类的成员变量还没初始化呢,所以连1都不是,是0 LogUtil.log(this.getClass().toString()+",base's num="+num); } }
package com.rca_gps.app.util; /** * 类名: com.rca_gps.app.util.AppUrl * 作者: yanhao * From: * 功能 : * 创建日期: 2016-10-27 21:14 * 修改日期: 2016-10-27 21:14 */ public class AppUrl { //测试地址 // public static final String BASE_URL = "http://ras-dev.rcaservice.com.cn"; public static final String BASE_URL = "https://ras-pre.rcaservice.com.cn"; //上线地址 // public static final String BASE_URL = "https://ras.rcaservice.com.cn"; //注册地址 public static final String REGISTER_URL ="/api/contractGps/appRegist"; //获取最新模板信息 public static final String GET_TEMPLATE_CHANGE ="/api/contractGps/getTemplateById"; //获取历史按键 public static final String GET_HISTORY_CASE = "/api/contractGps/getAcceptedCases"; }
package com.hp.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.hp.entity.Provider; import com.hp.entity.UserContactus; import com.hp.repository.UserContactusRepository; @Component public class UserContactusService { @Autowired private UserContactusRepository userContactusrepository; public List<UserContactus> getAllDetail() { return (List<UserContactus>) userContactusrepository.findAll(); } public void createDetailOfUserContactus(UserContactus entity) { userContactusrepository.save(entity); } public Optional<UserContactus> getSingleUserDetail(Long id) { return userContactusrepository.findById(id); } public UserContactus getSingleUserContactusDetailById(Long id) { return userContactusrepository.findById(id).orElse(null); } public void deleteUserContactusDetail(Long id) { userContactusrepository.deleteById(id); } public UserContactus findByUsername(String name) { // TODO Auto-generated method stub return userContactusrepository.findByUsername(name); } }
package net.minecraft.advancements; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSyntaxException; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.function.Function; import javax.annotation.Nullable; import net.minecraft.network.PacketBuffer; import net.minecraft.util.JsonUtils; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraft.util.text.event.HoverEvent; import org.apache.commons.lang3.ArrayUtils; public class Advancement { private final Advancement field_192076_a; private final DisplayInfo field_192077_b; private final AdvancementRewards field_192078_c; private final ResourceLocation field_192079_d; private final Map<String, Criterion> field_192080_e; private final String[][] field_192081_f; private final Set<Advancement> field_192082_g = Sets.newLinkedHashSet(); private final ITextComponent field_193125_h; public Advancement(ResourceLocation p_i47472_1_, @Nullable Advancement p_i47472_2_, @Nullable DisplayInfo p_i47472_3_, AdvancementRewards p_i47472_4_, Map<String, Criterion> p_i47472_5_, String[][] p_i47472_6_) { this.field_192079_d = p_i47472_1_; this.field_192077_b = p_i47472_3_; this.field_192080_e = (Map<String, Criterion>)ImmutableMap.copyOf(p_i47472_5_); this.field_192076_a = p_i47472_2_; this.field_192078_c = p_i47472_4_; this.field_192081_f = p_i47472_6_; if (p_i47472_2_ != null) p_i47472_2_.func_192071_a(this); if (p_i47472_3_ == null) { this.field_193125_h = (ITextComponent)new TextComponentString(p_i47472_1_.toString()); } else { this.field_193125_h = (ITextComponent)new TextComponentString("["); this.field_193125_h.getStyle().setColor(p_i47472_3_.func_192291_d().func_193229_c()); ITextComponent itextcomponent = p_i47472_3_.func_192297_a().createCopy(); TextComponentString textComponentString = new TextComponentString(""); ITextComponent itextcomponent2 = itextcomponent.createCopy(); itextcomponent2.getStyle().setColor(p_i47472_3_.func_192291_d().func_193229_c()); textComponentString.appendSibling(itextcomponent2); textComponentString.appendText("\n"); textComponentString.appendSibling(p_i47472_3_.func_193222_b()); itextcomponent.getStyle().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, (ITextComponent)textComponentString)); this.field_193125_h.appendSibling(itextcomponent); this.field_193125_h.appendText("]"); } } public Builder func_192075_a() { return new Builder((this.field_192076_a == null) ? null : this.field_192076_a.func_192067_g(), this.field_192077_b, this.field_192078_c, this.field_192080_e, this.field_192081_f); } @Nullable public Advancement func_192070_b() { return this.field_192076_a; } @Nullable public DisplayInfo func_192068_c() { return this.field_192077_b; } public AdvancementRewards func_192072_d() { return this.field_192078_c; } public String toString() { return "SimpleAdvancement{id=" + func_192067_g() + ", parent=" + ((this.field_192076_a == null) ? "null" : (String)this.field_192076_a.func_192067_g()) + ", display=" + this.field_192077_b + ", rewards=" + this.field_192078_c + ", criteria=" + this.field_192080_e + ", requirements=" + Arrays.deepToString((Object[])this.field_192081_f) + '}'; } public Iterable<Advancement> func_192069_e() { return this.field_192082_g; } public Map<String, Criterion> func_192073_f() { return this.field_192080_e; } public int func_193124_g() { return this.field_192081_f.length; } public void func_192071_a(Advancement p_192071_1_) { this.field_192082_g.add(p_192071_1_); } public ResourceLocation func_192067_g() { return this.field_192079_d; } public boolean equals(Object p_equals_1_) { if (this == p_equals_1_) return true; if (!(p_equals_1_ instanceof Advancement)) return false; Advancement advancement = (Advancement)p_equals_1_; return this.field_192079_d.equals(advancement.field_192079_d); } public int hashCode() { return this.field_192079_d.hashCode(); } public String[][] func_192074_h() { return this.field_192081_f; } public ITextComponent func_193123_j() { return this.field_193125_h; } public static class Builder { private final ResourceLocation field_192061_a; private Advancement field_192062_b; private final DisplayInfo field_192063_c; private final AdvancementRewards field_192064_d; private final Map<String, Criterion> field_192065_e; private final String[][] field_192066_f; Builder(@Nullable ResourceLocation p_i47414_1_, @Nullable DisplayInfo p_i47414_2_, AdvancementRewards p_i47414_3_, Map<String, Criterion> p_i47414_4_, String[][] p_i47414_5_) { this.field_192061_a = p_i47414_1_; this.field_192063_c = p_i47414_2_; this.field_192064_d = p_i47414_3_; this.field_192065_e = p_i47414_4_; this.field_192066_f = p_i47414_5_; } public boolean func_192058_a(Function<ResourceLocation, Advancement> p_192058_1_) { if (this.field_192061_a == null) return true; this.field_192062_b = p_192058_1_.apply(this.field_192061_a); return (this.field_192062_b != null); } public Advancement func_192056_a(ResourceLocation p_192056_1_) { return new Advancement(p_192056_1_, this.field_192062_b, this.field_192063_c, this.field_192064_d, this.field_192065_e, this.field_192066_f); } public void func_192057_a(PacketBuffer p_192057_1_) { if (this.field_192061_a == null) { p_192057_1_.writeBoolean(false); } else { p_192057_1_.writeBoolean(true); p_192057_1_.func_192572_a(this.field_192061_a); } if (this.field_192063_c == null) { p_192057_1_.writeBoolean(false); } else { p_192057_1_.writeBoolean(true); this.field_192063_c.func_192290_a(p_192057_1_); } Criterion.func_192141_a(this.field_192065_e, p_192057_1_); p_192057_1_.writeVarIntToBuffer(this.field_192066_f.length); byte b; int i; String[][] arrayOfString; for (i = (arrayOfString = this.field_192066_f).length, b = 0; b < i; ) { String[] astring = arrayOfString[b]; p_192057_1_.writeVarIntToBuffer(astring.length); byte b1; int j; String[] arrayOfString1; for (j = (arrayOfString1 = astring).length, b1 = 0; b1 < j; ) { String s = arrayOfString1[b1]; p_192057_1_.writeString(s); b1++; } b++; } } public String toString() { return "Task Advancement{parentId=" + this.field_192061_a + ", display=" + this.field_192063_c + ", rewards=" + this.field_192064_d + ", criteria=" + this.field_192065_e + ", requirements=" + Arrays.deepToString((Object[])this.field_192066_f) + '}'; } public static Builder func_192059_a(JsonObject p_192059_0_, JsonDeserializationContext p_192059_1_) { ResourceLocation resourcelocation = p_192059_0_.has("parent") ? new ResourceLocation(JsonUtils.getString(p_192059_0_, "parent")) : null; DisplayInfo displayinfo = p_192059_0_.has("display") ? DisplayInfo.func_192294_a(JsonUtils.getJsonObject(p_192059_0_, "display"), p_192059_1_) : null; AdvancementRewards advancementrewards = (AdvancementRewards)JsonUtils.deserializeClass(p_192059_0_, "rewards", AdvancementRewards.field_192114_a, p_192059_1_, AdvancementRewards.class); Map<String, Criterion> map = Criterion.func_192144_b(JsonUtils.getJsonObject(p_192059_0_, "criteria"), p_192059_1_); if (map.isEmpty()) throw new JsonSyntaxException("Advancement criteria cannot be empty"); JsonArray jsonarray = JsonUtils.getJsonArray(p_192059_0_, "requirements", new JsonArray()); String[][] astring = new String[jsonarray.size()][]; for (int i = 0; i < jsonarray.size(); i++) { JsonArray jsonarray1 = JsonUtils.getJsonArray(jsonarray.get(i), "requirements[" + i + "]"); astring[i] = new String[jsonarray1.size()]; for (int k = 0; k < jsonarray1.size(); k++) astring[i][k] = JsonUtils.getString(jsonarray1.get(k), "requirements[" + i + "][" + k + "]"); } if (astring.length == 0) { astring = new String[map.size()][]; int k = 0; for (String s2 : map.keySet()) { (new String[1])[0] = s2; astring[k++] = new String[1]; } } byte b; int j; String[][] arrayOfString1; for (j = (arrayOfString1 = astring).length, b = 0; b < j; ) { String[] astring1 = arrayOfString1[b]; if (astring1.length == 0 && map.isEmpty()) throw new JsonSyntaxException("Requirement entry cannot be empty"); byte b1; int k; String[] arrayOfString2; for (k = (arrayOfString2 = astring1).length, b1 = 0; b1 < k; ) { String s = arrayOfString2[b1]; if (!map.containsKey(s)) throw new JsonSyntaxException("Unknown required criterion '" + s + "'"); b1++; } b++; } for (String s1 : map.keySet()) { boolean flag = false; byte b1; int k; String[][] arrayOfString; for (k = (arrayOfString = astring).length, b1 = 0; b1 < k; ) { String[] astring2 = arrayOfString[b1]; if (ArrayUtils.contains((Object[])astring2, s1)) { flag = true; break; } b1++; } if (!flag) throw new JsonSyntaxException("Criterion '" + s1 + "' isn't a requirement for completion. This isn't supported behaviour, all criteria must be required."); } return new Builder(resourcelocation, displayinfo, advancementrewards, map, astring); } public static Builder func_192060_b(PacketBuffer p_192060_0_) throws IOException { ResourceLocation resourcelocation = p_192060_0_.readBoolean() ? p_192060_0_.func_192575_l() : null; DisplayInfo displayinfo = p_192060_0_.readBoolean() ? DisplayInfo.func_192295_b(p_192060_0_) : null; Map<String, Criterion> map = Criterion.func_192142_c(p_192060_0_); String[][] astring = new String[p_192060_0_.readVarIntFromBuffer()][]; for (int i = 0; i < astring.length; i++) { astring[i] = new String[p_192060_0_.readVarIntFromBuffer()]; for (int j = 0; j < (astring[i]).length; j++) astring[i][j] = p_192060_0_.readStringFromBuffer(32767); } return new Builder(resourcelocation, displayinfo, AdvancementRewards.field_192114_a, map, astring); } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\advancements\Advancement.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.acme.storeserver.model; import lombok.*; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.io.Serializable; @Data @Builder @NoArgsConstructor @AllArgsConstructor @Entity @Table(name = "store") public class Store implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Size(min = 2, max = 200) private String name; @NotNull @Size(min = 2, max = 255) private String address; }
package ciclo3.retos.backend.repositorios; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import ciclo3.retos.backend.crudrepositorio.ClientCrudRepository; import ciclo3.retos.backend.entidades.Client; @Repository public class ClientRepository { @Autowired private ClientCrudRepository clientCrudRepository; public List<Client> getAll(){return(List<Client>) clientCrudRepository.findAll();} public Optional<Client> getClient(int id){ return clientCrudRepository.findById(id); } public Client save(Client client){ return clientCrudRepository.save(client); } public void delete (Client client){ clientCrudRepository.delete(client);} }
import java.util.HashMap; import java.util.Map; public class Tap_Code { public static Map<String, Character> DECODE = new HashMap<>(); static { //ENCODE HashMap DECODE.put(". .", 'a'); DECODE.put(". ..", 'b'); DECODE.put(". ...", 'c'); DECODE.put(". ....", 'd'); DECODE.put(". .....", 'e'); DECODE.put(".. .", 'f'); DECODE.put(".. ..", 'g'); DECODE.put(".. ...", 'h'); DECODE.put(".. ....", 'i'); DECODE.put(".. .....", 'j'); DECODE.put("... .", 'l'); DECODE.put("... ..", 'm'); DECODE.put("... ...", 'n'); DECODE.put("... ....", 'o'); DECODE.put("... .....", 'p'); DECODE.put(".... .", 'q'); DECODE.put(".... ..", 'r'); DECODE.put(".... ...", 's'); DECODE.put(".... ....", 't'); DECODE.put(".... .....", 'u'); DECODE.put("..... .", 'v'); DECODE.put("..... ..", 'w'); DECODE.put("..... ...", 'x'); DECODE.put("..... ....", 'y'); DECODE.put("..... .....", 'z'); DECODE.put(" ", ' '); } public static String TapCodeEncode(char x) { switch (x) { case 'a': return ". . "; case 'b': return ". .. "; case 'c': return ". ... "; case 'd': return ". .... "; case 'e': return ". ..... "; case 'f': return ".. . "; case 'g': return ".. .. "; case 'h': return ".. ... "; case 'i': return ".. .... "; case 'j': return ".. ..... "; case 'l': return "... . "; case 'm': return "... .. "; case 'n': return "... ... "; case 'o': return "... .... "; case 'p': return "... ..... "; case 'q': return ".... . "; case 'r': return ".... .. "; case 's': return ".... ... "; case 't': return ".... .... "; case 'u': return ".... ..... "; case 'v': return "..... . "; case 'w': return "..... .. "; case 'x': return "..... ... "; case 'y': return "..... .... "; // for space case 'z': return "..... ..... "; } return ""; } public static void encode(String e) { for (int i = 0;i<e.length(); i++) System.out.print(TapCodeEncode(e.charAt(i))); System.out.println(); } public static String decode(String tap) { StringBuilder decoded = new StringBuilder(); String[] words = tap.trim().split(" ",1); for (String word : words) { String[] letters = word.split(" "); for (String letter : letters) { decoded.append(DECODE.get(letter)); } } System.out.println(decoded); return decoded.toString().toUpperCase(); } }
package cn.bs.zjzc.div; import android.content.Context; import android.support.v4.app.Fragment; import android.util.AttributeSet; import android.view.View; /** * Created by Ming on 2016/5/30. */ public class DashLine extends View { public DashLine(Context context) { this(context, null); } public DashLine(Context context, AttributeSet attrs) { super(context, attrs); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { this.setLayerType(View.LAYER_TYPE_SOFTWARE, null); } } }
package com.av.payment.repository.persistor; import com.av.payment.model.SubscriptionRequest; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Created by Aman Verma on 18/03/2018. * * Persister class can be switched based on <link>@Profile</link> Annotation in future */ @Component public class InternalStorageSubscriptionPersister implements SubscriptionPersister { private Map<String, SubscriptionRequest> subscriptionRequests = Collections.synchronizedMap(new HashMap<>()); /** * Persists request object in local datastructure * * @param subReq */ @Override public void saveSubscriptionRequest(SubscriptionRequest subReq) { // Can check for already existing recode and throw exception subscriptionRequests.put(subReq.getId(), subReq); } @Override public SubscriptionRequest getSubscriptionRequest(String id) { return null; } @Override public Map<String, SubscriptionRequest> getAllSubscriptionRequests() { return subscriptionRequests; } @Override public void deleteSubscriptionRequest(String id) { } }
package com.google.android.gms.common.api; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.signin.internal.AuthAccountResult; import com.google.android.gms.signin.internal.b; import java.lang.ref.WeakReference; class m$a extends b { private final WeakReference<m> aLb; m$a(m mVar) { this.aLb = new WeakReference(mVar); } public final void a(ConnectionResult connectionResult, AuthAccountResult authAccountResult) { m mVar = (m) this.aLb.get(); if (mVar != null) { mVar.aKG.a(new 1(this, mVar, mVar, connectionResult)); } } }
package gui; import control.WireSensorTFake; import control.WirelessSensorT; import control.WirelessSensorTFake; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class RoomMonitorPage extends Thread implements ActionListener { private CWFrame roomMonitorFrame; private CWBorderPanel wiredNodePanel, wirelessNodePanel;//整个界面分为左右两部分,来自有线传感器的数据和来自无线传感器的数据 private CWButton backBtn;//返回上个界面(选择) private CWLabel wiredTempLabel, wiredHumLabel, wirelessTempLabel, wirelessHumLabel, wiredWarningLabel, wirelessWarningLabel;//有线/无线的温湿度的标签/警报标签 private CWLabel wiredTempValueLabel, wiredHumValueLabel, wirelessTempValueLabel, wirelessHumValueLabel;//有线/无线的温湿度的数字显示 public static final ImageIcon background = new ImageIcon(new ImageIcon("src/img/OtherPage.jpg").getImage().getScaledInstance(Layout.getFrameWidth(), Layout.getFrameHeight(), Image.SCALE_DEFAULT)); private WireSensorTFake wireSensorTFake;//该线程每固定时间读取有线温湿度信息通过DHT11,这个是个接口,用的时候替换掉 private WirelessSensorTFake wirelessSensorTFake;//该线程使用无线节点,每隔固定时间读取温湿度信息 private WirelessSensorT wirelessSensorT;//该线程每固定时间读取有线温湿度信息通过DHT11 public RoomMonitorPage() { //Set Values roomMonitorFrame = new CWFrame("Intelligent Operating Room System"); //左半部分,显示DHT11的数据 wiredNodePanel = new CWBorderPanel(36, 7, 5, 40, 70, "Wired", new Color(144, 12, 62), new Color(144, 12, 62)); roomMonitorFrame.add(wiredNodePanel); //右半部分,显示无线传感器的数据 wirelessNodePanel = new CWBorderPanel(36, 53, 5, 40, 70, "Wireless", new Color(144, 12, 62), new Color(144, 12, 62)); roomMonitorFrame.add(wirelessNodePanel); //左边2个标签与2个值,有线传感器数据与警报 wiredTempLabel = new CWLabel("Temp:", 36, new Color(175, 117, 117), 15, 20, 10, 5, SwingConstants.LEFT); roomMonitorFrame.add(wiredTempLabel); wiredTempValueLabel = new CWLabel("66 C", 36, new Color(175, 117, 117), 25, 20, 15, 5, SwingConstants.LEFT); roomMonitorFrame.add(wiredTempValueLabel); wiredHumLabel = new CWLabel("Hum:", 36, new Color(175, 117, 117), 15, 30, 10, 5, SwingConstants.LEFT); roomMonitorFrame.add(wiredHumLabel); wiredHumValueLabel = new CWLabel("88 %", 36, new Color(175, 117, 117), 25, 30, 15, 5, SwingConstants.LEFT); roomMonitorFrame.add(wiredHumValueLabel); wiredWarningLabel = new CWLabel("NORMAL", 36, new Color(175, 117, 117), 19, 50, 16, 5, SwingConstants.CENTER); roomMonitorFrame.add(wiredWarningLabel); //右边2个标签与2个值,有线传感器数据与警报 wirelessTempLabel = new CWLabel("Temp:", 36, new Color(175, 117, 117), 61, 20, 10, 5, SwingConstants.LEFT); roomMonitorFrame.add(wirelessTempLabel); wirelessTempValueLabel = new CWLabel("66 C", 36, new Color(175, 117, 117), 71, 20, 15, 5, SwingConstants.LEFT); roomMonitorFrame.add(wirelessTempValueLabel); wirelessHumLabel = new CWLabel("Hum:", 36, new Color(175, 117, 117), 61, 30, 10, 5, SwingConstants.LEFT); roomMonitorFrame.add(wirelessHumLabel); wirelessHumValueLabel = new CWLabel("88 %", 36, new Color(175, 117, 117), 71, 30, 15, 5, SwingConstants.LEFT); roomMonitorFrame.add(wirelessHumValueLabel); wirelessWarningLabel = new CWLabel("NORMAL", 36, new Color(175, 117, 117), 65, 50, 16, 5, SwingConstants.CENTER); roomMonitorFrame.add(wirelessWarningLabel); backBtn = new CWButton("BACK", "Microsoft YaHei", 50, new Color(53, 48, 126), 85, 80, 10, 5); roomMonitorFrame.add(backBtn); backBtn.addActionListener(this); JLabel label = new JLabel(background); label.setBounds(0, 0, Layout.getFrameWidth(), Layout.getFrameHeight()); JPanel imagePanel = (JPanel) roomMonitorFrame.getContentPane(); imagePanel.setOpaque(false); roomMonitorFrame.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE)); //TODO:初始化两个传感器 //创建线程,启动两个传感器的读取,实时读取传感器状态并返回 TODO:换上正确的thread wireSensorTFake = new WireSensorTFake(); wirelessSensorT = new WirelessSensorT(); // wirelessSensorTFake = new WirelessSensorTFake(); wireSensorTFake.start(); wirelessSensorT.start(); // wirelessSensorTFake.start(); this.start(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource().equals(backBtn)) { roomMonitorFrame.dispose(); new ChooseFunctionPage(); this.stop(); } } @Override public void run() { //随时根据传感器获取的温湿度信息更改数据,并进行预警 while (true) { //以下是有线部分 this.wiredTempValueLabel.setText("" + wireSensorTFake.getTemp()+" C"); this.wiredHumValueLabel.setText("" + wireSensorTFake.getHum()+" %"); if (wireSensorTFake.isWarning()) { this.wiredWarningLabel.setText("WARNING"); this.wiredWarningLabel.setForeground(new Color(144, 12, 62)); } else { this.wiredWarningLabel.setText("Normal"); this.wiredWarningLabel.setForeground(new Color(175, 117, 117)); //TODO:亮灯 } //以下是无线部分 this.wirelessTempValueLabel.setText("" + wirelessSensorT.getTemp()); this.wirelessHumValueLabel.setText("" + wirelessSensorT.getHum()); if (wirelessSensorT.isWarning()) { this.wirelessWarningLabel.setText("WARNING"); this.wirelessWarningLabel.setForeground(new Color(144, 12, 62)); } else { this.wirelessWarningLabel.setText("Normal"); this.wirelessWarningLabel.setForeground(new Color(175, 117, 117)); //TODO:亮灯 } } } }
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.devtools_bridge.gcd; import android.util.JsonReader; import android.util.Log; import org.chromium.components.devtools_bridge.commands.Command; import org.chromium.components.devtools_bridge.commands.CommandFormatException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Reader for additional messages (used only in the testing app). */ public final class TestMessageReader { private static final String TAG = "TestMessageReader"; private final JsonReader mReader; public TestMessageReader(JsonReader reader) { mReader = reader; } public List<RemoteInstance> readRemoteInstances() throws IOException { final List<RemoteInstance> result = new ArrayList<RemoteInstance>(); mReader.beginObject(); while (mReader.hasNext()) { String name = mReader.nextName(); if (name.equals("devices")) { mReader.beginArray(); while (mReader.hasNext()) { result.add(readInstance()); } mReader.endArray(); } else { mReader.skipValue(); } } mReader.endObject(); return result; } private RemoteInstance readInstance() throws IOException { String id = null; String displayName = null; mReader.beginObject(); while (mReader.hasNext()) { String name = mReader.nextName(); if (name.equals("id")) { id = mReader.nextString(); } else if (name.equals("displayName")) { displayName = mReader.nextString(); } else { mReader.skipValue(); } } mReader.endObject(); if (id == null) { throw new IllegalArgumentException("Missing remote instance id"); } if (displayName == null) { throw new IllegalArgumentException("Missing remote instance display name"); } return new RemoteInstance(id, displayName); } public void readCommandResult(Command command) throws IOException { String state = null; Map<String, String> outParams = null; String errorMessage = null; mReader.beginObject(); while (mReader.hasNext()) { String name = mReader.nextName(); if (name.equals("state")) { state = mReader.nextString(); } else if (name.equals("results")) { outParams = MessageReader.readStringMap(mReader); } else if (name.equals("error")) { errorMessage = readErrorMessage(); } else { mReader.skipValue(); } } mReader.endObject(); if ("done".equals(state) && outParams != null) { try { command.setSuccess(outParams); } catch (CommandFormatException e) { Log.e(TAG, "Invalid command format", e); command.setFailure("Invalid format: " + e.getMessage()); } } else if ("error".equals(state) && errorMessage != null) { Log.w(TAG, "Command error: " + errorMessage); command.setFailure(errorMessage); } else { Log.w(TAG, "Invalid command state: " + state); command.setFailure("Invalid state: " + state); } } private String readErrorMessage() throws IOException { String result = null; mReader.beginObject(); while (mReader.hasNext()) { if (mReader.nextName().equals("message")) { result = mReader.nextString(); } else { mReader.skipValue(); } } mReader.endObject(); return result; } }
/* * datosreg_qualitas.java * * Created on 10 de enero de 2008, 17:24 * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package herramientas; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; /** * * @author Administrador */ public class datosreg_qualitas { private String sRutaPropiedades = "/data/informes/datosreg_qualitas/datosregqualitas.properties"; private String sRutaLog; private Utilidades.Propiedades propiedades = null; private Connection conexion = null; private Connection conexion2 = null; private String sConsulta = ""; //LOG public static Logger logger = Logger.getLogger(datosreg_qualitas.class); public static void main (String [] args ) { datosreg_qualitas datregq = new datosreg_qualitas(); }//main /** Creates a new instance of datosreg_qualitas */ public datosreg_qualitas() { try { cargaPropiedades(); cruza_datosreg_e4xtt(); } catch (FileNotFoundException fnfe) { logger.info("ERROR 1: "+fnfe.toString()); //Utilidades.Log.addText(sRutaLog,"ERROR 1: "+fnfe.toString()); System.out.println("ERROR 1"); } catch (IOException ioe) { logger.info("ERROR 2: "+ioe.toString()); //Utilidades.Log.addText(sRutaLog,"ERROR 2: "+ioe.toString()); System.out.println("ERROR 2"); } } private void cruza_datosreg_e4xtt() { String numexp = ""; String libro = ""; String tomo = ""; String registro = ""; int total = 0; int buenos = 0; int malos = 0; int noEncontrados = 0; int numero; try { conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion.setAutoCommit(false); conexion2 = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion2.setAutoCommit(false); ResultSet rsTotal = null; //ResultSet rsE4xtt = null; sConsulta = "SELECT datosreg.*,e4xtt.* FROM datosreg,e4xtt WHERE numexp = e4xha and numero = e4xya and tomo = 'A' AND libro = '16685'"; rsTotal = Utilidades.Conexion.select(sConsulta,conexion); while (rsTotal.next()) { libro = ""; tomo = ""; registro = ""; total ++; System.out.println("Subtotal: "+Integer.toString(total)); numexp = rsTotal.getString("numexp"); numero = rsTotal.getInt("numero"); System.out.println("Expediente: "+numexp); //sConsulta = "SELECT * FROM e4xtt WHERE e4xha = '"+numexp+"' and e4xya =" + Integer.toString(numero); //rsE4xtt = Utilidades.Conexion.select(sConsulta,conexion); //if (rsE4xtt.next()) //{ //System.out.println("ENCONTRADO"); tomo = rsTotal.getString("e4y0a"); libro = rsTotal.getString("e4y1a"); registro = rsTotal.getString("e4xza"); sConsulta = "UPDATE datosreg SET tomo ='"+tomo+"', libro ='"+libro+"', registro = '"+registro+"' where numexp = '"+numexp+"' and numero ="+Integer.toString(numero); if (Utilidades.Conexion.update(sConsulta,conexion2) > 0) { conexion2.commit(); buenos ++; logger.info("Actualizado expediente: "+numexp+ " Tomo: "+tomo+" Libro: "+libro+" Registro: "+registro); //Utilidades.Log.addText(sRutaLog,"Actualizado expediente: "+numexp+ " Tomo: "+tomo+" Libro: "+libro+" Registro: "+registro); } else { conexion2.rollback(); malos ++; logger.info("ERROR 5: Imposible acutalizar datos registrales para el expediente: "+numexp); //Utilidades.Log.addText(sRutaLog,"ERROR 5: Imposible acutalizar datos registrales para el expediente: "+numexp); System.out.println("ERROR 3"); } System.out.println("Buenos: "+Integer.toString(buenos)); System.out.println("Malos: "+Integer.toString(malos)); //} /* else { noEncontrados ++; Utilidades.Log.addText(sRutaLog,"Expediente no localizado en E4XTT: "+numexp); System.out.println("NO ENCONTRADO"); } rsE4xtt.close(); */ } System.out.println("Total: "+Integer.toString(total)); logger.info("TOTAL procesados: "+Integer.toString(total)); //Utilidades.Log.addText(sRutaLog,"TOTAL procesados: "+Integer.toString(total)); logger.info("BUENOS: "+Integer.toString(buenos)); //Utilidades.Log.addText(sRutaLog,"BUENOS: "+Integer.toString(buenos)); logger.info("MALOS: "+Integer.toString(malos)); //Utilidades.Log.addText(sRutaLog,"MALOS: "+Integer.toString(malos)); logger.info("NO ENCONTRADOS: "+Integer.toString(noEncontrados)); //Utilidades.Log.addText(sRutaLog,"NO ENCONTRADOS: "+Integer.toString(noEncontrados)); rsTotal.close(); conexion.close(); conexion2.close(); System.gc(); } catch (ClassNotFoundException cnfe) { logger.info("ERROR 3: "+cnfe.toString()); //Utilidades.Log.addText(sRutaLog,"ERROR 3: "+cnfe.toString()); System.out.println("ERROR 3"); } catch (SQLException sqle) { logger.info("ERROR 4: "+sqle.toString()); //Utilidades.Log.addText(sRutaLog,"ERROR 4: "+sqle.toString()); System.out.println("ERROR 4"); } finally { try { if (conexion != null && !conexion.isClosed()) conexion.close(); if (conexion2 != null && !conexion2.isClosed()) conexion2.close(); } catch (SQLException e) { logger.info("Imposible cerrar conexión: "+e.toString().trim()); //Utilidades.Log.addText(sRutaLog,"Imposible cerrar conexión: "+e.toString().trim()); } conexion = null; conexion2 = null; System.gc(); } }//cruza_datosreg_e4xtt private void cargaPropiedades() throws FileNotFoundException, IOException { File fPropiedades = new File(sRutaPropiedades); if (fPropiedades.exists()) { propiedades = new Utilidades.Propiedades(fPropiedades.getAbsolutePath()); sRutaLog = propiedades.getValueProperty("RutaLog"); PropertyConfigurator.configure(sRutaLog + "Log4j.properties"); } else { throw new FileNotFoundException ("Imposible localizar fichero de propiedades en la ruta: " + sRutaPropiedades.trim()); } }//cargaPropiedades }
package com.tencent.mm.plugin.sns.ui; import android.view.View; class bh$a { View nid = null; String ntR; final /* synthetic */ bh ohO; public bh$a(bh bhVar, String str, View view) { this.ohO = bhVar; this.ntR = str; this.nid = view; } }
package net.suntrans.haipopeiwang.bean; import java.util.ArrayList; import java.util.List; /** * Created by Looney on 2018/3/5. * Des: */ public class TenDevice { public List<TenSwitchItem> datas = new ArrayList<>(); TenDevice() { for (int i=0;i<=10;i++){ TenSwitchItem item = new TenSwitchItem(); } } }
package com.b12.inventory.inventoryService.service; import java.util.List; import com.b12.inventory.inventoryService.model.Inventory; public interface InventoryService { public List<Inventory> getAllProducts(); public Inventory getProductByName(String name); public List<Inventory> getProductByGroup(String group); public List<Inventory> getProductByType(String type); public Inventory createProduct(Inventory inventory); public Inventory updateProduct(Inventory inventory); public void deleteProduct(Inventory inventory); public Inventory checkProductAvailability(String name); public Inventory productAvailabilityNotification(String name); }
package com.example.v2.socket; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; /** * InetAddress IP地址 * * InetSocketAddress IP套字节地址(IP地址 + 端口) */ public class InetAddressTest { public static void main(String[] args) throws IOException { InetAddress localHostAddress = InetAddress.getLocalHost(); System.out.println(localHostAddress); InetSocketAddress inetSocketAddress = new InetSocketAddress(localHostAddress, 8000); System.out.println(inetSocketAddress.getHostName()); System.out.println(inetSocketAddress.getHostString()); System.out.println(inetSocketAddress.getPort()); } }
package com.tencent.mm.plugin.sport.c; import android.os.Looper; import com.tencent.mm.g.a.fh; import com.tencent.mm.g.a.qt; import com.tencent.mm.kernel.g; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bn; import java.util.Calendar; import org.json.JSONObject; public final class b { public c<qt> ooJ = new c<qt>() { { this.sFo = qt.class.getName().hashCode(); } public final /* synthetic */ boolean a(com.tencent.mm.sdk.b.b bVar) { qt qtVar = (qt) bVar; switch (qtVar.cbp.action) { case 1: case 2: case 3: if (n.bFQ()) { boolean ft; long ciZ = bi.ciZ() / 10000; long L = i.L(513, 0); long L2 = i.L(512, 0); Calendar instance = Calendar.getInstance(); instance.setTimeInMillis(L); instance.set(11, 0); instance.set(12, 0); instance.set(13, 0); if (ciZ != instance.getTimeInMillis() / 10000) { L2 = 0; } if (qtVar.cbp.action == 1) { ft = b.this.ft(L2); fh fhVar = new fh(); fhVar.bNx.action = 1; a.sFg.a(fhVar, Looper.getMainLooper()); } else { ft = n.F(b.this.bFG(), L2) ? b.this.ft(L2) : false; } x.i("MicroMsg.Sport.ExtApiStepManager", "upload step %d %d %b", new Object[]{Integer.valueOf(qtVar.cbp.action), Long.valueOf(L2), Boolean.valueOf(ft)}); break; } break; } return false; } }; public f ooK; public c ooQ = new 1(this); private long ooR; private long ooS; public b() { this.ooQ.cht(); this.ooJ.cht(); } final boolean i(com.tencent.mm.sdk.b.b bVar) { fh fhVar = (fh) bVar; switch (fhVar.bNx.action) { case 2: int i; long j = fhVar.bNx.bNA; long currentTimeMillis = System.currentTimeMillis(); long j2 = fhVar.bNx.bNB; com.tencent.mm.g.a.fh.b bVar2 = fhVar.bNy; if (!n.bFv()) { i = 3906; } else if (n.bFQ()) { long L = i.L(513, 0); long L2 = i.L(512, 0); x.v("MicroMsg.Sport.ExtApiStepManager", "lastUpdateTime:%d lastUpdateStep:%d newUpdateTime:%d newUpdateStep:%d", new Object[]{Long.valueOf(L), Long.valueOf(L2), Long.valueOf(currentTimeMillis), Long.valueOf(j)}); if (currentTimeMillis - L < 300000) { x.w("MicroMsg.Sport.ExtApiStepManager", "update interval must larger than 5 minute"); i = 3903; } else { JSONObject bFJ = g.bFJ(); if (!bi.u(currentTimeMillis, L)) { L = bi.ciZ(); L2 = 0; } long j3 = currentTimeMillis - L; x.v("MicroMsg.Sport.ExtApiStepManager", "interval5m %d intervalTime %d newUpdateTime:%d compareUpdateTime:%d maxIncreaseStep:%d", new Object[]{Long.valueOf((j3 / 300000) + ((long) (j3 % 300000 > 0 ? 1 : 0))), Long.valueOf(j3), Long.valueOf(currentTimeMillis), Long.valueOf(L), Long.valueOf(((long) bFJ.optInt("stepCounterMaxStep5m")) * ((j3 / 300000) + ((long) (j3 % 300000 > 0 ? 1 : 0))))}); L2 = j - L2; if (L2 < 0 || L2 > r14) { x.w("MicroMsg.Sport.ExtApiStepManager", "invalid step in 5 minute actual: %d max: %d", new Object[]{Long.valueOf(L2), Long.valueOf(r14)}); i = 3904; } else { x.i("MicroMsg.Sport.ExtApiStepManager", "can update time: %s, step: %d", new Object[]{n.bx(currentTimeMillis), Long.valueOf(j)}); i.M(513, currentTimeMillis); i.M(512, j); i.M(514, j2); i = 1; } } } else { i = 3902; } bVar2.bNE = i; if (fhVar.bNy.bNE == 1) { if (this.ooR == 0) { this.ooR = i.L(515, 0); } boolean E = n.E(this.ooR, System.currentTimeMillis()); boolean F = n.F(bFG(), j); if (E && F) { ft(j); } } fhVar.bNy.bND = true; break; case 3: try { JSONObject optJSONObject = g.bFJ().optJSONObject("extStepApiConfig"); if (optJSONObject != null) { fhVar.bNy.bNC = optJSONObject.toString(); } if (bi.oW(fhVar.bNy.bNC)) { fhVar.bNy.bNE = 3905; } else { fhVar.bNy.bNE = 1; } } catch (Exception e) { fhVar.bNy.bNE = 3905; } fhVar.bNy.bND = true; break; } return true; } final boolean ft(long j) { if (this.ooK != null) { g.DF().c(this.ooK); } long currentTimeMillis = System.currentTimeMillis(); Calendar instance = Calendar.getInstance(); instance.set(11, 0); instance.set(12, 0); instance.set(13, 0); x.i("MicroMsg.Sport.ExtApiStepManager", "update Api Step time: %s stepCount: %s", new Object[]{n.bx(currentTimeMillis), Long.valueOf(j)}); this.ooK = new f("", "gh_43f2581f6fd6", (int) (instance.getTimeInMillis() / 1000), (int) (currentTimeMillis / 1000), (int) j, bn.cmZ(), 2); g.DF().a(this.ooK, 0); this.ooR = currentTimeMillis; i.M(515, currentTimeMillis); this.ooS = j; i.L(516, this.ooS); return true; } public final long bFG() { if (this.ooS == 0) { this.ooS = i.L(516, 0); } return this.ooS; } }
package com.example.renzo.alarmagarage; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by Renzo on 23/10/2016. */ public class UsuariosSQLiteHelper extends SQLiteOpenHelper { String sqlCreateUsuario = "CREATE TABLE Usuarios (codigo TEXT, nombre TEXT, clave TEXT, email TEXT, emailReferido TEXT)"; public UsuariosSQLiteHelper(Context context, String nombre, SQLiteDatabase.CursorFactory factory, int version) { super(context, nombre, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(sqlCreateUsuario); } @Override public void onUpgrade(SQLiteDatabase db, int versionAnterior, int versionNueva) { db.execSQL("DROP TABLE IF EXISTS Usuarios"); db.execSQL(sqlCreateUsuario); } }
package com.kunsoftware.controller.front; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.kunsoftware.bean.BuyBean; import com.kunsoftware.bean.CommentsRequestBean; import com.kunsoftware.bean.JsonBean; import com.kunsoftware.controller.BaseController; import com.kunsoftware.entity.Comments; import com.kunsoftware.entity.FlightChedule; import com.kunsoftware.entity.FlightChedulePlan; import com.kunsoftware.entity.FlightChedulePrice; import com.kunsoftware.entity.Orders; import com.kunsoftware.entity.OrdersDetail; import com.kunsoftware.entity.ProductResource; import com.kunsoftware.exception.KunSoftwareException; import com.kunsoftware.service.FlightChedulePlanService; import com.kunsoftware.service.FlightChedulePriceService; import com.kunsoftware.service.FlightCheduleService; import com.kunsoftware.service.OrdersService; import com.kunsoftware.service.ProductResourceService; import com.kunsoftware.service.ValueSetService; import com.kunsoftware.util.WebUtil; @Controller @RequestMapping("/product") public class FrontBuyController extends BaseController { private static Logger logger = LoggerFactory.getLogger(FrontBuyController.class); @Autowired private OrdersService service; @Autowired private ProductResourceService productResourceService; @Autowired private FlightCheduleService flightCheduleService; @Autowired private FlightChedulePriceService flightChedulePriceService; @Autowired private FlightChedulePlanService flightChedulePlanService; @Autowired private ValueSetService valueSetService; @RequestMapping("/buy") public String buy(ModelMap model,BuyBean buyBean) throws KunSoftwareException { logger.info("购买"); ProductResource productResource = productResourceService.selectByPrimaryKey(buyBean.getId()); Date date = new Date(); date = DateUtils.setMonths(date, new Integer(buyBean.getCheduleMonth()) - 1); date = DateUtils.setDays(date, new Integer(buyBean.getCheduleDay())); FlightChedule flightChedule = flightCheduleService.selectByResource(buyBean.getId(), DateFormatUtils.format(date, "yyyy-MM-dd")); List retList = new ArrayList(); OrdersDetail ordersDetail = null; double allTotal = 0; if("1".equals(productResource.getCombo())) { FlightChedulePlan flightChedulePlan = flightChedulePlanService.selectByFlightCheduleId(flightChedule.getId(), new Integer(buyBean.getTplId())); model.addAttribute("name", flightChedulePlan.getName()); model.addAttribute("decribe", flightChedulePlan.getPlanDescribe()); if(buyBean.getNum1() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("1"); ordersDetail.setUnitPrice(flightChedulePlan.getAdultPrice()); ordersDetail.setQuantity(buyBean.getNum1()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getAdultPrice().doubleValue() * buyBean.getNum1(); } if(buyBean.getNum2() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("2"); ordersDetail.setUnitPrice(flightChedulePlan.getChildBedPrice()); ordersDetail.setQuantity(buyBean.getNum2()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getChildBedPrice().doubleValue() * buyBean.getNum2(); } if(buyBean.getNum3() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("3"); ordersDetail.setUnitPrice(flightChedulePlan.getAdultExtraBedPrice()); ordersDetail.setQuantity(buyBean.getNum3()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getAdultExtraBedPrice().doubleValue() * buyBean.getNum3(); } if(buyBean.getNum4() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("4"); ordersDetail.setUnitPrice(flightChedulePlan.getChildNoBedPrice()); ordersDetail.setQuantity(buyBean.getNum4()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getChildNoBedPrice().doubleValue() * buyBean.getNum4(); } int allNum = buyBean.getNum1() + buyBean.getNum2() + buyBean.getNum3() + buyBean.getNum4(); if(allNum > 1 && allNum %2 != 0) { ordersDetail = new OrdersDetail(); ordersDetail.setName(flightChedulePlan.getName()); ordersDetail.setType("5"); ordersDetail.setUnitPrice(flightChedulePlan.getSingleRoom()); ordersDetail.setQuantity(1); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getSingleRoom().doubleValue() * 1; } } else { FlightChedulePrice flightChedulePrice = flightChedulePriceService.selectByFlightCheduleId(flightChedule.getId(), new Integer(buyBean.getTplId())); model.addAttribute("name", flightChedulePrice.getName()); model.addAttribute("decribe", flightChedulePrice.getPriceDescribe()); if(buyBean.getNum6() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("6"); ordersDetail.setUnitPrice(flightChedulePrice.getPrice()); ordersDetail.setQuantity(buyBean.getNum6()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePrice.getPrice().doubleValue() * buyBean.getNum6(); } } buyBean.setAllTotal(allTotal); model.addAttribute("productResource", productResource); model.addAttribute("flightChedule", flightChedule); model.addAttribute("retList", retList); model.addAttribute("buyBean", buyBean); model.addAttribute("destinationList", valueSetService.selectValueSetDestinationList()); return "front/product-buy"; } @RequestMapping("/buy2") public String buy2(ModelMap model,BuyBean buyBean) throws KunSoftwareException { logger.info("购买2"); Integer num1 = buyBean.getNum1() + buyBean.getNum3(); Integer num2 = buyBean.getNum2() + buyBean.getNum4(); model.addAttribute("num1", num1); model.addAttribute("num2", num2); model.addAttribute("buyBean", buyBean); model.addAttribute("destinationList", valueSetService.selectValueSetDestinationList()); return "front/product-buy2"; } @RequestMapping("/buy3") public String buy3(ModelMap model,BuyBean buyBean) throws KunSoftwareException { logger.info("购买3"); ProductResource productResource = productResourceService.selectByPrimaryKey(buyBean.getId()); Date date = new Date(); date = DateUtils.setMonths(date, new Integer(buyBean.getCheduleMonth()) - 1); date = DateUtils.setDays(date, new Integer(buyBean.getCheduleDay())); FlightChedule flightChedule = flightCheduleService.selectByResource(buyBean.getId(), DateFormatUtils.format(date, "yyyy-MM-dd")); List retList = new ArrayList(); OrdersDetail ordersDetail = null; double allTotal = 0; Integer flightChedulePlanPriceId = null; if("1".equals(productResource.getCombo())) { FlightChedulePlan flightChedulePlan = flightChedulePlanService.selectByFlightCheduleId(flightChedule.getId(), new Integer(buyBean.getTplId())); model.addAttribute("name", flightChedulePlan.getName()); model.addAttribute("decribe", flightChedulePlan.getPlanDescribe()); flightChedulePlanPriceId = flightChedulePlan.getId(); if(buyBean.getNum1() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("1"); ordersDetail.setUnitPrice(flightChedulePlan.getAdultPrice()); ordersDetail.setQuantity(buyBean.getNum1()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getAdultPrice().doubleValue() * buyBean.getNum1(); } if(buyBean.getNum2() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("2"); ordersDetail.setUnitPrice(flightChedulePlan.getChildBedPrice()); ordersDetail.setQuantity(buyBean.getNum2()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getChildBedPrice().doubleValue() * buyBean.getNum2(); } if(buyBean.getNum3() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("3"); ordersDetail.setUnitPrice(flightChedulePlan.getAdultExtraBedPrice()); ordersDetail.setQuantity(buyBean.getNum3()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getAdultExtraBedPrice().doubleValue() * buyBean.getNum3(); } if(buyBean.getNum4() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setType("4"); ordersDetail.setUnitPrice(flightChedulePlan.getChildNoBedPrice()); ordersDetail.setQuantity(buyBean.getNum4()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getChildNoBedPrice().doubleValue() * buyBean.getNum4(); } int allNum = buyBean.getNum1() + buyBean.getNum2() + buyBean.getNum3() + buyBean.getNum4(); if(allNum > 1 && allNum %2 != 0) { ordersDetail = new OrdersDetail(); ordersDetail.setName(flightChedulePlan.getName()); ordersDetail.setType("5"); ordersDetail.setUnitPrice(flightChedulePlan.getSingleRoom()); ordersDetail.setQuantity(1); retList.add(ordersDetail); allTotal = allTotal + flightChedulePlan.getSingleRoom().doubleValue() * 1; } } else { FlightChedulePrice flightChedulePrice = flightChedulePriceService.selectByFlightCheduleId(flightChedule.getId(), new Integer(buyBean.getTplId())); flightChedulePlanPriceId = flightChedulePrice.getId(); model.addAttribute("name", flightChedulePrice.getName()); model.addAttribute("decribe", flightChedulePrice.getPriceDescribe()); if(buyBean.getNum6() > 0) { ordersDetail = new OrdersDetail(); ordersDetail.setName(flightChedulePrice.getName()); ordersDetail.setType("6"); ordersDetail.setUnitPrice(flightChedulePrice.getPrice()); ordersDetail.setQuantity(buyBean.getNum6()); retList.add(ordersDetail); allTotal = allTotal + flightChedulePrice.getPrice().doubleValue() * buyBean.getNum5(); } } buyBean.setFlightChedulePlanPriceId(flightChedulePlanPriceId); Orders orders = service.insertMemberOrder(buyBean, productResource, flightChedule, retList); model.addAttribute("orders",orders); model.addAttribute("destinationList", valueSetService.selectValueSetDestinationList()); return "front/product-buy3"; } }
package com.mx.profuturo.bolsa.service.desk; import com.mx.profuturo.bolsa.model.desk.dto.DeskDTO; import com.mx.profuturo.bolsa.model.desk.vo.EscritorioVO; import com.mx.profuturo.bolsa.model.restclient.RequestBean; import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException; import com.mx.profuturo.bolsa.service.desk.*; import com.mx.profuturo.bolsa.util.exception.custom.GenericStatusException; public interface DeskService { public EscritorioVO getDeskData(DeskDTO dto) throws GenericStatusException; RecruiterCorpDeskResponse __getRecruiterCorpData(RequestBean<String> request) throws GenericStatusException; AdministratorCorpDeskResponse __getAdministratorCorpData(RequestBean<String> request) throws GenericStatusException; AdministratorCommDeskResponse __getAdministratorCommData(RequestBean<String> request) throws GenericStatusException; ConsultorCommDeskResponse __getCommConsultorData(RequestBean<String> request) throws GenericStatusException; AnalystCommDeskResponse __getCommAnalystData(RequestBean<String> request)throws GenericStatusException; ObserverCommDeskResponse __getCommObserver(RequestBean<String> request)throws GenericStatusException; ObserverCorpDeskResponse __getObserverCorpData(RequestBean<String> request)throws GenericStatusException; CustomerRecruiterCorpDeskResponse __getCustomerRecruiterCorpData(RequestBean<String> request) throws GenericStatusException; }
/* * 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 subclases; /** * * @author ESTUDIANTE */ public class Gato implements Animal{ @Override public void rugir() { System.out.println("miauuu"); } @Override public void saltar() { System.out.println("El gato está saltando."); } }
package com.meroapp.meroblog.service; import org.springframework.web.multipart.MultipartFile; public interface UploadService { public boolean uploadImage(MultipartFile image); }
package com.retail.discounts.controller; /* * Author : Abdul Haq Shaik * */ import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.retail.discounts.model.Bill; import com.retail.discounts.model.Transaction; import com.retail.discounts.service.NetAmountServiceImpl; @RestController @RequestMapping(value="/amount") public class RetailDiscountsController { private static final Logger logger = LogManager.getLogger(RetailDiscountsController.class); @Autowired NetAmountServiceImpl netAmountService; @RequestMapping(value="/net", method=RequestMethod.POST, consumes="application/json", produces="application/json") @ResponseBody public ResponseEntity<Bill> getNetAmount(@RequestBody Transaction txn) { logger.debug("Sending the transation from the POS Machine to the Discount Calculator"); Bill bill = netAmountService.getBill(txn); logger.debug("Getting the transation from the Discount Calculator and sending to POS Machine"); return new ResponseEntity<Bill>(bill,HttpStatus.OK); } }
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder; import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.RechteckType; import java.io.StringWriter; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; public class RechteckTypeBuilder { public static String marshal(RechteckType rechteckType) throws JAXBException { JAXBElement<RechteckType> jaxbElement = new JAXBElement<>(new QName("TESTING"), RechteckType.class , rechteckType); StringWriter stringWriter = new StringWriter(); return stringWriter.toString(); } private Double startLaenge; private Double startBreite; private Double breite; private Double laenge; public RechteckTypeBuilder setStartLaenge(Double value) { this.startLaenge = value; return this; } public RechteckTypeBuilder setStartBreite(Double value) { this.startBreite = value; return this; } public RechteckTypeBuilder setBreite(Double value) { this.breite = value; return this; } public RechteckTypeBuilder setLaenge(Double value) { this.laenge = value; return this; } public RechteckType build() { RechteckType result = new RechteckType(); result.setStartLaenge(startLaenge); result.setStartBreite(startBreite); result.setBreite(breite); result.setLaenge(laenge); return result; } }
public class Pair<T, S>{ private final T first; private final S second; public Pair(T first, S second){ this.first = first; this.second = second; } public T getFirst(){ return first; } public S getSecond(){ return second; } @Override public int hashCode() { int hash = 7; hash = 37 * hash + this.first.hashCode(); return hash; } @Override public boolean equals(Object obj) { if(this == obj) return true; if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Pair other = (Pair) obj; if (!this.first.equals(other.first)) { return false; } return true; } }
package com.example.android.customerapp.models; import java.io.Serializable; public class RecipeImage implements Serializable { private int id; private String s3Url; public RecipeImage(int id, String s3Url) { this.id = id; this.s3Url = s3Url; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getS3Url() { return s3Url; } public void setS3Url(String s3Url) { this.s3Url = s3Url; } }
package com.zest.web.client.dao.category; import java.util.List; import com.zest.web.client.model.CategoryPageVO; import com.zest.web.client.model.CategoryVO; public interface CategoryDAO { //카테고리 리스트를 불러오는 DAO List<CategoryVO> getCategoryList(); // 카테고리(대분류) 페이지 리스트를 불러오는 메서드 List<CategoryPageVO> getCategoryPageList(Object obj); // 카테고리(소분류) 페이지 리스트를 불러오는 메서드 List<CategoryPageVO> getLecturePageList(Object obj); //가져올 글개수 카운트 Integer getCategoryPageListCount(Object obj); }
package com.tencent.mm.protocal.c; import com.tencent.mm.bk.a; public final class amn extends a { public String bWP; public int huV; public String hwg; public String rIw; public int rPk; public long rPl; public long rPm; public String rrW; public long ruW; protected final int a(int i, Object... objArr) { int h; if (i == 0) { f.a.a.c.a aVar = (f.a.a.c.a) objArr[0]; if (this.rrW != null) { aVar.g(1, this.rrW); } aVar.T(2, this.ruW); aVar.fT(3, this.rPk); aVar.T(4, this.rPl); aVar.T(5, this.rPm); if (this.rIw != null) { aVar.g(6, this.rIw); } if (this.hwg != null) { aVar.g(7, this.hwg); } aVar.fT(8, this.huV); if (this.bWP == null) { return 0; } aVar.g(9, this.bWP); return 0; } else if (i == 1) { if (this.rrW != null) { h = f.a.a.b.b.a.h(1, this.rrW) + 0; } else { h = 0; } h = (((h + f.a.a.a.S(2, this.ruW)) + f.a.a.a.fQ(3, this.rPk)) + f.a.a.a.S(4, this.rPl)) + f.a.a.a.S(5, this.rPm); if (this.rIw != null) { h += f.a.a.b.b.a.h(6, this.rIw); } if (this.hwg != null) { h += f.a.a.b.b.a.h(7, this.hwg); } h += f.a.a.a.fQ(8, this.huV); if (this.bWP != null) { h += f.a.a.b.b.a.h(9, this.bWP); } return h; } else if (i == 2) { f.a.a.a.a aVar2 = new f.a.a.a.a((byte[]) objArr[0], unknownTagHandler); for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) { if (!super.a(aVar2, this, h)) { aVar2.cJS(); } } return 0; } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; amn amn = (amn) objArr[1]; switch (((Integer) objArr[2]).intValue()) { case 1: amn.rrW = aVar3.vHC.readString(); return 0; case 2: amn.ruW = aVar3.vHC.rZ(); return 0; case 3: amn.rPk = aVar3.vHC.rY(); return 0; case 4: amn.rPl = aVar3.vHC.rZ(); return 0; case 5: amn.rPm = aVar3.vHC.rZ(); return 0; case 6: amn.rIw = aVar3.vHC.readString(); return 0; case 7: amn.hwg = aVar3.vHC.readString(); return 0; case 8: amn.huV = aVar3.vHC.rY(); return 0; case 9: amn.bWP = aVar3.vHC.readString(); return 0; default: return -1; } } } }
package com.sky.contract.service; import com.sky.contract.mapper.PermissionMapper; import com.sky.contract.model.Permission; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; /** * Created by shiqm on 2018/9/25. */ @Service public class PermissionService { @Autowired private PermissionMapper permissionMapper; public List<Permission> getAllPermissionForTree() { List<Permission> list = permissionMapper.selectAll(); List<Permission> result = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { Permission permission = list.get(i); if (permission.getParentId() == 0) { result.add(permission); } installTree(permission, list, i); } return result; } private void installTree(Permission target, List<Permission> list, int i) { for (int m = i; m < list.size(); m++) { Permission permission = list.get(m); if (target.getPermissionId().compareTo(permission.getParentId()) == 0) { target.getList().add(permission); } } } public List<Permission> getPermissionsByRoleId(Long roleId){ return permissionMapper.getPermissionsByRoleId(roleId); } }
/** * ファイル名 : MVsmUserMapper.java * 作成者 : nv-manh * 作成日時 : 2018/05/31 * Copyright © 2017-2018 TAU Corporation. All Rights Reserved. */ package jp.co.tau.web7.admin.supplier.mappers; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import jp.co.tau.web7.admin.supplier.dto.LoginDTO; import jp.co.tau.web7.admin.supplier.dto.UserInfoDTO; import jp.co.tau.web7.admin.supplier.dto.VSM15010XDTO; import jp.co.tau.web7.admin.supplier.dto.VSM15010XSearchDTO; import jp.co.tau.web7.admin.supplier.entity.MVsmUserEntity; import jp.co.tau.web7.admin.supplier.mappers.common.BaseMapper; /** * <p> クラス名 : MVsmUserMapper </p> * <p> 説明 : VSM_ユーザマッパー </p> * * @author tt-anh * @since 2018/05/31 */ @Mapper public interface MVsmUserMapper extends BaseMapper<MVsmUserEntity> { /** * <p>説明 : VSM_ユーザー情報取得</p> * @author tt-anh * @since 2018/5/31 * @param loginInfor User login * @return UserInfoDTO List */ public List<UserInfoDTO> findVsmUserInfo(LoginDTO loginInfor); /** * <p>説明 : ユーザーロール取得</p> * @author pg-huu * @since 2018/5/31 * @param userInfoDTO User login * @return userRole */ public String findUserRole(UserInfoDTO userInfoDTO); /** * <p>説明 : VSM_ユーザーの最終ログイン日時の更新</p> * @author tt-anh * @since 2018/5/31 * @param userInfoDTO User login * @return Number of updated record */ int updateLastLoginTime(UserInfoDTO userInfoDTO); /** * <p>説明 : VSM_ユーザーの最終ログイン日時の更新</p> * @author pg-huu * @since 2018/5/31 * @param userInfoDTO User login * @return Number of updated record */ int updateVsmUser(UserInfoDTO userInfoDTO); /** * <p>説明 : VSM_ユーザーの最終ログイン日時の更新</p> * @author luantx * @since 2018/5/31 * @param userInfoDTO User login * @return Number of updated record */ int updateUser(MVsmUserEntity mVsmUserEntity); /** * <p>説明 : Update count login failure</p> * @author hung.pd * @param userInfoDTO User login failure * @return Number record updated */ int updateVsmUserLoginFailure(UserInfoDTO userInfoDTO); /** * * <p>説明 : Get user by userid and aution type code</p> * @author hung.pd * @param userId User id login * @param aucTypeCd Aution type code * @return Number of record */ int getUserID(@Param("userId") String userId, @Param("aucTypeCd") String aucTypeCd); /** * <p>説明 : Insert user</p> * @author hung.pd * @param item user * @return Number of record inserted */ int insertUser(UserInfoDTO item); /** * <p>説明 : Finding user infomation</p> * @author hung.pd * @param userId User id login * @param aucTypeCd Aution type code * @return Number of record */ public UserInfoDTO findUserInfo(@Param("userId") String userId, @Param("aucTypeCd") String aucTypeCd); /** * <p>説明 : Finding user infomation 2</p> * @author hung.pd * @param item user * @return Number of record */ public UserInfoDTO findUserInfo2(UserInfoDTO item); /** * <p>説明 : Find user by name</p> * @author Luantx * @param username, deleteFlg , aucTypeCd * @return MVsmUserEntity */ public List<MVsmUserEntity> findVsmUserByName(@Param("userNm") String userNm, @Param("deleteFlg") String deleteFlg, @Param("aucTypeCd") String aucTypeCd); /** * <p>説明 : get list User</p> * @author Luantx * @param VSM15010XSearchDTO vsm15010XSearchDTO * @return List<VSM15010XDTO> */ public List<VSM15010XDTO> getUserList(VSM15010XSearchDTO vsm15010XSearchDTO); /** * <p>説明 : get list User</p> * @author Luantx * @param VSM15010XSearchDTO vsm15010XSearchDTO * @return List<String> */ public List<String> getUserListCd(VSM15010XSearchDTO vsm15010XSearchDTO); /** * <p>説明 : get total number user</p> * @author Luantx * @param VSM15010XSearchDTO vsm15010XSearchDTO * @return int total record */ public int getTotalUser(VSM15010XSearchDTO vsm15010XSearchDTO); /** * <p>説明 : Update user password</p> * @param userInfoDTO * @return */ public int updateUserPassword(UserInfoDTO userInfoDTO); /** * <p>説明 : Find user info for update password</p> * @param loginInfor * @return */ public List<UserInfoDTO> findUserForUpdatePass(LoginDTO loginInfor); }
package com.tencent.mm.protocal.c; import f.a.a.b; import f.a.a.c.a; import java.util.LinkedList; public final class azu extends bhp { public int iwS; public String iwT; public azv scs; public azj sct; public LinkedList<azi> scu = new LinkedList(); public int scv; protected final int a(int i, Object... objArr) { int fS; byte[] bArr; if (i == 0) { a aVar = (a) objArr[0]; if (this.six == null) { throw new b("Not all required fields were included: BaseResponse"); } if (this.six != null) { aVar.fV(1, this.six.boi()); this.six.a(aVar); } aVar.fT(2, this.iwS); if (this.iwT != null) { aVar.g(3, this.iwT); } if (this.scs != null) { aVar.fV(4, this.scs.boi()); this.scs.a(aVar); } if (this.sct != null) { aVar.fV(5, this.sct.boi()); this.sct.a(aVar); } aVar.d(6, 8, this.scu); aVar.fT(7, this.scv); return 0; } else if (i == 1) { if (this.six != null) { fS = f.a.a.a.fS(1, this.six.boi()) + 0; } else { fS = 0; } fS += f.a.a.a.fQ(2, this.iwS); if (this.iwT != null) { fS += f.a.a.b.b.a.h(3, this.iwT); } if (this.scs != null) { fS += f.a.a.a.fS(4, this.scs.boi()); } if (this.sct != null) { fS += f.a.a.a.fS(5, this.sct.boi()); } return (fS + f.a.a.a.c(6, 8, this.scu)) + f.a.a.a.fQ(7, this.scv); } else if (i == 2) { bArr = (byte[]) objArr[0]; this.scu.clear(); f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler); for (fS = bhp.a(aVar2); fS > 0; fS = bhp.a(aVar2)) { if (!super.a(aVar2, this, fS)) { aVar2.cJS(); } } if (this.six != null) { return 0; } throw new b("Not all required fields were included: BaseResponse"); } else if (i != 3) { return -1; } else { f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0]; azu azu = (azu) objArr[1]; int intValue = ((Integer) objArr[2]).intValue(); LinkedList IC; int size; f.a.a.a.a aVar4; boolean z; switch (intValue) { case 1: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); fl flVar = new fl(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = flVar.a(aVar4, flVar, bhp.a(aVar4))) { } azu.six = flVar; } return 0; case 2: azu.iwS = aVar3.vHC.rY(); return 0; case 3: azu.iwT = aVar3.vHC.readString(); return 0; case 4: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); azv azv = new azv(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = azv.a(aVar4, azv, bhp.a(aVar4))) { } azu.scs = azv; } return 0; case 5: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); azj azj = new azj(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = azj.a(aVar4, azj, bhp.a(aVar4))) { } azu.sct = azj; } return 0; case 6: IC = aVar3.IC(intValue); size = IC.size(); for (intValue = 0; intValue < size; intValue++) { bArr = (byte[]) IC.get(intValue); azi azi = new azi(); aVar4 = new f.a.a.a.a(bArr, unknownTagHandler); for (z = true; z; z = azi.a(aVar4, azi, bhp.a(aVar4))) { } azu.scu.add(azi); } return 0; case 7: azu.scv = aVar3.vHC.rY(); return 0; default: return -1; } } } }
package com.tencent.mm.ac; import com.tencent.mm.ac.e.a; import com.tencent.mm.ac.e.a.b; import com.tencent.mm.g.c.ai; import com.tencent.mm.g.c.am; import com.tencent.mm.kernel.g; import com.tencent.mm.model.s; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.bd; class z$2 implements a { final /* synthetic */ z dMY; z$2(z zVar) { this.dMY = zVar; } public final void a(b bVar) { if ((bVar.dMb == a.a.dLX || bVar.dMb == a.a.dLZ) && bVar.dMc != null) { ai Yg = ((i) g.l(i.class)).FR().Yg(bVar.dKF); if (Yg == null) { return; } if (!Yg.ckW()) { z.h(bVar.dMc); } else if (!s.hr(Yg.field_username)) { com.tencent.mm.storage.ai Yq = ((i) g.l(i.class)).FW().Yq(bVar.dKF); x.v("MicroMsg.SubCoreBiz", "hakon onEvent bizName = %s", bVar.dKF); if (!(!bVar.dMc.LZ() || bVar.dMc.bG(false) == null || bVar.dMc.bG(false).MB() == null || bi.oW(bVar.dMc.Mg()) || !bi.oW(bVar.dMc.field_enterpriseFather))) { bVar.dMc.field_enterpriseFather = bVar.dMc.Mg(); z.MY().e(bVar.dMc); x.i("MicroMsg.SubCoreBiz", "hakon bizStgExt, %s set enterpriseFather %s", bVar.dKF, bVar.dMc.field_enterpriseFather); } if (Yq != null) { int i; boolean i2; if (bVar.dMc.LZ()) { if (bVar.dMc.bG(false) == null) { x.e("MicroMsg.SubCoreBiz", "getExtInfo() == null"); return; } else if (bVar.dMc.bG(false).MB() == null) { x.e("MicroMsg.SubCoreBiz", "enterpriseBizInfo == null"); return; } else { String str = Yq.field_parentRef; if (bVar.dMc.Ma()) { Yq.ef(null); } else { x.i("MicroMsg.SubCoreBiz", "Enterprise belong %s, userName: %s", bVar.dMc.Mg(), bVar.dKF); Yq.ef(bi.oV(bVar.dMc.Mg())); } if (str != null && Yq.field_parentRef != null && !str.equals(Yq.field_parentRef)) { i2 = 1; } else if (str == null && Yq.field_parentRef != null) { i2 = 1; } else if (str == null || Yq.field_parentRef != null) { i2 = false; } else { i2 = 1; } x.v("MicroMsg.SubCoreBiz", "hakon isEnterpriseChildType, %s, %s", bVar.dKF, Yq.field_parentRef); } } else if (bVar.dMc.LY()) { x.v("MicroMsg.SubCoreBiz", "hakon isEnterpriseFatherType, %s", bVar.dKF); i2 = 1; } else if (!bVar.dMc.LV() && !s.hM(Yg.field_username) && !"officialaccounts".equals(Yq.field_parentRef)) { Yq.ef("officialaccounts"); i2 = 1; } else if (!bVar.dMc.LV() || Yq.field_parentRef == null) { i2 = false; } else { Yq.ef(null); i2 = 1; } if (i2 != 0) { ((i) g.l(i.class)).FW().a(Yq, Yq.field_username); if (!bi.oW(Yq.field_parentRef)) { am Yq2; String clI; bd GE; if ("officialaccounts".equals(Yq.field_parentRef)) { Yq2 = ((i) g.l(i.class)).FW().Yq("officialaccounts"); if (Yq2 == null) { am aiVar = new com.tencent.mm.storage.ai("officialaccounts"); aiVar.clx(); ((i) g.l(i.class)).FW().d(aiVar); Yq2 = aiVar; } if (bi.oW(Yq2.field_content)) { x.i("MicroMsg.SubCoreBiz", "conv content is null"); clI = ((i) g.l(i.class)).FW().clI(); if (bi.oW(clI)) { x.w("MicroMsg.SubCoreBiz", "last convBiz is null"); return; } GE = ((i) g.l(i.class)).bcY().GE(clI); if (GE == null || GE.field_msgId == 0) { x.w("MicroMsg.SubCoreBiz", "last biz msg is error"); return; } else { ((i) g.l(i.class)).bcY().a(GE.field_msgId, GE); return; } } return; } x.i("MicroMsg.SubCoreBiz", "hakon username = %s, parentRef = %s", bVar.dKF, Yq.field_parentRef); Yq2 = ((i) g.l(i.class)).FW().Yq(Yq.field_parentRef); if (Yq2 != null && bi.oW(Yq2.field_content)) { x.i("MicroMsg.SubCoreBiz", "conv content is null"); clI = ((i) g.l(i.class)).FW().YD(Yq.field_parentRef); if (bi.oW(clI)) { x.w("MicroMsg.SubCoreBiz", "last enterprise convBiz is null"); return; } GE = ((i) g.l(i.class)).bcY().GE(clI); if (GE == null || GE.field_msgId == 0) { x.w("MicroMsg.SubCoreBiz", "last enterprise biz msg is error"); } else { ((i) g.l(i.class)).bcY().a(GE.field_msgId, GE); } } } } } } } } }
package controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.ListIterator; public class Renner { private Date geboorteDatum; private char geslacht; private String naam, voorNaam; private List<Date> trainingenAanwezig; Renner(Date bd, char gender, String name, String firstName) { this.geboorteDatum = bd; this.geslacht = gender; this.naam = name; this.voorNaam = firstName; this.trainingenAanwezig = new ArrayList<Date>(); } private void addTraining(Date trainingDatum){ this.trainingenAanwezig.add(trainingDatum); } private void removeTraining(Date trainingDatum) { boolean found = false; ListIterator<Date> li = this.trainingenAanwezig.listIterator(); while (li.hasNext() && !found) { if (li.next() == trainingDatum) { li.remove(); found = true; } } if(found) System.out.println("Training met specifieke datum niet teruggevonden: "+trainingDatum.toString()); } }
package org.sodeja.stm; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.sodeja.collections.PersistentSet; import org.sodeja.lang.IDGenerator; public class Tx { private final AtomicReference<Version> versionRef; private final ThreadLocal<TransactionInfo> state = new ThreadLocal<TransactionInfo>(); private final IDGenerator idGen = new IDGenerator(); private final ConcurrentLinkedQueue<TransactionInfo> order = new ConcurrentLinkedQueue<TransactionInfo>(); private PersistentSet<TxListener> listners = new PersistentSet<TxListener>(); public Tx() { this.versionRef = new AtomicReference<Version>(new Version(idGen.next(), new HashMap<TxVar<?>, Object>(), null)); } public void addListner(TxListener l) { listners = listners.addValue(l); } public void begin(boolean readonly) { TransactionInfo newInfo = null; while(true) { Version version = versionRef.get(); newInfo = new TransactionInfo(version, readonly); version.transactionInfoCount.incrementAndGet(); if(versionRef.compareAndSet(version, version)) { break; } version.transactionInfoCount.decrementAndGet(); } state.set(newInfo); order.offer(newInfo); return; } public void commit() { TransactionInfo info = state.get(); if(info == null) { throw new RuntimeException("No transaction"); } if(info.rolledback) { throw new RuntimeException("Already rolledback"); } if(info.readonly) { clearInfo(info); return; } waitOtherTransactions(info); try { commitTransaction(info); } finally { clearInfo(info); } } private void waitOtherTransactions(TransactionInfo info) { while(order.peek() != info) { // if we are not the head, wait for it synchronized(info) { try { info.wait(100); } catch (InterruptedException e) { e.printStackTrace(); // Hmmm ? rollback? } } } } private void commitTransaction(TransactionInfo info) { // Cheks? long verId = idGen.next(); boolean result = versionRef.compareAndSet(info.version, new Version(verId, info.data, info.version)); if(result) { notifyOnCommit(); return; } Version ver = versionRef.get(); if(hasConflictingChanges(ver, info)) { rollback(); throw new RuntimeException("Rolled back due conflicts"); } Map<TxVar<?>, Object> relationInfo = merge(ver, info); //Checks again? state.set(info); Version newVersion = new Version(verId, relationInfo, ver); result = versionRef.compareAndSet(ver, newVersion); if(! result) { throw new RuntimeException("WTF"); } notifyOnCommit(); newVersion.clearOld(); } private void notifyOnCommit() { PersistentSet<TxListener> listners = this.listners; for(TxListener l : listners) { l.onCommit(); } } private boolean hasConflictingChanges(Version ver, TransactionInfo info) { for(TxVar<?> v : info.data.keySet()) { Object orig = info.version.data.get(v); Object ov = ver.data.get(v); Object oi = info.data.get(v); if(oi != orig && ov != orig) { return true; } } return false; } private Map<TxVar<?>, Object> merge(Version ver, TransactionInfo info) { Map<TxVar<?>, Object> result = new HashMap<TxVar<?>, Object>(ver.data); for(Map.Entry<TxVar<?>, Object> e : info.data.entrySet()) { result.put(e.getKey(), e.getValue()); } return result; } public void rollback() { TransactionInfo info = state.get(); info.rolledback = true; clearInfo(info); } private void clearInfo(TransactionInfo info) { order.remove(info); // order.poll(); state.remove(); info.version.transactionInfoCount.decrementAndGet(); TransactionInfo nextInfo = null; while((nextInfo = order.peek()) != null && nextInfo.rolledback) { order.poll(); } if(nextInfo != null) { synchronized (nextInfo) { nextInfo.notifyAll(); } } } protected Object get(TxVar<?> var) { ValuesDelta current = getInfo(false); return current.data.get(var); } protected void set(TxVar<?> var, Object nval) { ValuesDelta current = getInfo(true); current.data.put(var, nval); } private ValuesDelta getInfo(boolean withTransaction) { TransactionInfo transactionInfo = state.get(); if(transactionInfo != null && transactionInfo.rolledback) { throw new RuntimeException("Transaction already rolledback"); } if(withTransaction && transactionInfo == null) { throw new RuntimeException("Must be in transaction"); } if(withTransaction && transactionInfo.readonly) { throw new RuntimeException("Must start write transaction"); } return transactionInfo != null ? transactionInfo : versionRef.get(); } private static abstract class ValuesDelta { protected final Map<TxVar<?>, Object> data; public ValuesDelta(Map<TxVar<?>, Object> data) { this.data = data; } } private static class TransactionInfo extends ValuesDelta { protected final Version version; protected final boolean readonly; protected boolean rolledback; public TransactionInfo(Version version, boolean readonly) { super(version.newData()); this.version = version; this.readonly = readonly; } public TransactionInfo(Version version, Map<TxVar<?>, Object> data) { super(data); this.version = version; this.readonly = false; } } private static class Version extends ValuesDelta { protected final long id; protected final AtomicReference<Version> previousRef; protected final AtomicInteger transactionInfoCount = new AtomicInteger(); public Version(long id, Map<TxVar<?>, Object> data, Version previous) { super(data); this.id = id; this.previousRef = new AtomicReference<Version>(previous); } public void clearOld() { Version previous = previousRef.get(); if(previous != null) { previous.internalClear(this); } } private void internalClear(Version next) { Version previous = previousRef.get(); if(previous != null) { previous.internalClear(this); } previous = previousRef.get(); if(previous != null) { return; } if(transactionInfoCount.get() == 0) { next.previousRef.set(null); } } public Map<TxVar<?>, Object> newData() { return new HashMap<TxVar<?>, Object>(data); } @Override public String toString() { return "V" + id; } } }
import java.util.*; import java.io.*; public class GestaoGeral implements Serializable { // variaveis de instancia private GestaoAluguer alugueres; private GestaoAtor atores; private GestaoVeiculo veiculos; // construtores public GestaoGeral() { this.alugueres = new GestaoAluguer(); this.atores = new GestaoAtor(); this.veiculos = new GestaoVeiculo(); } public HashMap<String, Ator> getAtores() { return this.atores.getAtor(); } public HashMap<String, Veiculo> getVeiculos() { return this.veiculos.getVeiculo(); } public HashMap<Integer, Aluguer> getAlugueres() { return this.alugueres.getAluguer(); } // métodos para registar atores public void registaCliente(String emailAux, String nomeAux, String passwordAux, String moradaAux, Date dataNascimentoAux, double classificacaoAux, List<Realizado> alugueresAux, Ponto localizacaoAux) throws GestaoGeralException { if (atores.verifica(emailAux)) throw new GestaoGeralException(emailAux); else { Cliente c_aux = new Cliente(emailAux, nomeAux, passwordAux, moradaAux, dataNascimentoAux, classificacaoAux, alugueresAux,0, localizacaoAux); this.atores.addAtor(c_aux); } } public void registaProprietario(String emailAux, String nomeAux, String passwordAux, String moradaAux, Date dataNascimentoAux, double classificacaoAux, List<Realizado> alugueresAux) throws GestaoGeralException { if (atores.verifica(emailAux)) throw new GestaoGeralException(emailAux); else { Proprietario p_aux = new Proprietario(emailAux, nomeAux, passwordAux, moradaAux, dataNascimentoAux, classificacaoAux, alugueresAux,0); this.atores.addAtor(p_aux); } } // métodos para registar veiculos public void registaEletrico(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, Proprietario proprietarioAux, double consumoKmAux, double bateriaAtualAux, double tamanhoBateriaAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Eletrico e_aux = new Eletrico(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux, consumoKmAux, bateriaAtualAux, tamanhoBateriaAux, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(e_aux); } } public void registaPrancha(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, Proprietario proprietarioAux, double consumoKmAux, double bateriaAtualAux, double tamanhoBateriaAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Prancha p_aux = new Prancha(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux, consumoKmAux, bateriaAtualAux, tamanhoBateriaAux, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(p_aux); } } public void registaGasolina(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, Proprietario proprietarioAux, double consumoKmAux, double combustivelAtualAux, double tamanhoDepositoAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Gasolina g_aux = new Gasolina(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux, consumoKmAux, combustivelAtualAux, tamanhoDepositoAux, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(g_aux); } } public void registaBicicleta(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, Proprietario proprietarioAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Bicicleta b_aux = new Bicicleta(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux); this.veiculos.addVeiculo(b_aux); } } public void registaHibrido(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, Proprietario proprietarioAux, double consumoKmAuxEletricidade,double consumoKmAuxGasolina, double bateriaAtualAux, double tamanhoBateriaAux, double combustivelAtualAux, double tamanhoDepositoAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Hibridos h_aux = new Hibridos(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux, consumoKmAuxEletricidade,consumoKmAuxGasolina, bateriaAtualAux, tamanhoBateriaAux, combustivelAtualAux, tamanhoDepositoAux, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(h_aux); } } public void registaEletricoL(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, String proprietarioAux, double consumoKmAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Proprietario proprietarioAux2 = (Proprietario) this.getAtores().get(proprietarioAux + "@gmail.com"); Eletrico e_aux = new Eletrico(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux2, consumoKmAux, 0, 0, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(e_aux); this.veiculos.setCombustivel(matriculaAux); } } public void registaPranchaL(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, String proprietarioAux, double consumoKmAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Proprietario proprietarioAux2 = (Proprietario) this.getAtores().get(proprietarioAux + "@gmail.com"); Prancha p_aux = new Prancha(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux2, consumoKmAux,0,0, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(p_aux); this.veiculos.setCombustivel(matriculaAux); } } public void registaGasolinaL(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, String proprietarioAux, double consumoKmAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Proprietario proprietarioAux2 = (Proprietario) this.getAtores().get(proprietarioAux + "@gmail.com"); Gasolina g_aux = new Gasolina(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux2, consumoKmAux, 0,0, autonomiaAux, condicaoAux); this.veiculos.addVeiculo(g_aux); this.veiculos.setCombustivel(matriculaAux); } } public void registaBicicletaL(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, String proprietarioAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Proprietario proprietarioAux2 = (Proprietario) this.getAtores().get(proprietarioAux + "@gmail.com"); Bicicleta b_aux = new Bicicleta(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux2); this.veiculos.addVeiculo(b_aux); } } public void registaHibridoL(String matriculaAux, Ponto localizacaoAux, double precoKmAux, double velocidadeKmAux, double classificacaoAux, String descricaoAux, String proprietarioAux, double consumoKmAux, double autonomiaAux, Boolean condicaoAux) throws GestaoGeralException { if (veiculos.verifica(matriculaAux)) throw new GestaoGeralException(matriculaAux); else { Proprietario proprietarioAux2 = (Proprietario) this.getAtores().get(proprietarioAux + "@gmail.com"); Hibridos h_aux = new Hibridos(matriculaAux, localizacaoAux, precoKmAux, velocidadeKmAux, classificacaoAux, descricaoAux, proprietarioAux2, consumoKmAux,consumoKmAux,0,0,0,0, autonomiaAux, condicaoAux); this.veiculos.setCombustivel(matriculaAux); this.veiculos.addVeiculo(h_aux); } } // métodos para login public void loginCliente(String emailAux, String passwordAux) throws GestaoGeralException { if (atores.loginCl(emailAux, passwordAux) == false) throw new GestaoGeralException(emailAux); } public void loginProprietario(String emailAux, String passwordAux) throws GestaoGeralException { if (atores.loginProp(emailAux, passwordAux) == false) throw new GestaoGeralException(emailAux); } public void loginAdmin(String admin,String pass) throws GestaoGeralException { if ((admin.equals("admin"))==false || (pass.equals("123"))==false) throw new GestaoGeralException(); } // métodos para abastecimento public void abasteceVAUX(String matriculaAux, Proprietario prop) throws GestaoGeralException { if ((this.getVeiculos().get(matriculaAux) == null)) throw new GestaoGeralException(matriculaAux); if (((this.getVeiculos().get(matriculaAux).verificaDono(prop)) == false)) throw new GestaoGeralException(matriculaAux); } public void abasteceE(String matriculaAux, double quantidade) throws GestaoGeralException { HashMap<String, Veiculo> gv = new HashMap<String, Veiculo>(this.getVeiculos()); Eletrico e = new Eletrico(); e = (Eletrico) gv.get(matriculaAux); if (e.abasteceEletrico(quantidade) == -1) throw new GestaoGeralException(matriculaAux); else { e.abasteceEletrico(quantidade); this.veiculos.setVeiculo(gv); } } public void abasteceG(String matriculaAux, double quantidade) throws GestaoGeralException { HashMap<String, Veiculo> gv = new HashMap<String, Veiculo>(this.getVeiculos()); Gasolina ga = new Gasolina(); ga = (Gasolina) gv.get(matriculaAux); if (ga.abasteceGasolina(quantidade) == -1) throw new GestaoGeralException(matriculaAux); else { ga.abasteceGasolina(quantidade); this.veiculos.setVeiculo(gv); } } public void abasteceH(String matriculaAux, double quantidadeC, double quantidadeE) throws GestaoGeralException { HashMap<String, Veiculo> gv = new HashMap<String, Veiculo>(this.getVeiculos()); Hibridos h = new Hibridos(); h = (Hibridos) gv.get(matriculaAux); if (h.abasteceHibrido(quantidadeE, quantidadeC) == -1) throw new GestaoGeralException(matriculaAux); else { h.abasteceHibrido(quantidadeE, quantidadeC); this.veiculos.setVeiculo(gv); } } public void abasteceP(String matriculaAux, double quantidade) throws GestaoGeralException { HashMap<String, Veiculo> gv = new HashMap<String, Veiculo>(this.getVeiculos()); Prancha p = new Prancha(); p = (Prancha) gv.get(matriculaAux); if (p.abastecePrancha(quantidade) == -1) throw new GestaoGeralException(matriculaAux); else { p.abastecePrancha(quantidade); this.veiculos.setVeiculo(gv); } } // método para alteração de preço public void alteraPreco(String matriculaAux, double preco, Proprietario prop) throws GestaoGeralException { if ((this.getVeiculos().get(matriculaAux) == null)) throw new GestaoGeralException(matriculaAux); if (((this.getVeiculos().get(matriculaAux).verificaDono(prop)) == false)) throw new GestaoGeralException(matriculaAux); else { HashMap<String, Veiculo> gv = new HashMap<String, Veiculo>(this.getVeiculos()); Veiculo v = gv.get(matriculaAux); v.alteracaPrecoKm(preco); this.veiculos.setVeiculo(gv); } } // métodos para registar alugueres //pedido mais barato // qualquer tipo de veiculo public void registaPedidoBarato(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisBarato(destino).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBarato(destino))); int id = this.getAlugueres().size(); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato carro a gasolina public void registaPedidoBaratoGasolina(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoGasolina(destino).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoGasolina(destino))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato carro eletrico public void registaPedidoBaratoEletrico(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoEletrico(destino).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoEletrico(destino))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato carro hibrido public void registaPedidoBaratoHibrido(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoHibrido(destino).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoHibrido(destino))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato prancha public void registaPedidoBaratoPrancha(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoPrancha(destino).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoPrancha(destino))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato bike public void registaPedidoBaratoBicicleta(Date dataAux, Cliente clienteAux,Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoBicicleta().equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoBicicleta())); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } //Pedido mais proximo // qualquer tipo de veiculo public void registaPedidoProximo(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisPerto(destino, clienteAux.getLocalizacao()).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisPerto(destino, clienteAux.getLocalizacao()))); int id = this.getAlugueres().size(); // posteriormente por como variavel de classe ?? Proprietario propAux = veiculoAux.getProprietario(); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais perto carro a gasolina public void registaPedidoProximoGasolina(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisPertoGasolina(destino, clienteAux.getLocalizacao()).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisPertoGasolina(destino, clienteAux.getLocalizacao()))); int id = this.getAlugueres().size(); // posteriormente por como variavel de classe ?? Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais perto carro eletrico public void registaPedidoProximoEletrico(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisPertoEletrico(destino, clienteAux.getLocalizacao()).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisPertoEletrico(destino, clienteAux.getLocalizacao()))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais perto carro hibrido public void registaPedidoProximoHibrido(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisPertoHibrido(destino, clienteAux.getLocalizacao()).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisPertoHibrido(destino, clienteAux.getLocalizacao()))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais perto prancha public void registaPedidoProximoPrancha(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisPertoPrancha(destino, clienteAux.getLocalizacao()).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisPertoPrancha(destino, clienteAux.getLocalizacao()))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais perto bike public void registaPedidoProximoBicicleta(Date dataAux, Cliente clienteAux, Ponto destino) throws GestaoGeralException { if (this.veiculos.procuraMaisPertoBicicleta(clienteAux.getLocalizacao()).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisPertoBicicleta(clienteAux.getLocalizacao()))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } //pedido mais barato dentro de uma distancia // qualquer tipo de veiculo public void registaPedidoBaratoDist(Date dataAux, Cliente clienteAux, Ponto destino, double dist) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoDist(destino, clienteAux.getLocalizacao(), dist).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoDist(destino, clienteAux.getLocalizacao(), dist))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato carro a gasolina public void registaPedidoBaratoGasolinaDist(Date dataAux, Cliente clienteAux, Ponto destino, double dist) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoGasolinaDist(destino, clienteAux.getLocalizacao(), dist).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoGasolinaDist(destino, clienteAux.getLocalizacao(), dist))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato carro eletrico public void registaPedidoBaratoEletricoDist(Date dataAux, Cliente clienteAux,Ponto destino, double dist) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoEletricoDist(destino, clienteAux.getLocalizacao(), dist).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoEletricoDist(destino, clienteAux.getLocalizacao(), dist))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato carro hibrido public void registaPedidoBaratoHibridoDist(Date dataAux, Cliente clienteAux,Ponto destino, double dist) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoHibridoDist(destino, clienteAux.getLocalizacao(), dist).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoHibridoDist(destino, clienteAux.getLocalizacao(), dist))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato prancha public void registaPedidoBaratoPranchaDist(Date dataAux, Cliente clienteAux,Ponto destino, double dist) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoPranchaDist(destino, clienteAux.getLocalizacao(), dist).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoPranchaDist(destino, clienteAux.getLocalizacao(), dist))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // mais barato bike public void registaPedidoBaratoBicicletaDist(Date dataAux, Cliente clienteAux, Ponto destino, double dist) throws GestaoGeralException { if (this.veiculos.procuraMaisBaratoBicicletaDist(clienteAux.getLocalizacao(), dist).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = (this.getVeiculos().get(this.veiculos.procuraMaisBaratoBicicletaDist(clienteAux.getLocalizacao(), dist))); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // pedido de um carro especifico public void registaEspecifico(Date dataAux, Cliente clienteAux,Ponto destino, String ma) throws GestaoGeralException { int id = this.getAlugueres().size(); Veiculo veiculoAux = this.getVeiculos().get(ma); if (this.getVeiculos().get(ma) == null) throw new GestaoGeralException(ma); if (veiculoAux instanceof Bicicleta) { double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } else { if (veiculoAux instanceof Gasolina) { Gasolina g = (Gasolina) veiculoAux; if (g.getAutonomia() < g.getLocalizacao().distanciaPonto(destino)) throw new GestaoGeralException(ma); else { double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } if (veiculoAux instanceof Eletrico) { Eletrico e = (Eletrico) veiculoAux; if (e.getAutonomia() < e.getLocalizacao().distanciaPonto(destino)) throw new GestaoGeralException(ma); else { double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } if (veiculoAux instanceof Hibridos) { Hibridos h = (Hibridos) veiculoAux; if (h.getAutonomia() < h.getLocalizacao().distanciaPonto(destino)) throw new GestaoGeralException(ma); else { double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } if (veiculoAux instanceof Prancha) { Prancha p = (Prancha) veiculoAux; if (p.getAutonomia() < p.getLocalizacao().distanciaPonto(destino)) throw new GestaoGeralException(ma); else { double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); Pedido pe = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(pe); } } } } // registo de pedidos com certa autonomia // qualquer tipo de veiculo public void registaPedidoAutonomia(Date dataAux, Cliente clienteAux, Ponto destino, double autonomia) throws GestaoGeralException { if (this.veiculos.procuraAutonomia(destino,autonomia).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = this.getVeiculos().get(this.veiculos.procuraAutonomia(destino,autonomia)); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // carro a gasolina public void registaPedidoAutonomiaGasolina(Date dataAux, Cliente clienteAux, Ponto destino, double autonomia) throws GestaoGeralException { if (this.veiculos.procuraAutonomiaGasolina(destino,autonomia).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = this.getVeiculos().get(this.veiculos.procuraAutonomiaGasolina(destino,autonomia)); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // carro eletrico public void registaPedidoAutonomiaEletrico(Date dataAux, Cliente clienteAux,Ponto destino, double autonomia) throws GestaoGeralException { if (this.veiculos.procuraAutonomiaEletrico(destino,autonomia).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = this.getVeiculos().get(this.veiculos.procuraAutonomiaEletrico(destino,autonomia)); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // carro hibrido public void registaPedidoAutonomiaHibrido(Date dataAux, Cliente clienteAux,Ponto destino, double autonomia) throws GestaoGeralException { if (this.veiculos.procuraAutonomiaHibrido(destino,autonomia).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = this.getVeiculos().get(this.veiculos.procuraAutonomiaHibrido(destino,autonomia)); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // prancha public void registaPedidoAutonomiaPrancha(Date dataAux, Cliente clienteAux,Ponto destino, double autonomia) throws GestaoGeralException { if (this.veiculos.procuraAutonomiaPrancha(destino,autonomia).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = this.getVeiculos().get(this.veiculos.procuraAutonomiaPrancha(destino,autonomia)); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // bike public void registaPedidoAutonomiaBicicleta(Date dataAux, Cliente clienteAux, Ponto destino, double autonomia) throws GestaoGeralException { if (this.veiculos.procuraAutonomiaBicicleta(destino).equals("")) throw new GestaoGeralException(destino.toString()); else { Veiculo veiculoAux = this.getVeiculos().get(this.veiculos.procuraAutonomiaBicicleta(destino)); int id = this.getAlugueres().size(); Proprietario propAux = new Proprietario(veiculoAux.getProprietario()); double tempo = veiculoAux.getLocalizacao().tempoHumano(clienteAux.getLocalizacao()); Pedido p = new Pedido(id, veiculoAux, dataAux, clienteAux, propAux, false, false, destino, tempo); this.alugueres.addPedido(p); } } // método que aceita pedido e trata de todas as atualizaçoes necessarias public void AceitaPedido(int idP,Proprietario p) throws GestaoGeralException { if ((this.getAlugueres().get(idP)) instanceof Realizado) throw new GestaoGeralException(String.valueOf(idP)); Pedido pd = (Pedido) this.getAlugueres().get(idP); if (pd == null) throw new GestaoGeralException(String.valueOf(idP)); if (pd.getflagRespondido() != false) throw new GestaoGeralException(String.valueOf(idP)); if (pd.getProprietario().getEmail().equals(p.getEmail())==false) throw new GestaoGeralException(String.valueOf(idP)); else { pd.setFlagRespondido(true); pd.setRespostaProp(true); double km = pd.getVeiculo().getLocalizacao().distanciaPonto(pd.getDestino()); double duracao = km / pd.getVeiculo().getVelocidadeKm(); double preco = km * pd.getVeiculo().getPrecoKm(); int id = this.getAlugueres().size(); Date data = new Date(); Realizado r = new Realizado(id,pd.getVeiculo(),data,pd.getCliente(),pd.getProprietario(),-1,-1,-1,preco,duracao,km); this.alugueres.remove(this.getAlugueres().get(idP).getVeiculo().getMatricula(),this.getAlugueres().get(idP).getCliente()); //está a dar shit!!!! this.atores.atualizaProp(r,pd.getProprietario().getEmail()); this.alugueres.addRealizado(r); this.veiculos.atualizaVeiculo(pd.getVeiculo().getMatricula(), pd.getDestino()); this.atores.atualizaCliente(pd.getDestino(),pd.getCliente().getEmail(),r); } } // historico public List<Realizado> RealizadosProp(Proprietario p){ return p.getAlugueres(); } public List<Realizado> RealizadosCliente(Cliente c){ return c.getAlugueres(); } public List<Realizado> RealizadosPropDatas(Proprietario p,Date inicio,Date fim){ List<Realizado> list = new ArrayList<>(p.getAlugueres()); List<Realizado> list2 = new ArrayList<>(); for(Realizado a : list) if (a.getData().after(inicio) && a.getData().before(fim)) list2.add(a); return list2; } public List<Realizado> RealizadosClienteDatas(Cliente c,Date inicio, Date fim){ ArrayList<Realizado> list = new ArrayList<>(c.getAlugueres()); ArrayList<Realizado> list2 = new ArrayList<>(); for(Realizado a : list) if (a.getData().after(inicio) && a.getData().before(fim)) list2.add(a); return list2; } // faturado veiculo public double faturadoVeiculo(String matricula,Proprietario p, Date inicio, Date fim) throws GestaoGeralException{ if (this.getVeiculos().get(matricula) == null) throw new GestaoGeralException(matricula); if (this.getVeiculos().get(matricula).getProprietario().getEmail().equals(p.getEmail()) == false) throw new GestaoGeralException(matricula); else { return this.alugueres.faturacao(matricula,inicio,fim); } } // rankings public TreeSet<Cliente> rank10Vezes() { TreeSet<Cliente> t = new TreeSet<>(new ComparadorNrVezes()); ArrayList<Ator> atores = new ArrayList<Ator> (this.getAtores().values()); for (Ator a : atores) if (a instanceof Cliente) t.add(((Cliente) a).clone()); return t; } public TreeSet<Cliente> rank10km() { TreeSet<Cliente> t = new TreeSet<>(new ComparadorKmPercorridos()); ArrayList<Ator> atores = new ArrayList<Ator>(this.getAtores().values()); for (Ator a : atores) if (a instanceof Cliente) t.add(((Cliente) a).clone()); return t; } // notificacoes public List<Veiculo> notificacoes(Proprietario p){ ArrayList<Veiculo> list = new ArrayList<Veiculo>(this.getVeiculos().values()); ArrayList<Veiculo> resultado = new ArrayList<Veiculo>(); for(Veiculo v : list) if (v.getProprietario().getEmail().equals(p.getEmail())){ if (v instanceof Hibridos && ((Hibridos)v).getCondicao() == false) resultado.add(v); if (v instanceof Gasolina && ((Gasolina)v).getCondicao() == false) resultado.add(v); if (v instanceof Eletrico && ((Eletrico)v).getCondicao() == false) resultado.add(v); if (v instanceof Prancha && ((Prancha)v).getCondicao() == false) resultado.add(v); } return resultado; } // admin public List<Veiculo> listagemVeiculos(){ ArrayList<Veiculo> list = new ArrayList<Veiculo>(this.getVeiculos().values()); return list; } public List<Cliente> listagemClientes(){ ArrayList<Ator> list = new ArrayList<Ator>(this.getAtores().values()); ArrayList<Cliente> list2 = new ArrayList<Cliente>(); for(Ator a : list) if (a instanceof Cliente) list2.add((Cliente)a); return list2; } public List<Proprietario> listagemProprietarios(){ ArrayList<Ator> list = new ArrayList<Ator>(this.getAtores().values()); ArrayList<Proprietario> list2 = new ArrayList<Proprietario>(); for(Ator a : list) if (a instanceof Proprietario) list2.add((Proprietario) a); return list2; } public List<Realizado> listagemAlugueresRealizados(){ ArrayList<Aluguer> list = new ArrayList<Aluguer>(this.getAlugueres().values()); ArrayList<Realizado> list2 = new ArrayList<Realizado>(); for(Aluguer a : list) if (a instanceof Realizado) list2.add((Realizado) a); return list2; } public List<Pedido> listagemPedidos(){ ArrayList<Aluguer> list = new ArrayList<Aluguer>(this.getAlugueres().values()); ArrayList<Pedido> list2 = new ArrayList<Pedido>(); for(Aluguer a : list) { if (a instanceof Pedido) list2.add((Pedido) a); } return list2; } // lista alugueres possiveis de aceitar por parte do proprietario public List<Pedido> listaPedidos(Proprietario prop){ ArrayList<Aluguer> list = new ArrayList<Aluguer>(this.getAlugueres().values()); ArrayList<Pedido> pedidos = new ArrayList<Pedido>(); for(Aluguer a: list) if((a instanceof Pedido) && ((Pedido)a).getflagRespondido()==false && a.getProprietario().getEmail().equals(prop.getEmail()) ) pedidos.add((Pedido)a); return pedidos; } // logs public String logsGasolinaMaisPerto(Ponto destino,Ponto cliente){ return this.veiculos.procuraMaisPertoGasolina(destino,cliente); } public String logsGasolinaMaisBarato(Ponto destino){ return this.veiculos.procuraMaisBaratoGasolina(destino); } public String logsEletricoMaisPerto(Ponto destino,Ponto cliente){ return this.veiculos.procuraMaisPertoEletrico(destino,cliente); } public String logsEletricoMaisBarato(Ponto destino){ return this.veiculos.procuraMaisBaratoEletrico(destino); } public void logsRegistaAluguer(String matricula,String emailCliente,Ponto destino){ int id = this.getAlugueres().size(); Date data = new Date(); double km = this.getVeiculos().get(matricula).getLocalizacao().distanciaPonto(destino); double duracao = km / this.getVeiculos().get(matricula).getVelocidadeKm(); double preco = km * this.getVeiculos().get(matricula).getPrecoKm(); Realizado r = new Realizado(id,this.getVeiculos().get(matricula),data,(Cliente)this.getAtores().get(emailCliente),this.getVeiculos().get(matricula).getProprietario(),-1,-1,-1,preco,duracao,km); // passar a -1 this.alugueres.addRealizado(r); this.atores.atualizaProp(r,this.getVeiculos().get(matricula).getProprietario().getEmail()); this.atores.atualizaClientelogs(r.getCliente().getEmail(),r); } // métodos que tratam da clasificação public void registaClassProp(int idA,double classificacao,Proprietario p) throws GestaoGeralException{ if (this.getAlugueres().get(idA) == null) throw new GestaoGeralException(String.valueOf(idA)); if (this.getAlugueres().get(idA).getProprietario().getEmail().equals(p.getEmail()) == false) throw new GestaoGeralException(String.valueOf(idA)); if (((Realizado)(this.getAlugueres().get(idA))).getClassificacaoCliente() != -1) throw new GestaoGeralException(String.valueOf(idA)); else { this.alugueres.classificacaoProprietario(idA,classificacao); this.atores.atualizaClassificacaoCliente(classificacao,this.getAlugueres().get(idA).getCliente()); } } public void registaClassCliente(int idA,double classificacaoVeiculo,double classificacaoProp,Cliente c) throws GestaoGeralException{ if (this.getAlugueres().get(idA) == null) throw new GestaoGeralException(String.valueOf(idA)); if (this.getAlugueres().get(idA).getCliente().getEmail().equals(c.getEmail()) == false) throw new GestaoGeralException(String.valueOf(idA)); if ((((Realizado)(this.getAlugueres().get(idA))).getClassificacaoProprietario() != -1) || (((Realizado)(this.getAlugueres().get(idA))).getClassificacaoVeiculo() != -1)) throw new GestaoGeralException(String.valueOf(idA)); else { this.alugueres.classificacaoCliente(idA,classificacaoProp,classificacaoVeiculo); this.atores.atualizaClassificacaoProprietario(classificacaoProp,this.getAlugueres().get(idA).getProprietario()); this.veiculos.atualizaClassificacaoVeiculo(classificacaoVeiculo,this.getVeiculos().get(this.getAlugueres().get(idA).getVeiculo().getMatricula())); } } public List<Realizado> listaClassificarProp(Proprietario p){ return this.alugueres.realidadosClassificarProp(p); } public List<Realizado> listaClassificarCliente(Cliente c){ return this.alugueres.realizadosClassificarCliente(c); } // gravar e carregar //metodo para gravar estado public void guardaEstado() throws FileNotFoundException,IOException { FileOutputStream fos1 = new FileOutputStream("GAluguer"); FileOutputStream fos2 = new FileOutputStream("GAtores"); FileOutputStream fos3 = new FileOutputStream("GVeiculos"); ObjectOutputStream oos1 = new ObjectOutputStream(fos1); ObjectOutputStream oos2 = new ObjectOutputStream(fos2); ObjectOutputStream oos3 = new ObjectOutputStream(fos3); oos1.writeObject(this.alugueres); oos2.writeObject(this.atores); oos3.writeObject(this.veiculos); oos1.flush(); oos2.flush(); oos3.flush(); oos1.close(); oos2.close(); oos3.close(); } //metodo para carregar estado public void carregaEstado() throws FileNotFoundException,IOException, ClassNotFoundException{ FileInputStream fis1 = new FileInputStream("GAluguer"); FileInputStream fis2 = new FileInputStream("GAtores"); FileInputStream fis3 = new FileInputStream("GVeiculos"); ObjectInputStream ois1 = new ObjectInputStream(fis1); ObjectInputStream ois2 = new ObjectInputStream(fis2); ObjectInputStream ois3 = new ObjectInputStream(fis3); alugueres = (GestaoAluguer) ois1.readObject(); atores = (GestaoAtor) ois2.readObject(); veiculos = (GestaoVeiculo) ois3.readObject(); ois1.close(); ois2.close(); ois3.close(); } }
package com.bitbus.fantasyprep; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import com.bitbus.fantasyprep.auction.Auction; import com.bitbus.fantasyprep.auction.AuctionService; import com.bitbus.fantasyprep.auction.PlayerAuction; import com.bitbus.fantasyprep.player.Player; import com.bitbus.fantasyprep.player.PlayerService; import com.bitbus.fantasyprep.player.Position; import com.bitbus.fantasyprep.team.TeamAbbreviation; import lombok.extern.slf4j.Slf4j; @SpringBootApplication @Slf4j public class DefaultAuctionValuesLoader { public static final String AUCTION_ID = "PFF-Custom"; private static final String AUCTION_CSV = "C:\\Users\\Lisa\\Desktop\\auction-yahoo.csv"; @Autowired private PlayerService playerService; @Autowired private PlayerProjectionsLoader playerProjectionsLoader; @Autowired private AuctionService auctionService; public static void main(String[] args) throws IOException { ConfigurableApplicationContext ctx = SpringApplication.run(DefaultAuctionValuesLoader.class, args); DefaultAuctionValuesLoader defaultAuctionValuesLoader = ctx.getBean(DefaultAuctionValuesLoader.class); defaultAuctionValuesLoader.load(); } public void load() throws IOException { Auction auction = new Auction(); auction.setAuctionId(AUCTION_ID); auction.setDescription("Auction values per Pro Football Focus"); auction.setCreationTime(LocalDateTime.now()); List<Player> players = playerService.findAll(); if (players.size() == 0) { log.info("Player projections not loaded yet, running that process first"); playerProjectionsLoader.load(); players = playerService.findAll(); } else { log.info("Player projections already loaded, ready to load auction values"); } log.info("Loading the default auction values"); List<PlayerAuction> playerAuctionValues = new ArrayList<>(); try (BufferedReader reader = Files.newBufferedReader(Paths.get(AUCTION_CSV)); CSVParser csvParser = new CSVParser(reader, CSVFormat.EXCEL // .withHeader("Id", "Name", "Team", "Bye", "Position", "Proj Pts", "VoRepl", "VoNext", "Auction $", "PFF Ranking", "Expert Raank", "Projection-Based Ranking", "ADP") .withSkipHeaderRecord());) { for (CSVRecord csvRecord : csvParser) { PlayerAuction playerAuction = new PlayerAuction(); String playerName = csvRecord.get(1); TeamAbbreviation playerTeam = TeamAbbreviation.valueOf(csvRecord.get(2)); Position playerPosition = Position.valueOf(csvRecord.get(4).toUpperCase()); if (playerPosition == Position.K || playerPosition == Position.DST) { continue; } Optional<Player> player = players.stream() // .filter(playerPredicate -> playerPredicate.getPlayerName().equals(playerName)) // .filter(playerPredicate -> playerPredicate.getTeam().getAbbreviation() == playerTeam) // .findFirst(); if (!player.isPresent()) { continue; } playerAuction.setPlayer(player.get()); playerAuction.setAuction(auction); playerAuction.setAuctionValue(Math.max(Double.valueOf(csvRecord.get(8)), 1)); playerAuctionValues.add(playerAuction); } } auction.setPlayerAuctionValues(playerAuctionValues); auctionService.create(auction); log.info("Done loading the default auction values"); } }
/* 1: */ package com.kaldin.email.hibernate; /* 2: */ /* 3: */ import com.kaldin.common.util.HibernateUtil; /* 4: */ import com.kaldin.common.util.PagingBean; /* 5: */ import com.kaldin.email.dto.EmailTemplateDTO; /* 6: */ import java.util.Iterator; /* 7: */ import java.util.List; /* 8: */ import org.hibernate.HibernateException; /* 9: */ import org.hibernate.Query; /* 10: */ import org.hibernate.Session; /* 11: */ import org.hibernate.Transaction; /* 12: */ /* 13: */ public class EmailTemplateHibernate /* 14: */ { /* 15: */ public EmailTemplateDTO getEmailTemplate(String templateName, int companyid) /* 16: */ { /* 17: 18 */ EmailTemplateDTO emailTemplateDTO = new EmailTemplateDTO(); /* 18: 19 */ Transaction trObj = null; /* 19: 20 */ Session sesObj = null; /* 20: 21 */ List<?> listObj = null; /* 21: */ try /* 22: */ { /* 23: 23 */ sesObj = HibernateUtil.getSession(); /* 24: 24 */ trObj = HibernateUtil.getTrascation(sesObj); /* 25: 25 */ Query query = sesObj.createQuery("from EmailTemplateDTO emailDTO where emailDTO.companyid in(?,0) and emailDTO.mailtype = ? order by emailDTO.companyid desc limit 1"); /* 26: */ /* 27: */ /* 28: 28 */ query.setInteger(0, companyid); /* 29: 29 */ query.setString(1, templateName); /* 30: 30 */ query.setMaxResults(1); /* 31: 31 */ listObj = query.list(); /* 32: 32 */ Iterator<?> listiter = listObj.iterator(); /* 33: 33 */ while (listiter.hasNext()) { /* 34: 34 */ emailTemplateDTO = (EmailTemplateDTO)listiter.next(); /* 35: */ } /* 36: 36 */ trObj.commit(); /* 37: */ } /* 38: */ catch (HibernateException e) /* 39: */ { /* 40: 38 */ trObj.rollback(); /* 41: 39 */ e.printStackTrace(); /* 42: */ } /* 43: */ finally /* 44: */ { /* 45: 41 */ sesObj.close(); /* 46: */ } /* 47: 44 */ return emailTemplateDTO; /* 48: */ } /* 49: */ /* 50: */ public EmailTemplateDTO getEmailTemplate(int id, int companyid) /* 51: */ { /* 52: 48 */ EmailTemplateDTO emailTemplateDTO = new EmailTemplateDTO(); /* 53: 49 */ Transaction trObj = null; /* 54: 50 */ Session sesObj = null; /* 55: 51 */ List<?> listObj = null; /* 56: */ try /* 57: */ { /* 58: 53 */ sesObj = HibernateUtil.getSession(); /* 59: 54 */ trObj = HibernateUtil.getTrascation(sesObj); /* 60: 55 */ Query query = sesObj.createQuery("from EmailTemplateDTO emailDTO where emailDTO.id = ?"); /* 61: */ /* 62: 57 */ query.setInteger(0, id); /* 63: 58 */ listObj = query.list(); /* 64: 59 */ Iterator<?> listiter = listObj.iterator(); /* 65: 60 */ while (listiter.hasNext()) { /* 66: 61 */ emailTemplateDTO = (EmailTemplateDTO)listiter.next(); /* 67: */ } /* 68: 63 */ trObj.commit(); /* 69: */ } /* 70: */ catch (HibernateException e) /* 71: */ { /* 72: 65 */ trObj.rollback(); /* 73: 66 */ e.printStackTrace(); /* 74: */ } /* 75: */ finally /* 76: */ { /* 77: 68 */ sesObj.close(); /* 78: */ } /* 79: 71 */ return emailTemplateDTO; /* 80: */ } /* 81: */ /* 82: */ public boolean saveEmailTemplate(EmailTemplateDTO emailTemplateDTO) /* 83: */ { /* 84: 75 */ Session sesObj = null; /* 85: 76 */ Transaction trObj = null; /* 86: */ try /* 87: */ { /* 88: 79 */ sesObj = HibernateUtil.getSession(); /* 89: 80 */ trObj = HibernateUtil.getTrascation(sesObj); /* 90: */ /* 91: 82 */ sesObj.save(emailTemplateDTO); /* 92: 83 */ trObj.commit(); /* 93: 84 */ return true; /* 94: */ } /* 95: */ catch (HibernateException e) /* 96: */ { /* 97: 86 */ trObj.rollback(); /* 98: 87 */ e.printStackTrace(); /* 99: */ } /* 100: */ finally /* 101: */ { /* 102: 89 */ sesObj.close(); /* 103: */ } /* 104: 91 */ return false; /* 105: */ } /* 106: */ /* 107: */ public boolean editEmailTemplate(EmailTemplateDTO emailTemplateDTO) /* 108: */ { /* 109: 95 */ Session sesObj = null; /* 110: 96 */ Transaction trObj = null; /* 111: */ try /* 112: */ { /* 113: 99 */ sesObj = HibernateUtil.getSession(); /* 114:100 */ trObj = HibernateUtil.getTrascation(sesObj); /* 115:101 */ EmailTemplateDTO dtoObj = (EmailTemplateDTO)sesObj.get(EmailTemplateDTO.class, Integer.valueOf(emailTemplateDTO.getId())); /* 116: */ /* 117:103 */ dtoObj.setMailtype(emailTemplateDTO.getMailtype()); /* 118:104 */ dtoObj.setMailsubject(emailTemplateDTO.getMailsubject()); /* 119:105 */ dtoObj.setMailcontent(emailTemplateDTO.getMailcontent()); /* 120:106 */ dtoObj.setType(emailTemplateDTO.getType()); /* 121:107 */ dtoObj.setFromfield(emailTemplateDTO.getFromfield()); /* 122:108 */ dtoObj.setCcfield(emailTemplateDTO.getCcfield()); /* 123:109 */ dtoObj.setBccfield(emailTemplateDTO.getBccfield()); /* 124:110 */ dtoObj.setHeader(emailTemplateDTO.getHeader()); /* 125:111 */ dtoObj.setFooter(emailTemplateDTO.getFooter()); /* 126: */ /* 127:113 */ trObj.commit(); /* 128:114 */ return true; /* 129: */ } /* 130: */ catch (HibernateException e) /* 131: */ { /* 132: */ boolean bool; /* 133:116 */ trObj.rollback(); /* 134:117 */ e.printStackTrace(); /* 135:118 */ return false; /* 136: */ } /* 137: */ finally /* 138: */ { /* 139:120 */ sesObj.close(); /* 140: */ } /* 141: */ } /* 142: */ /* 143: */ public boolean deleteEmailTemplate(EmailTemplateDTO emailTemplateDTO) /* 144: */ { /* 145:125 */ Session sesObj = null; /* 146:126 */ Transaction trObj = null; /* 147: */ try /* 148: */ { /* 149:129 */ sesObj = HibernateUtil.getSession(); /* 150:130 */ trObj = HibernateUtil.getTrascation(sesObj); /* 151: */ /* 152:132 */ EmailTemplateDTO dtoObj = (EmailTemplateDTO)sesObj.get(EmailTemplateDTO.class, Integer.valueOf(emailTemplateDTO.getId())); /* 153: */ /* 154:134 */ sesObj.delete(dtoObj); /* 155:135 */ trObj.commit(); /* 156:136 */ return true; /* 157: */ } /* 158: */ catch (HibernateException e) /* 159: */ { /* 160: */ boolean bool; /* 161:138 */ trObj.rollback(); /* 162:139 */ e.printStackTrace(); /* 163:140 */ return false; /* 164: */ } /* 165: */ finally /* 166: */ { /* 167:142 */ sesObj.close(); /* 168: */ } /* 169: */ } /* 170: */ /* 171: */ public List<?> showEmailTemplate() /* 172: */ { /* 173:147 */ Session sesObj = null; /* 174:148 */ Transaction trObj = null; /* 175:149 */ List<?> listObj = null; /* 176: */ try /* 177: */ { /* 178:151 */ sesObj = HibernateUtil.getSession(); /* 179:152 */ trObj = HibernateUtil.getTrascation(sesObj); /* 180:153 */ Query qry = sesObj.createQuery("from EmailTemplateDTO emailTemplateDTO "); /* 181: */ /* 182:155 */ listObj = qry.list(); /* 183:156 */ trObj.commit(); /* 184: */ } /* 185: */ catch (HibernateException e) /* 186: */ { /* 187:158 */ trObj.rollback(); /* 188:159 */ e.printStackTrace(); /* 189: */ } /* 190: */ finally /* 191: */ { /* 192:161 */ sesObj.close(); /* 193: */ } /* 194:163 */ return listObj; /* 195: */ } /* 196: */ /* 197: */ public List<?> showEmailTemplate(int companyId) /* 198: */ { /* 199:167 */ Session sesObj = null; /* 200:168 */ Transaction trObj = null; /* 201:169 */ List<?> listObj = null; /* 202: */ try /* 203: */ { /* 204:171 */ sesObj = HibernateUtil.getSession(); /* 205:172 */ trObj = HibernateUtil.getTrascation(sesObj); /* 206:173 */ Query qry = sesObj.createQuery("from EmailTemplateDTO emailTemplateDTO where emailTemplateDTO.companyid=? and emailTemplateDTO.mailtype in ('Test Result','Scheduled Exam','Public Exam Result','Candidate Exam Result','Forgot Password Candidate','Reset Password Candidate')"); /* 207:174 */ qry.setParameter(0, Integer.valueOf(companyId)); /* 208:175 */ listObj = qry.list(); /* 209:176 */ trObj.commit(); /* 210: */ } /* 211: */ catch (HibernateException e) /* 212: */ { /* 213:178 */ trObj.rollback(); /* 214:179 */ e.printStackTrace(); /* 215: */ } /* 216: */ finally /* 217: */ { /* 218:181 */ sesObj.close(); /* 219: */ } /* 220:183 */ return listObj; /* 221: */ } /* 222: */ /* 223: */ public List<?> showEmailTemplate(PagingBean pagingBean, int records) /* 224: */ { /* 225:188 */ Session sesObj = null; /* 226:189 */ Transaction trObj = null; /* 227:190 */ List<?> listObj = null; /* 228: */ try /* 229: */ { /* 230:192 */ sesObj = HibernateUtil.getSession(); /* 231:193 */ trObj = HibernateUtil.getTrascation(sesObj); /* 232:194 */ Query query = sesObj.createQuery("from EmailTemplateDTO emailTemplateDTO "); /* 233: */ /* 234:196 */ pagingBean.setCount(records); /* 235:197 */ query.setFirstResult(pagingBean.getStartRec()); /* 236:198 */ query.setMaxResults(pagingBean.getPageSize()); /* 237:199 */ listObj = query.list(); /* 238:200 */ trObj.commit(); /* 239: */ } /* 240: */ catch (HibernateException e) /* 241: */ { /* 242:202 */ trObj.rollback(); /* 243:203 */ e.printStackTrace(); /* 244: */ } /* 245: */ finally /* 246: */ { /* 247:205 */ sesObj.close(); /* 248: */ } /* 249:207 */ return listObj; /* 250: */ } /* 251: */ /* 252: */ public EmailTemplateDTO getLatestSavedRecord() /* 253: */ { /* 254:211 */ Transaction trObj = null; /* 255:212 */ Session sesObj = null; /* 256:213 */ List<?> listObj = null; /* 257:214 */ EmailTemplateDTO emailTemplateDTO = null; /* 258: */ try /* 259: */ { /* 260:216 */ sesObj = HibernateUtil.getSession(); /* 261:217 */ trObj = HibernateUtil.getTrascation(sesObj); /* 262:218 */ listObj = sesObj.createQuery("from EmailTemplateDTO").list(); /* 263:219 */ Iterator<?> listiter = listObj.iterator(); /* 264:220 */ while (listiter.hasNext()) { /* 265:221 */ emailTemplateDTO = (EmailTemplateDTO)listiter.next(); /* 266: */ } /* 267:223 */ trObj.commit(); /* 268: */ } /* 269: */ catch (HibernateException e) /* 270: */ { /* 271:225 */ trObj.rollback(); /* 272:226 */ e.printStackTrace(); /* 273: */ } /* 274: */ finally /* 275: */ { /* 276:228 */ sesObj.close(); /* 277: */ } /* 278:230 */ return emailTemplateDTO; /* 279: */ } /* 280: */ /* 281: */ public boolean copyEmailTemplates(int destincationCompany) /* 282: */ { /* 283:234 */ List<?> listObj1 = showEmailTemplate(0); /* 284:236 */ for (Object object : listObj1) /* 285: */ { /* 286:237 */ EmailTemplateDTO emailTemplateDTO = (EmailTemplateDTO)object; /* 287:238 */ EmailTemplateDTO dtoObj = new EmailTemplateDTO(); /* 288:239 */ dtoObj.setMailtype(emailTemplateDTO.getMailtype()); /* 289:240 */ dtoObj.setMailsubject(emailTemplateDTO.getMailsubject()); /* 290:241 */ dtoObj.setMailcontent(emailTemplateDTO.getMailcontent()); /* 291:242 */ dtoObj.setType(emailTemplateDTO.getType()); /* 292:243 */ dtoObj.setFromfield(emailTemplateDTO.getFromfield()); /* 293:244 */ dtoObj.setCcfield(emailTemplateDTO.getCcfield()); /* 294:245 */ dtoObj.setBccfield(emailTemplateDTO.getBccfield()); /* 295:246 */ dtoObj.setHeader(emailTemplateDTO.getHeader()); /* 296:247 */ dtoObj.setFooter(emailTemplateDTO.getFooter()); /* 297:248 */ dtoObj.setCompanyid(destincationCompany); /* 298:249 */ saveEmailTemplate(dtoObj); /* 299: */ } /* 300:251 */ return true; /* 301: */ } /* 302: */ } /* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip * Qualified Name: kaldin.email.hibernate.EmailTemplateHibernate * JD-Core Version: 0.7.0.1 */
package org.christophe.marchal.redis.client.jedis.utils; import java.util.List; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.PipelineBlock; import redis.clients.jedis.exceptions.JedisConnectionException; public class JedisExecutor { private JedisPool pool; private JedisPool slavePool; public void close(){ pool.destroy(); slavePool.destroy(); } public <T> T set(JedisCallback<T> callback, String key, String value){ Jedis jConnection = null; try{ jConnection = pool.getResource(); String res = jConnection.set(key, value); return callback.handleResult(res); } catch(JedisConnectionException jce){ changeSlaveToMaster(); set(callback, key, value); } catch(Exception e){ callback.handleErrors(e); } finally { pool.returnResource(jConnection); } return null; } public <T> T mget( JedisCallback<T> callback, String... keys){ Jedis jConnection = null; try{ jConnection = pool.getResource(); List<String> res = jConnection.mget(keys); return callback.handleResult(res); } catch(JedisConnectionException jce){ changeSlaveToMaster(); mget(callback, keys); } catch(Exception e){ callback.handleErrors(e); } finally { pool.returnResource(jConnection); } return null; } public List<String> mget( JedisCallback<List<String>> callback, byte... keys){ Jedis jConnection = null; try{ jConnection = pool.getResource(); List<byte[]> res = jConnection.mget(keys); return callback.handleResult(res); } catch(JedisConnectionException jce){ changeSlaveToMaster(); mget(callback, keys); } catch(Exception e){ callback.handleErrors(e); } finally { pool.returnResource(jConnection); } return null; } private void changeSlaveToMaster() { if(pool.equals(slavePool)) return; pool = slavePool; Jedis jedis = pool.getResource(); try{ // Change the slave to master jedis.slaveofNoOne(); } finally{ pool.returnResource(jedis); } } public void flushAll(){ Jedis jConnection = pool.getResource(); try{ jConnection.flushAll(); } finally { pool.returnResource(jConnection); } } public <T> T lpush(JedisCallback<T> callback, String key, String value){ Jedis jConnection = null; try{ jConnection = pool.getResource(); Long l = jConnection.lpush(key, value); return callback.handleResult(l); } catch(JedisConnectionException jce){ changeSlaveToMaster(); lpush(callback, key, value); }catch (Exception e) { callback.handleErrors(e); } finally{ pool.returnResource(jConnection); } return null; } public <T> T pipeline(PipelineBlock pipelineBlock, JedisCallback<T> callback){ Jedis jedis = null; try{ jedis = pool.getResource(); List<Object> results = jedis.pipelined(pipelineBlock); return callback.handleResult(results); } catch(JedisConnectionException jce){ changeSlaveToMaster(); pipeline(pipelineBlock, callback); } catch (Exception e) { callback.handleErrors(e); } finally{ pool.returnResource(jedis); } return null; } public void setPool(JedisPool pool) { this.pool = pool; } public void setSlavePool(JedisPool slavePool) { this.slavePool = slavePool; } }
/* * 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 Project; import java.awt.Color; import java.awt.Font; import java.util.ArrayList; import javax.swing.JLabel; import javax.swing.JPanel; /** * * @author Burak */ public class CourseAnalys extends javax.swing.JFrame { public static ArrayList<String> arr; public static String id; /** * Creates new form NewJFrame * //@param first * //@param second * //@param third * @param a * @return */ public static ArrayList<String> array(ArrayList<String> a) { arr = a; System.out.println(arr); String lastIndex = arr.get(arr.size()-2); //arr.remove(lastIndex); System.out.println(arr); return arr; } public CourseAnalys() { init(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { kGradientPanel1 = new keeptoo.KGradientPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); setType(java.awt.Window.Type.POPUP); kGradientPanel1.setkEndColor(new java.awt.Color(144, 87, 81)); kGradientPanel1.setkGradientFocus(1100); kGradientPanel1.setkStartColor(new java.awt.Color(100, 104, 99)); kGradientPanel1.setLayout(null); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Here is the list of courses that "); kGradientPanel1.add(jLabel2); jLabel2.setBounds(120, 30, 320, 50); jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 24)); // NOI18N jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("You have take in total :"); kGradientPanel1.add(jLabel3); jLabel3.setBounds(240, 77, 250, 40); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Res/BackArrow.png"))); // NOI18N jLabel4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel4MouseClicked(evt); } }); kGradientPanel1.add(jLabel4); jLabel4.setBounds(30, 30, 40, 30); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kGradientPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 953, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kGradientPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE) ); setSize(new java.awt.Dimension(967, 617)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jLabel4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel4MouseClicked // TODO add your handling code here:7 Welcome.main(); this.dispose(); }//GEN-LAST:event_jLabel4MouseClicked /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ public void arr() { JLabel a; JPanel p; int count = 0; int x = 400; int y = 150; Color col = null; for(int i = 0; i<arr.size(); i++) { count++; } String[] myArray = new String[count]; for(int k = 0; k<arr.size(); k++) { myArray[k] = arr.get(k); } int index = 2; for(int j = 0; j< myArray.length; j++) { if(myArray[index].equals("fail")) { if(myArray[j].equals("fail") || myArray[j].equals("pass") || myArray[j].equals(id)) { } else { p = new JPanel(); p.setBounds(x, y, 250, 32); p.setBackground(new Color(204, 41, 0)); a = new JLabel(); a.setText(myArray[j]); a.setFont(new Font("Segoe UI", 0, 18)); a.setForeground(new Color(255, 255, 255)); a.setBounds(x, y, 250, 30); p.add(a); kGradientPanel1.add(p); y=y+35; } if(j == index) { if(index + 3 < count) { index = index + 3; } } } else if(myArray[index].equals("pass")) { if(myArray[j].equals("faill") || myArray[j].equals("pass") || myArray[j].equals(id)) { } else { p = new JPanel(); p.setBounds(x, y, 250, 32); p.setBackground(new Color(0, 153, 0)); a = new JLabel(); a.setText(myArray[j]); a.setFont(new Font("Segoe UI", 0, 18)); a.setForeground(new Color(255, 255, 255)); a.setBounds(x, y, 250, 30); p.add(a); kGradientPanel1.add(p); y=y+35; } if(j == index) { if(index + 3 < count) { index = index + 3; } } } } } @SuppressWarnings(value = "unchecked") public void init() { kGradientPanel1 = new keeptoo.KGradientPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); kGradientPanel1.setkEndColor(new java.awt.Color(144, 87, 81)); kGradientPanel1.setkGradientFocus(1100); kGradientPanel1.setkStartColor(new java.awt.Color(100, 104, 99)); kGradientPanel1.setLayout(null); jLabel2.setFont(new java.awt.Font("Segoe UI", 0, 24)); jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("Here is the list of courses that "); kGradientPanel1.add(jLabel2); jLabel2.setBounds(120, 30, 320, 50); jLabel3.setFont(new java.awt.Font("Segoe UI", 0, 24)); jLabel3.setForeground(new java.awt.Color(255, 255, 255)); jLabel3.setText("You have took in total :"); kGradientPanel1.add(jLabel3); jLabel3.setBounds(200, 75, 250, 40); jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Res/BackArrow.png"))); // NOI18N jLabel4.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { jLabel4MouseClicked(evt); } }); kGradientPanel1.add(jLabel4); jLabel4.setBounds(30, 30, 40, 30); arr(); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kGradientPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 953, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(kGradientPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE) ); setSize(new java.awt.Dimension(967, 617)); setLocationRelativeTo(null); } // </editor-fold> /** */ public static void main() { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CourseAnalys.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new CourseAnalys().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; public keeptoo.KGradientPanel kGradientPanel1; // End of variables declaration//GEN-END:variables }
///* //package com.tutorial.batch.job; // //import lombok.NoArgsConstructor; //import lombok.RequiredArgsConstructor; //import lombok.extern.slf4j.Slf4j; //import org.springframework.batch.core.ExitStatus; //import org.springframework.batch.core.Job; //import org.springframework.batch.core.Step; //import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; //import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; //import org.springframework.batch.repeat.RepeatStatus; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; // //@Slf4j //@Configuration //@RequiredArgsConstructor //public class StepNextConditionalJobConfig { // // private final JobBuilderFactory jobBuilderFactory; // private final StepBuilderFactory stepBuilderFactory; // // @Bean // public Job stepNextConditionalJob(){ // return jobBuilderFactory.get("stepNextConditionalJob") // .start(conditionalStep1()) // .on("FAILED") // .to(conditionalStep3()) // .on("*") // .end() // .from(conditionalStep1()) // .on("*") // .to(conditionalStep2()) // .next(conditionalStep3()) // .on("*") // .end() // .end() // .build(); // } // // @Bean // public Step conditionalStep1(){ // return stepBuilderFactory.get("step1") // .tasklet((contribution, chunkContext)->{ // log.info(">>>>>>>>>>>> This is stepNextConditionalJob Step1"); // // */ ///* 해당 Step을 FAILED로 지정하는 방법 *//* // // //contribution.setExitStatus(ExitStatus.FAILED); // return RepeatStatus.FINISHED; // }) // .build(); // } // // @Bean // public Step conditionalStep2(){ // return stepBuilderFactory.get("conditionalStep2") // .tasklet((contribution,chunkContext)->{ // log.info(">>>>>>>>>>>> This is stepNextConditionalJob Step2"); // return RepeatStatus.FINISHED; // }) // .build(); // } // // @Bean // public Step conditionalStep3(){ // return stepBuilderFactory.get("conditionalJobStep3") // .tasklet((contribution, chunkContext) -> { // log.info(">>>>>>>>>>>> This is stepNextConditionalJob Step3"); // return RepeatStatus.FINISHED; // }) // .build(); // } //} //*/
package dyvilx.tools.gradle; import org.gradle.api.file.FileTree; import org.gradle.api.file.RelativePath; import org.gradle.api.file.SourceDirectorySet; import org.gradle.api.tasks.*; import java.io.File; import java.util.ArrayList; import java.util.List; public class GenSrcRunTask extends JavaExec { protected SourceDirectorySet sourceDirs; protected File outputDir; public GenSrcRunTask() { this.setMain("dyvilx.tools.gensrc.Runner"); this.getArgumentProviders().add(this::collectArgs); } private List<String> collectArgs() { final List<String> args = new ArrayList<>(); for (final File sourceDir : this.getSourceDirs().getSrcDirs()) { args.add("--source-dir=" + sourceDir); } args.add("--output-dir=" + this.getOutputDir()); final FileTree files = this.getAllSource(); final FileTree templates = files.matching(it -> it.include("**/*.dgt")); templates.visit(details -> { if (!details.isDirectory()) { args.add(templateName(details.getRelativePath())); } }); final FileTree specs = files.matching(it -> it.include("**/*.dgs")); specs.visit(details -> { if (!details.isDirectory()) { args.add(details.getRelativePath().getPathString()); } }); return args; } private static String templateName(RelativePath relativePath) { // org/example/Foo.dyv.dgt -> org.example.Foo_dyv final String[] segments = relativePath.getSegments(); final int last = segments.length - 1; final StringBuilder templateName = new StringBuilder(); for (int i = 0; i < last; i++) { templateName.append(segments[i]).append('.'); } templateName.append(segments[last].replace('.', '_'), 0, segments[last].length() - 4); return templateName.toString(); } private FileTree getAllSource() { return this.getProject().files(this.getSourceDirs().getSrcDirs()).getAsFileTree(); } @InputFiles @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE) public FileTree getSource() { return this.getAllSource().matching(it -> it.include("**/*.dgt", "**/*.dgs")); } @Internal public SourceDirectorySet getSourceDirs() { return sourceDirs; } public void setSourceDirs(SourceDirectorySet sourceDirs) { this.sourceDirs = sourceDirs; } @OutputDirectory public File getOutputDir() { return outputDir; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } }
package test.main; /* * 3. 비교 연산자 테스트 * - 비교 연산의 결과는 boolean type 이다. * ==, !=, >, >=, <, <= */ public class MainClass03 { public static void main(String[] args) { boolean result1=10==10;//true boolean result2=10!=10;//false boolean result3=10>100;//false boolean result4=10>=10;//true boolean result5=10<100;//true boolean result6=10<=10;//true // String type 변수에 null 대입하기 // null 은 참조데이터 type 이 담길수 있는 빈 공간을 만들때 사용한다. String name=null; //어떤 값이 null 인지 아닌지 비교 가능하다 boolean result7=name==null; //true boolean result8=name!=null; //false } }
package assemAssist.model.facade; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import assemAssist.TestInit; import assemAssist.model.company.CarManufacturingCompany; /** * A test class for the Facade class. * * @author SWOP Group 3 * @version 3.0 */ public class FacadeTest { private Facade facade; private CarManufacturingCompany company; @Before public void initialise() { company = TestInit.getCarManufacturingCompany(); facade = new Facade(company); } @Test(expected = IllegalArgumentException.class) public void constructorInvalid() { new Facade(null); } @Test public void getCompany() { assertEquals(company, facade.getCompany()); } }
package edu.buet.cse.spring.ch07.v2.service; import java.util.List; import edu.buet.cse.spring.ch07.v2.model.Message; import edu.buet.cse.spring.ch07.v2.model.User; public interface ChirperService { User getUser(Long id); User getUser(String username); Message getMessage(Long id); List<Message> getMessages(int count); List<Message> getMessagesFromUser(Long userId, int count); boolean addUser(User user); boolean addMessage(Message message); }
/** * @author yuanwq, date: 2017年7月23日 */ package com.xwechat.api.jssdk; import com.xwechat.api.Apis; import com.xwechat.api.AuthorizedApi; import com.xwechat.api.jssdk.JsapiTicketApi.JsapiTicketResponse; import com.xwechat.core.IWechatResponse; import com.xwechat.enums.TicketType; /** * 获取jsapi ticket接口,用于公众号的各种接口,比如分享等 * * @Note 公众平台 * @url https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi * @see https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183 * @author yuanwq */ public class JsapiTicketApi extends AuthorizedApi<JsapiTicketResponse> { public JsapiTicketApi() { super(Apis.JSAPI_TICKET); this.urlBuilder.setQueryParameter("type", TicketType.JSAPI.asParameter()); } @Override public Class<JsapiTicketResponse> getResponseClass() { return JsapiTicketResponse.class; } public static class JsapiTicketResponse implements IWechatResponse { private int errcode; private String errmsg; private String ticket; private int expiresIn; public int getErrcode() { return errcode; } public void setErrcode(int errcode) { this.errcode = errcode; } public String getErrmsg() { return errmsg; } public void setErrmsg(String errmsg) { this.errmsg = errmsg; } public String getTicket() { return ticket; } public void setTicket(String ticket) { this.ticket = ticket; } public int getExpiresIn() { return expiresIn; } public void setExpiresIn(int expiresIn) { this.expiresIn = expiresIn; } } }
package net.minecraft.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.tileentity.TileEntityEnderChest; public class InventoryEnderChest extends InventoryBasic { private TileEntityEnderChest associatedChest; public InventoryEnderChest() { super("container.enderchest", false, 27); } public void setChestTileEntity(TileEntityEnderChest chestTileEntity) { this.associatedChest = chestTileEntity; } public void loadInventoryFromNBT(NBTTagList p_70486_1_) { for (int i = 0; i < getSizeInventory(); i++) setInventorySlotContents(i, ItemStack.field_190927_a); for (int k = 0; k < p_70486_1_.tagCount(); k++) { NBTTagCompound nbttagcompound = p_70486_1_.getCompoundTagAt(k); int j = nbttagcompound.getByte("Slot") & 0xFF; if (j >= 0 && j < getSizeInventory()) setInventorySlotContents(j, new ItemStack(nbttagcompound)); } } public NBTTagList saveInventoryToNBT() { NBTTagList nbttaglist = new NBTTagList(); for (int i = 0; i < getSizeInventory(); i++) { ItemStack itemstack = getStackInSlot(i); if (!itemstack.func_190926_b()) { NBTTagCompound nbttagcompound = new NBTTagCompound(); nbttagcompound.setByte("Slot", (byte)i); itemstack.writeToNBT(nbttagcompound); nbttaglist.appendTag((NBTBase)nbttagcompound); } } return nbttaglist; } public boolean isUsableByPlayer(EntityPlayer player) { return (this.associatedChest != null && !this.associatedChest.canBeUsed(player)) ? false : super.isUsableByPlayer(player); } public void openInventory(EntityPlayer player) { if (this.associatedChest != null) this.associatedChest.openChest(); super.openInventory(player); } public void closeInventory(EntityPlayer player) { if (this.associatedChest != null) this.associatedChest.closeChest(); super.closeInventory(player); this.associatedChest = null; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\inventory\InventoryEnderChest.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package me.xuyupeng.share; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * 字节码读取示例 * * @author : xuyupeng * @date 2020/3/21 13:32 */ public class BcReadDemo { public static void main(String[] args) throws IOException { //System.out.println(System.getProperty("user.dir")); //System.out.println(BcReadDemo.class.getResource("").getPath() + "DemoClazz.class"); //System.out.println(BcReadDemo.class.getResource("").getPath() + "DemoClazz.class"); InputStream inputStream = null; { try { inputStream = new FileInputStream(BcReadDemo.class.getResource("").getPath() + "/DemoClazz.class"); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (null != inputStream) { BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream); int tempByte; int i = 16; while (-1 != (tempByte = bufferedInputStream.read())) { System.out.printf("%02x ", tempByte); if (--i == 0) { System.out.println(""); i = 16; } } } } }
/* * Copyright 2013 Cloudera. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kitesdk.data.spi; import org.kitesdk.data.DatasetDescriptor; import org.kitesdk.data.DatasetRepository; /** * A common DatasetRepository base class to simplify implementation. * * Implementers can use this class to maintain compatibility with old API calls, * without needing to implement deprecated methods. It also includes backwards- * compatible implementations of current API methods so that implementers don't * need to implement deprecated methods. */ public abstract class AbstractDatasetRepository implements DatasetRepository { public static final String REPOSITORY_URI_PROPERTY_NAME = "repositoryUri"; protected DatasetDescriptor addRepositoryUri(DatasetDescriptor descriptor) { if (getUri() == null) { return descriptor; } return new DatasetDescriptor.Builder(descriptor) .property(REPOSITORY_URI_PROPERTY_NAME, getUri().toString()) .build(); } }
package com.example.administrator.recyclerviewdemo; import android.app.Activity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.administrator.rxjavademo.R; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Administrator on 2017/8/30. */ public class RecyClerViewDemo extends Activity { @BindView(R.id.recycle_view) RecyclerView recycleView; @BindView(R.id.activity_recyclerview) LinearLayout activityRecyclerview; private ArrayList<String> mDatas; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recyclerview); ButterKnife.bind(this); initData(); //设置布局管理器 recycleView.setLayoutManager(new LinearLayoutManager(this)); recycleView.setAdapter(new HomeAdapter()); } private void initData() { mDatas = new ArrayList<>(); for (int i = 'A'; i < 'z'; i++) { mDatas.add("" + (char) i); } } private class HomeAdapter extends RecyclerView.Adapter<RecyClerViewDemo.MyViewHolder> { @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(RecyClerViewDemo.this).inflate(R.layout.item_recyclerview,parent,false)); return myViewHolder; } @Override public void onBindViewHolder(MyViewHolder holder, int position) { holder.mTextView.setText(mDatas.get(position)); Glide.with(RecyClerViewDemo.this).load(Images.imageUrls[position]).placeholder(R.drawable.splash).error(R.drawable.error).into(holder.mImageView); } @Override public int getItemCount() { return mDatas.size(); } } private class MyViewHolder extends RecyclerView.ViewHolder{ private final ImageView mImageView; private final TextView mTextView; public MyViewHolder(View itemView) { super(itemView); mImageView = (ImageView) itemView.findViewById(R.id.image_recycler); mTextView = (TextView) itemView.findViewById(R.id.text_view_recycler); } } }
package com.fleet.async.controller; import org.springframework.scheduling.annotation.Async; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class TestController { @Resource private AsyncTask asyncTask; @RequestMapping("start") public void start() throws Exception { System.out.println("任务开始"); asyncTask.doAsync(); System.out.println("任务结束"); } @RequestMapping("start1") public void start1() throws Exception { System.out.println("任务开始"); doAsync(); System.out.println("任务结束"); } /** * @Async 异步方法不要和同步调用方法写在同一个类中,否则注解时效 */ @Async public void doAsync() throws InterruptedException { System.out.println("执行任务开始"); Thread.sleep(1000 * 10); System.out.println("执行任务结束"); } }
package com; import org.junit.Assert; import org.junit.jupiter.api.Test; import java.util.LinkedList; import java.util.Queue; public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode() { } public TreeNode(int val) { this.val = val; } public TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } public static String printPreOrder(TreeNode node) { System.out.print("PreOrder: "); String res = preorder(node); System.out.println(res); return res; } public static String printInOrder(TreeNode node) { System.out.print("InOrder: "); String res = inorder(node); System.out.println(res); return res; } public static String preorder(TreeNode node) { if (node == null) return ""; String res = ""; res += (node.val + " "); res += preorder(node.left); res += preorder(node.right); return res; } public static String inorder(TreeNode node) { if (node == null) return ""; String res = ""; res += inorder(node.left); res += (node.val + " "); res += inorder(node.right); return res; } public static TreeNode buildTree(Integer[] nums) { if (nums == null || nums.length == 0) { throw new RuntimeException("Error Input"); } TreeNode root = new TreeNode(nums[0]); Queue<TreeNode> queue = new LinkedList<TreeNode>() {{ add(root); }}; int i = 1, len = nums.length; while (!queue.isEmpty() && i < len) { TreeNode poll = queue.poll(); if (i < len && nums[i] != null) { poll.left = new TreeNode(nums[i]); queue.add(poll.left); } i++; if (i < len && nums[i] != null) { poll.right = new TreeNode(nums[i]); queue.add(poll.right); } i++; } return root; } public static void main(String[] args) { TreeNode root = TreeNode.buildTree(new Integer[]{1, 2, 3, null, 5, 6, 7}); Assert.assertTrue(TreeNode.inorder(root).contains("2 5 1 6 3 7")); TreeNode.printPreOrder(root); Assert.assertTrue(TreeNode.preorder(root).contains("1 2 5 3 6 7")); } }
package com.cognizant.controller; //import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; 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.RestController; import org.springframework.web.bind.annotation.SessionAttributes; import com.cognizant.truyum.model.MenuItem; import com.cognizant.truyum.service.MenuItemServiceImpl; import lombok.extern.slf4j.Slf4j; /** * MenuItemController class used to handle request from menu items pages * * @see MenuItemService * @author Danish */ @SessionAttributes("userId") @RestController @Slf4j public class MenuItemController { @Autowired MenuItemServiceImpl service; /** * showMenuItemListAdmin method shows items for admin * * @param model * @return */ @GetMapping("/show-menu-list-admin") public List<MenuItem> showMenuItemListAdmin() /* throws SystemException */ { log.info("showMenuItemListAdmin -Start"); List<MenuItem> items = service.getMenuItemListAdmin(); log.debug("AdminList:{}", items); log.info("showMenuItemListAdmin -End"); return items; } /** * showEditMenuItem method handles get request and display page to edit menu * items for admin * * @param menuItemId * @param model * @return */ @GetMapping("/show-edit-menu-item/{id}") public MenuItem showEditMenuItem(@PathVariable("id") long id) { log.info("showEditMenuItem -Start"); MenuItem item = service.getMenuItem(id); System.out.println(item); log.debug("Item :{}", item); log.info("showEditMenuItem -End"); return item; } /** * editMenuItem mehod handles post request from edit menu page it edit the item * in database * * @param menuItem * @param bindingResult * @return */ @PutMapping("/edit-menu-item") public String editMenuItem(@RequestBody @Valid MenuItem menuItem) { log.info("showEditMenuItemPost -Start"); service.editMenuItem(menuItem); log.info("showEditMenuItemPost -End"); return "editied scuuess"; } /** * showMenuItemListCustomer method display menu items for customer * * @param model * @return */ @GetMapping("/show-menu-list-customer") public List<MenuItem> showMenuItemListCustomer() { log.info("showMenuItemListCustomer -Start"); List<MenuItem> item = service.getMenuItemListCustomer(); //model.addAttribute("itemList", item); log.info("showMenuItemListCustomer -End"); return item; } /** * populateCategory method used to populate the * category in edit menu jsp * * * @return * **/ @ModelAttribute("categoryList") public List<String> populateCategory() { log.info("populateCategory -Start"); List<String> categoryList = new ArrayList<String>(); categoryList.add("Starters"); categoryList.add("Main Course"); categoryList.add("Dessert"); categoryList.add("Drinks"); log.info("populateCategory -End"); return categoryList; } }
/* * Copyright 2005-2010 the original author or authors. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sdloader.util; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.UnsupportedCharsetException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Locale; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Web用ユーティリティ * * @author c9katayama */ @SuppressWarnings("unchecked") public class WebUtil { /** * ヘッダー日付フォーマット */ private static final DateFormat HEADER_DATE_FORMAT = new SimpleDateFormat( "E, d MMM yyyy HH:mm:ss 'GMT'", Locale.UK); /** * クッキー日付フォーマット */ private static final DateFormat COOKIE_DATE_FORMAT = new SimpleDateFormat( "E, d-MMM-yyyy HH:mm:ss 'GMT'", Locale.UK); private WebUtil() { super(); } /** * ContentType(text/html;charse=UTF-8など)からUTF-8部分を取り出します。 * * @param value * @return */ public static String parseCharsetFromContentType(String value) { final String sepString = "charset="; int sep = value.indexOf(sepString); if (sep != -1) { sep += sepString.length(); int endIndex = value.length(); int scIndex = value.indexOf(";", sep); if (scIndex != -1) endIndex = scIndex; String charSet = value.substring(sep, endIndex); return charSet.trim(); } else { return null; } } /** * サポートされているエンコードかどうか サポートされていない場合、UnsupportedEncodingExceptionが発生します。 * * @param encoding * @return * @throws UnsupportedEncodingException */ public static void checkSupportedEndcoding(String encoding) throws UnsupportedEncodingException { if (encoding == null) throw new UnsupportedCharsetException("Charset is null."); URLDecoder.decode("", encoding); } /** * ヘッダー用の日付文字を、ミリ秒フォーマットに変換します。 * * @param date * @return * @throws ParseException */ public static long parseHeaderDate(String date) throws ParseException { synchronized (HEADER_DATE_FORMAT) { return HEADER_DATE_FORMAT.parse(date).getTime(); } } /** * クッキー用の日付文字を、ミリ秒フォーマットに変換します。 * * @param date * @return * @throws ParseException */ public static long parseCookieDate(String date) throws ParseException { synchronized (COOKIE_DATE_FORMAT) { return COOKIE_DATE_FORMAT.parse(date).getTime(); } } /** * 日付をヘッダー用の日付文字列にフォーマットします。 * * @param date * @return */ public static String formatHeaderDate(Date date) { synchronized (HEADER_DATE_FORMAT) { return HEADER_DATE_FORMAT.format(date); } } /** * 日付をクッキー用の日付文字列にフォーマットします。 * * @param date * @return * @throws ParseException */ public static String formatCookieDate(Date date) { synchronized (COOKIE_DATE_FORMAT) { return COOKIE_DATE_FORMAT.format(date); } } public static URL[] createClassPaths(String targetDir, FileFilter fileFilter, boolean recursive) { return createClassPaths(new File(targetDir), fileFilter, recursive); } /** * 対象ディレクトリ中のファイルへのURLを生成します。 * * @param targetDir * @param fileFilter * @param recursive * 再帰的に追加するかどうか * @return * @throws MalformedURLException */ public static URL[] createClassPaths(File targetDir, FileFilter fileFilter, boolean recursive) { if (!targetDir.exists()) return null; List<URL> urlList = CollectionsUtil.newArrayList(); File[] libs = targetDir.listFiles(fileFilter); if (libs != null) { for (int i = 0; i < libs.length; i++) { urlList.add(PathUtil.file2URL(libs[i])); } } if (recursive) { File[] dirs = targetDir.listFiles(); if (dirs != null) { for (int i = 0; i < dirs.length; i++) { if (dirs[i].isDirectory()) { URL[] urls = createClassPaths( dirs[i].getAbsolutePath(), fileFilter, recursive); if (urls != null) { for (int j = 0; j < urls.length; j++) urlList.add(urls[j]); } } } } } return (URL[]) urlList.toArray(new URL[] {}); } /** * リクエストURI中のコンテキストパス以外の部分を返します。 resoucePath = servletpath + pathinfo * ただし、requestURIが"/"の場合(ルートアプリケーション)のみ、"/"を返します。 * * @param requestURI * @return resourcePath */ public static String getResourcePath(String contextPath, String requestURI) { if (requestURI == null) return null; if (requestURI.equals("/")) { return "/"; } if (contextPath.equals(requestURI)) { return null; } else { String servletPath = requestURI.substring(contextPath.length(), requestURI.length()); return servletPath; } } /** * servletPath+PathInfoのパスから、サーブレットパスの部分を返します。 resoucePath = servletpath + * pathinfo * * @param requestURI * @return resourcePath */ public static String getServletPath(String pattern, String resourcePath) { if (resourcePath == null) return null; int type = matchPattern(pattern, resourcePath); switch (type) { case PATTERN_DEFAULT_MATCH: return ""; case PATTERN_EXT_MATCH: case PATTERN_EXACT_MATCH: return resourcePath; case PATTERN_PATH_MATCH: return pattern.substring(0, pattern.length() - "/*".length()); default: throw new RuntimeException("PATTERN_NOMATCH pattern=" + pattern + " path=" + resourcePath); } } /** * リクエストURI中のコンテキストパス以外の部分を返します. resoucePath = servletpath + pathinfo * * @param requestURI * @return resourcePath */ public static String getPathInfo(String pattern, String resourcePath) { if (resourcePath == null) return null; int type = matchPattern(pattern, resourcePath); switch (type) { case PATTERN_DEFAULT_MATCH: return resourcePath; case PATTERN_EXT_MATCH: case PATTERN_EXACT_MATCH: return null; case PATTERN_PATH_MATCH: return resourcePath.substring(pattern.length() - "/*".length()); default: throw new RuntimeException("PATTERN_NOMATCH pattern=" + pattern + " path=" + resourcePath); } } /** * パターンマッチなし */ public static final int PATTERN_NOMATCH = 0; /** * デフォルトパターン(/*)でマッチ */ public static final int PATTERN_DEFAULT_MATCH = 1; /** * 拡張子でマッチ */ public static final int PATTERN_EXT_MATCH = 2; /** * パスでマッチ */ public static final int PATTERN_PATH_MATCH = 3; /** * 完全マッチ */ public static final int PATTERN_EXACT_MATCH = 4; /** * パスパターンと パスのマッチングを行います。 * * @param pattern * @param path * @return PATTERN_NOMATCH PATTERN_DEFAULT_MATCH PATTERN_EXT_MATCH * PATTERN_PATH_MATCH PATTERN_EXACT_MATCH */ public static int matchPattern(String pattern, String path) { if (pattern == null || path == null) return PATTERN_NOMATCH; if (pattern.equals(path)) return PATTERN_EXACT_MATCH; if (pattern.equals("/*")) return PATTERN_DEFAULT_MATCH; if (pattern.endsWith("/*")) { if (pattern.regionMatches(0, path, 0, pattern.length() - 2)) { if (path.length() == (pattern.length() - 2)) return PATTERN_PATH_MATCH; else if (path.charAt(pattern.length() - 2) == '/') return PATTERN_PATH_MATCH; } return PATTERN_NOMATCH; } if (pattern.startsWith("*.")) { int resourceDot = path.lastIndexOf("."); if (resourceDot >= 0) { String resourceExt = path.substring(resourceDot, path.length()); int patternDot = pattern.indexOf("."); String patternExt = pattern.substring(patternDot, pattern .length()); if (resourceExt.equals(patternExt)) return PATTERN_EXT_MATCH; } } return PATTERN_NOMATCH; } /** * Query部分を取り除きます * * @param requestURI * @return */ public static String stripQueryPart(String requestURI) { int queryIndex = requestURI.indexOf("?"); if (queryIndex > 0) { return requestURI.substring(0, queryIndex); } else { return requestURI; } } /** * Queary部分を取得します。ない場合、nullを返します。 * * @param requestURI * @return */ public static String getQueryPart(String requestURI) { int queryIndex = requestURI.indexOf("?"); if (queryIndex > 0) { return requestURI.substring(queryIndex + 1, requestURI.length()); } else { return null; } } /** * RequestURLを構築します。 * * @param scheme * @param host * @param port * @param requestURI * @return */ public static StringBuffer buildRequestURL(String scheme, String host, int port, String requestURI) { String portString; if (port == 80 && scheme.equals("http")) { portString = ""; } else if (port == 443 && scheme.equals("https")) { portString = ""; } else if (host.indexOf(":") != -1) { portString = ""; } else { portString = ":" + port; } requestURI = stripQueryPart(requestURI); return new StringBuffer(scheme + "://" + host + portString + requestURI); } /** * RequestURLを構築します。 host部分にポート指定が無い場合、schemeからポートを 設定します。 * * @param scheme * @param host * @param port * @param requestURI * @return */ public static StringBuffer buildRequestURL(String scheme, String host, String requestURI) { int portSep = host.indexOf(":"); String portString; if (portSep != -1) { portString = host.substring(portSep + 1); host = host.substring(0, portSep); } else { if (scheme.equals("http")) portString = ""; else if (scheme.equals("https")) portString = ""; else throw new RuntimeException("schema:" + scheme + " not support."); } return buildRequestURL(scheme, host, Integer.parseInt(portString), requestURI); } public static void writeNotFoundPage(HttpServletResponse res) throws IOException { res.setStatus(HttpServletResponse.SC_NOT_FOUND); res.setContentType("text/html;charset=UTF-8"); PrintWriter writer = res.getWriter(); writer.println("<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"); writer.println("<html><head>"); writer.println("<title>404 Not Found</title>"); writer.println("<head><body>"); writer.println("<h1>Not Found</h1>"); writer .println("<p>The requested URL resource was not found on this SDLoader.</p>"); writer.println("<body></html>"); writer.flush(); } public static void writeInternalServerErrorPage(HttpServletRequest req, HttpServletResponse res, Throwable t) throws IOException { res.reset(); res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); res.setContentType("text/html;charset=UTF-8"); PrintWriter writer = res.getWriter(); writer.println("<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">"); writer.println("<html><head>"); writer.println("<title>500 Internal Server Error</title>"); writer.println(getFoldingJS()); writer.println("<head><body>"); writer.println("<h1>500 Internal Server Error</h1>"); writer.println(getFoldingContents("RequestHeader", getRequestHeaderContents(req), false)); writer.println(getFoldingContents("RequestParameter", getRequestParameterContents(req), false)); writer.println(getFoldingContents("RequestAttribute", getRequestAttrituteContents(req), false)); writer.println(getFoldingContents("Session", getSessionContents(req), false)); writer.println(getFoldingContents("Cookie", getCookieContents(req), false)); if (t != null) { StringWriter exceptionWriter = new StringWriter(); PrintWriter exceptionPrintWriter = new PrintWriter(exceptionWriter); exceptionPrintWriter.println("<pre style='color:#FF0000'>"); t.printStackTrace(exceptionPrintWriter); exceptionPrintWriter.println("</pre>"); exceptionPrintWriter.flush(); writer.println(getFoldingContents("StackTrace", exceptionWriter .toString(), true)); } writer.println("</body></html>"); writer.flush(); } private static String getRequestHeaderContents(HttpServletRequest req) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); Enumeration<String> names = req.getHeaderNames(); if (!names.hasMoreElements()) { return "No Header."; } printWriter.write("<table width='100%'>"); while (names.hasMoreElements()) { String key = names.nextElement(); Enumeration<String> values = req.getHeaders(key); if (values != null) { while (values.hasMoreElements()) { printWriter .write("<tr style='background-color:#DDDDDD;'><td style='text-align:right;white-space:nowrap;'>" + key + "</td><td>" + values.nextElement() + "</td></tr>"); } } } printWriter.write("</table>"); printWriter.close(); return stringWriter.toString(); } private static String getRequestParameterContents(HttpServletRequest req) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); Enumeration<String> names = req.getParameterNames(); if (!names.hasMoreElements()) { return "No Paramter."; } printWriter.write("<table width='100%'>"); while (names.hasMoreElements()) { String key = names.nextElement(); String[] values = req.getParameterValues(key); if (values != null) { for (int i = 0; i < values.length; i++) { printWriter .write("<tr style='background-color:#DDDDDD;'><td style='text-align:right;white-space:nowrap;'>" + key + "</td><td>" + values[i] + "</td></tr>"); } } } printWriter.write("</table>"); printWriter.close(); return stringWriter.toString(); } private static String getRequestAttrituteContents(HttpServletRequest req) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); Enumeration<String> names = req.getAttributeNames(); if (!names.hasMoreElements()) { return "No Attribute."; } printWriter.write("<table width='100%'>"); while (names.hasMoreElements()) { String key = names.nextElement(); Object value = req.getAttribute(key); printWriter .write("<tr style='background-color:#DDDDDD;'><td style='text-align:right;white-space:nowrap;'>" + key + "</td><td>" + value.toString() + "</td></tr>"); } printWriter.write("</table>"); printWriter.close(); return stringWriter.toString(); } private static String getSessionContents(HttpServletRequest req) { HttpSession session = req.getSession(false); if (session == null) { return "No Session."; } Enumeration<String> names = session.getAttributeNames(); if (!names.hasMoreElements()) { return "No Session."; } StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.write("<table width='100%'>"); while (names.hasMoreElements()) { String key = names.nextElement(); Object value = session.getAttribute(key); printWriter .write("<tr style='background-color:#DDDDDD;'><td style='text-align:right;white-space:nowrap;'>" + key + "</td><td>" + value.toString() + "</td></tr>"); } printWriter.write("</table>"); printWriter.close(); return stringWriter.toString(); } private static String getCookieContents(HttpServletRequest req) { Cookie[] cookies = req.getCookies(); if (cookies == null) { return "No Cookie."; } StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.write("<table width='100%'>"); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String valueText = "name=" + cookie.getName(); valueText += " value=" + cookie.getValue(); if (cookie.getPath() != null) { valueText += " path=" + cookie.getPath(); } if (cookie.getDomain() != null) { valueText += " domain=" + cookie.getDomain(); } if (cookie.getMaxAge() != 0) { valueText += " maxAge=" + cookie.getMaxAge(); } if (cookie.getComment() != null) { valueText += " comment=" + cookie.getComment(); } printWriter .write("<tr style='background-color:#DDDDDD;'><td style='white-space:nowrap;'>" + valueText + "</td></tr>"); } printWriter.write("</table>"); printWriter.close(); return stringWriter.toString(); } private static String getFoldingContents(String name, String contents, boolean open) { String contentsStype = "style='display=" + (open ? "block" : "none") + ";padding-left:6px'"; return "<div id='title" + name + "' onclick='folding(" + "\"contents" + name + "\"" + ");return false;' style='padding-left:6px;padding-top:2px;paddin-bottom2px;margin:4px;color:white;background-color:black'>" + name + "</div>" + "<div id='contents" + name + "' " + contentsStype + ">" + contents + "</div>"; } private static String getFoldingJS() { return "<script type='text/javascript'>\r\n" + "<!--\r\n" + "function folding(targetId){\r\n" + " var target = document.getElementById(targetId);\r\n" + " if(target.style.display == 'none' ) {\r\n" + " target.style.display = 'block';\r\n" + " }else {\r\n" + " target.style.display = 'none';\r\n" + " }\r\n" + "}\r\n" + "//-->\r\n" + "</script>\r\n"; } }
package org.javamisc.csv; import org.junit.*; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.BufferedReader; import java.util.Set; import java.util.HashSet; import java.util.Random; public class CsvTest { String xyData; private static int xyFunction(int x) { return (2 * x + 3); } private static String csvTextFunction(int i) { String text = "this is just some test"; if (i % 4 == 1) { text = "\"this is quoted text\""; } else if (i % 4 == 2) { text = "\"this has \"\"escaped\"\" quotes\""; } else if (i % 4 == 3) { text = "this \"a\"ppears\"\" to have an escaped quote"; } return (text); } private static String plainTextFunction(int i) { String text = "this is just some test"; if (i % 4 == 1) { text = "this is quoted text"; } else if (i % 4 == 2) { text = "this has \"escaped\" quotes"; } else if (i % 4 == 3) { text = "this appears to have an escaped quote"; } return (text); } @Before public void setUp() { Random rng = new Random(4711); this.xyData = "i,x,y,s\n"; for (int i = 0; i < 10; i++) { int x = rng.nextInt(10); this.xyData += String.format("%d,%d,%d,%s\n", i, x, xyFunction(x), csvTextFunction(i)); } } private BufferedReader getXYReader() { return new BufferedReader(new StringReader(this.xyData)); } @Test public void testCsvTable() throws IOException { BufferedReader xyReader = this.getXYReader(); CsvTable t = new CsvTable(new CsvReader(xyReader)); Assert.assertEquals(t.getColumnNameList()[0], "i"); Assert.assertEquals(t.getColumnNameList()[1], "x"); Assert.assertEquals(t.getColumnNameList()[2], "y"); Assert.assertEquals(t.getColumnNameList()[3], "s"); while (t.next()) { Assert.assertEquals(t.getString(1), t.getString("x")); Assert.assertEquals(t.getString(2), t.getString("y")); int i = Integer.parseInt(t.getString("i")); int x = Integer.parseInt(t.getString("x")); int y = Integer.parseInt(t.getString("y")); String s = t.getString("s"); Assert.assertEquals(y, xyFunction(x)); Assert.assertEquals(s, plainTextFunction(i)); } } }
package Xmlparser; import java.io.*; import java.util.HashSet; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.SAXException; import weborder.*; import java.util.*; public class XMLParse { private static List ordersList; public XMLParse() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); ordersList = new ArrayList(); try { DocumentBuilder builder = factory.newDocumentBuilder(); try { Document doc = builder.parse("/Users/MacProHome/Desktop/RIO Stuff/orders.xml"); Element webOrder = doc.getDocumentElement(); NodeList webOrders = webOrder.getChildNodes(); if (webOrders != null && webOrders.getLength() > 0) { for (int j = 0; j < webOrders.getLength(); j++) { if (webOrders.item(j).getNodeType() == Node.ELEMENT_NODE) { Element orderNode = (Element) webOrders.item(j); if (orderNode.getNodeName().contains("order")) { String orderReference = orderNode.getElementsByTagName( "order_reference").item(0).getTextContent(); String courierName = orderNode.getElementsByTagName( "courier_name").item(0).getTextContent(); String billingTelephone = orderNode.getElementsByTagName( "billing_telephone").item(0).getTextContent(); String billingEmail = orderNode.getElementsByTagName( "billing_email").item(0).getTextContent(); String deliveryFullname = orderNode.getElementsByTagName( "delivery_fullname").item(0).getTextContent(); String deliveryAddress1 = orderNode.getElementsByTagName( "delivery_address1").item(0).getTextContent(); String deliveryAddress2 = orderNode.getElementsByTagName( "delivery_address2").item(0).getTextContent(); String deliveryTown = orderNode.getElementsByTagName( "delivery_town").item(0).getTextContent(); String deliveryCountryName = orderNode.getElementsByTagName( "delivery_country_name").item(0).getTextContent(); String deliveryPostcode = orderNode.getElementsByTagName( "delivery_postcode").item(0).getTextContent(); String delivery_telephone = orderNode.getElementsByTagName( "delivery_telephone").item(0).getTextContent(); Weborder aWeborder = new Weborder(orderReference, courierName, deliveryFullname, deliveryAddress1, deliveryAddress2, deliveryTown, deliveryPostcode, deliveryCountryName, billingEmail, billingTelephone, delivery_telephone); ordersList.add(aWeborder); System.out.println(aWeborder.getOrderDetails()); } } } } } catch (SAXException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } catch (ParserConfigurationException ex) { ex.printStackTrace(); } } public List getOrders() { return ordersList; } }
package controller.command.impl; import controller.command.Command; import controller.constants.FrontConstants; import controller.exception.ServiceLayerException; import controller.service.BusService; import controller.service.ServiceFactory; import controller.service.impl.ServiceFactoryImpl; import controller.constants.PathJSP; import domain.Bus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EditBusCommand implements Command { private ServiceFactory serviceFactory; private BusService busService; public EditBusCommand() { serviceFactory = ServiceFactoryImpl.getInstance(); busService = serviceFactory.getBusService(); } @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServiceLayerException { String idBus = request.getParameter(FrontConstants.BUS_ID); Bus bus = busService.getElementById(Integer.parseInt(idBus)); request.setAttribute(FrontConstants.BUS, bus); return PathJSP.ADD_EDIT_BUS_PAGE; } }
package EmptyClass; import java.util.ArrayList; //this class save current student's information public class CurrentStudentInfo { public static ArrayList<String> studnetID = new ArrayList<String>(); }
package com.cnk.travelogix.v2.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.cnk.travelogix.supplier.mappings.city.model.SupplierCityModel; import com.cnk.travelogix.supplier.mappings.country.model.SupplierCountryModel; import com.cnk.travelogix.supplier.mappings.product.model.SupplierProductModel; import com.cnk.travelogix.supplier.mappings.room.model.SupplierRoomMappingModel; import com.cnk.travelogix.suppliers.events.SupplierCityMappingEvent; import com.cnk.travelogix.suppliers.events.SupplierCountryMappingEvent; import com.cnk.travelogix.suppliers.events.SupplierHotelCityMappingEvent; import com.cnk.travelogix.suppliers.events.SupplierProductMappingEvent; import de.hybris.platform.servicelayer.event.EventService; @Controller @RequestMapping(value = "/{baseSiteId}/testmappings") public class TestController extends BaseController { private static final Logger LOG = LoggerFactory.getLogger(TestController.class); @Resource(name = "eventService") private EventService eventService; @RequestMapping(value = "/supplierCity",method = RequestMethod.GET) @ResponseBody public void testSupplierCityMappings() { LOG.info("*******************Test Controller********************"); List<SupplierCityModel> supplierCityModels = new ArrayList<>(); SupplierCityModel cityModel = new SupplierCityModel(); cityModel.setActive(true); cityModel.setCountryCode("IN"); cityModel.setCountryName("India"); cityModel.setStateCode("Ka"); cityModel.setCode("mum"); SupplierCityModel cityModel1 = new SupplierCityModel(); cityModel1.setActive(true); cityModel1.setCountryCode("GE"); cityModel1.setCountryName("Germany"); cityModel1.setStateCode("TN"); cityModel1.setCode("abcd"); SupplierCityModel cityModel2 = new SupplierCityModel(); cityModel2.setActive(true); cityModel2.setCountryCode("US"); cityModel2.setCountryName("UnitedStates"); cityModel2.setStateCode("Ke"); cityModel2.setCode("xyz"); supplierCityModels.add(cityModel); supplierCityModels.add(cityModel1); for (SupplierCityModel supplierCityModel : supplierCityModels) { eventService.publishEvent(new SupplierCityMappingEvent(supplierCityModel)); } } @RequestMapping(value = "/supplierCountry",method = RequestMethod.GET) @ResponseBody public void testSupplierCountryMappings() { LOG.info("*******************Test Controller********************"); SupplierCountryModel supplierCountryModel = new SupplierCountryModel(); supplierCountryModel.setCode("country"); SupplierCountryModel supplierCountryModel1 = new SupplierCountryModel(); supplierCountryModel1.setCode("1234"); eventService.publishEvent(new SupplierCountryMappingEvent(supplierCountryModel1)); } @RequestMapping(value = "/supplierHotelCity",method = RequestMethod.GET) @ResponseBody public void testSupplierHotelCityMappings() { LOG.info("*******************Test Controller********************"); SupplierRoomMappingModel supplierRoomMappingModel = new SupplierRoomMappingModel(); supplierRoomMappingModel.setCode("hotelCity"); SupplierRoomMappingModel supplierRoomMappingModel1 = new SupplierRoomMappingModel(); supplierRoomMappingModel1.setCode("RoomCategoryMapping"); eventService.publishEvent(new SupplierHotelCityMappingEvent(supplierRoomMappingModel)); eventService.publishEvent(new SupplierHotelCityMappingEvent(supplierRoomMappingModel1)); } @RequestMapping(value = "/supplierProduct",method = RequestMethod.GET) @ResponseBody public void testSupplierProductMappings() { LOG.info("*******************Test Controller********************"); SupplierProductModel supplierProductModel = new SupplierProductModel(); supplierProductModel.setCode("product"); SupplierProductModel supplierProductModel1 = new SupplierProductModel(); supplierProductModel1.setCode("productMapping"); eventService.publishEvent(new SupplierProductMappingEvent(supplierProductModel)); eventService.publishEvent(new SupplierProductMappingEvent(supplierProductModel1)); } }
package corejava.io.files; import java.io.*; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.Map; import java.util.Scanner; /** * Created by xulz on 2017/3/12. */ public class IO { public static void main(String[] args) throws Exception { System.out.println(System.getProperty("user.dir")); System.out.println(File.separator); inout(); // readData(); charset(); // TODO: 读写二进制数据 } public static String tryWithResource() throws IOException{ // Java7+ : 实现Closeable接口支持try-with-resources, 自动释放资源 try(BufferedReader reader = new BufferedReader(new FileReader("abc.properties"))) { StringBuilder builder = new StringBuilder(); String line = null; while((line=reader.readLine()) != null){ builder.append(line); builder.append(String.format("%n")); } return builder.toString(); } // Java7+ : 捕获多个异常 // catch (IOException |RuntimeException ex){ // // } } public static void inout() throws Exception{ // stream data DataInputStream din = new DataInputStream( new BufferedInputStream( new FileInputStream("abc.properties") ) ); System.out.println(din.read()); // text InputStreamReader in = new InputStreamReader(new FileInputStream("abc.properties")); InputStreamReader stdin = new InputStreamReader(System.in); System.out.println(in.read()); // PrintWriter以文本格式写 PrintWriter pout = new PrintWriter("abc.properties"); PrintWriter out = new PrintWriter(new FileWriter("abc.properties"),true); String username = "Michael"; out.println(username); // Scanner以文本格式读 } public static void readData() throws Exception{ Scanner inFile = new Scanner(new FileInputStream("employee.dat"),"UTF-8"); String line = inFile.nextLine(); String[] tokens = line.split("\\|"); String name = tokens[0]; Double salary = Double.parseDouble(tokens[1]); } public static void charset(){ // 字符集 Charset cset = Charset.forName("UTF-8"); Map<String, Charset> charsets = Charset.availableCharsets(); for(String name:charsets.keySet()){ // System.out.println(name); } String str = "中文测试"; ByteBuffer buffer = cset.encode(str); byte[] bytes = buffer.array(); ByteBuffer bbuf = ByteBuffer.wrap(bytes); CharBuffer cbuf = cset.decode(bbuf); String strOut = cbuf.toString(); System.out.println(strOut); } }
public class Wlj{ private int id;//这是Id }
/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */ class Solution {    public int deepestLeavesSum(TreeNode root) {        Queue<TreeNode>            q = new LinkedList();        int count = 1;        q.add(root);        int tempCount = 0;        int cur = 0;        TreeNode temp;        while(!q.isEmpty())       { ​            cur = 0;            tempCount = 0;            while(count > 0)           {                temp = q.poll();                cur += temp.val;                if(temp.left != null)               {                    q.offer(temp.left);                    tempCount++;               }                if(temp.right != null)               {                    q.offer(temp.right);                    tempCount++;               }                count--;           }            count = tempCount;            if(tempCount == 0)           {                return cur;           }