file_id
stringlengths
5
9
content
stringlengths
86
32.8k
repo
stringlengths
9
63
path
stringlengths
7
161
token_length
int64
31
8.14k
original_comment
stringlengths
5
4.92k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
87
32.8k
excluded
bool
2 classes
63810_5
package top.mothership.cabbage.util.qq; import top.mothership.cabbage.constant.pattern.CQCodePattern; import top.mothership.cabbage.constant.pattern.RegularPattern; import top.mothership.cabbage.pojo.coolq.CqMsg; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; /** * 用于存放消息的循环队列 * @author QHS */ public class MsgQueue { private int start = 0; private int end = 0; private int len = 0; private int N=100; private CqMsg[] msgs = new CqMsg[N]; public MsgQueue(){} public MsgQueue(int N) { this.N=N; //2018-2-27 10:50:34构造方法居然没有重做一个数组…… msgs = new CqMsg[N]; } /** * 为了避免空指针异常,得new一个 */ private CqMsg msg = new CqMsg(); /** * 计算最近的消息构成复读的次数 * @return 最近一条消息构成复读的次数 */ public Integer countRepeat() { int count = 0; //根据循环队列情况不同进行遍历 if (start < end) { for (int i = 0; i < end; i++) { if (isThisRepeat(i)) { count++; } } } else { for (int i = end; i < msgs.length; i++) { if (isThisRepeat(i)) { count++; } } for (int i = 0; i < start - 1; i++) { if (isThisRepeat(i)) { count++; } } } return count; } /** * 向队列里增加消息,最近的消息会被写到成员变量里 * @param msg 要增加的消息 */ public void addMsg(CqMsg msg) { //循环队列的具体实现 //首先长度增加 len++; //如果0-100都有了消息,那就把start右移一个 if (len >= N) { len = N; start++; } //如果end已经达到数组最右端,就移到最左端 if (end == N) { end = 0; } if (start == N) { start = 0; } //把消息存到结束坐标里 msgs[end] = msg; //将这条消息存储到这个类的成员变量里 this.msg = msg; //结束坐标+1 end++; } /** * 把消息列表转为ArrayList……当时为啥要写这个方法来着? * 改成获取重复消息列表吧。 * @return 消息列表 */ public ArrayList<CqMsg> getRepeatList() { ArrayList<CqMsg> result = new ArrayList<>(); //根据循环队列情况不同进行遍历 if (start < end) { for (int i = 0; i < end; i++) { if (isThisRepeat(i)) { result.add(msgs[i]); } } } else { for (int i = end; i < msgs.length; i++) { if (isThisRepeat(i)) { result.add(msgs[i]); } } for (int i = 0; i < start - 1; i++) { if (isThisRepeat(i)) { result.add(msgs[i]); } } } return result; } /** * 根据QQ从循环队列中提取消息 * * @param QQ 给的QQ号 * @return 消息列表 */ public ArrayList<CqMsg> getMsgsByQQ(Long QQ) { ArrayList<CqMsg> result = new ArrayList<>(); if (start < end) { for (int i = 0; i < end; i++) { if (QQ.equals(msgs[i].getUserId())) { result.add(msgs[i]); } } } else { for (int i = end; i < msgs.length; i++) { if (QQ.equals(msgs[i].getUserId())) { result.add(msgs[i]); } } for (int i = 0; i < start - 1; i++) { if (QQ.equals(msgs[i].getUserId())) { result.add(msgs[i]); } } //目前会引发一个问题,当容器刚启动,这个群还没有消息的时候,调用这个会出NPE //但是我并不打算去用if,毕竟几乎不可能出现这个问题…… } return result; } /** * 判断最近的一条消息是否重复 * * @param i 循环队列里的坐标 * @return 该消息是否算作复读 */ private boolean isThisRepeat(int i) { Matcher cmdMatcher = RegularPattern.REG_CMD_REGEX.matcher(msg.getMessage()); if (cmdMatcher.find()) { //如果是命令,直接false return false; } Matcher singleImgMatcher = CQCodePattern.SINGLE_IMG.matcher(msg.getMessage()); if (singleImgMatcher.find()) { //如果是纯图片,直接false return false; } String msgFromArray = CQCodePattern.SINGLE_IMG.matcher( RegularPattern.REPEAT_FILTER_REGEX.matcher(msgs[i].getMessage()).replaceAll("")) .replaceAll(""); String msgFromGroup = CQCodePattern.SINGLE_IMG.matcher( RegularPattern.REPEAT_FILTER_REGEX.matcher(msg.getMessage()).replaceAll("")) .replaceAll(""); if ("".equals(msgFromArray)) { msgFromArray = msgs[i].getMessage(); } if("".equals(msgFromGroup)){ msgFromGroup = msg.getMessage(); } //目前的问题是:图片+符号会被判定复读, //流程是先去掉干扰,如果去干扰后是空串就恢复,然后判断去干扰后的消息是否相等+原消息是否是纯图片+原消息长度是否大于等于3 //应改为先去掉图片,是空串则 return msgFromArray.equals(msgFromGroup) && msg.getMessage().length() >= 3; } }
Mother-Ship/cabbageWeb
src/main/java/top/mothership/cabbage/util/qq/MsgQueue.java
1,500
/** * 向队列里增加消息,最近的消息会被写到成员变量里 * @param msg 要增加的消息 */
block_comment
zh-cn
package top.mothership.cabbage.util.qq; import top.mothership.cabbage.constant.pattern.CQCodePattern; import top.mothership.cabbage.constant.pattern.RegularPattern; import top.mothership.cabbage.pojo.coolq.CqMsg; import java.util.ArrayList; import java.util.Arrays; import java.util.regex.Matcher; /** * 用于存放消息的循环队列 * @author QHS */ public class MsgQueue { private int start = 0; private int end = 0; private int len = 0; private int N=100; private CqMsg[] msgs = new CqMsg[N]; public MsgQueue(){} public MsgQueue(int N) { this.N=N; //2018-2-27 10:50:34构造方法居然没有重做一个数组…… msgs = new CqMsg[N]; } /** * 为了避免空指针异常,得new一个 */ private CqMsg msg = new CqMsg(); /** * 计算最近的消息构成复读的次数 * @return 最近一条消息构成复读的次数 */ public Integer countRepeat() { int count = 0; //根据循环队列情况不同进行遍历 if (start < end) { for (int i = 0; i < end; i++) { if (isThisRepeat(i)) { count++; } } } else { for (int i = end; i < msgs.length; i++) { if (isThisRepeat(i)) { count++; } } for (int i = 0; i < start - 1; i++) { if (isThisRepeat(i)) { count++; } } } return count; } /** * 向队列 <SUF>*/ public void addMsg(CqMsg msg) { //循环队列的具体实现 //首先长度增加 len++; //如果0-100都有了消息,那就把start右移一个 if (len >= N) { len = N; start++; } //如果end已经达到数组最右端,就移到最左端 if (end == N) { end = 0; } if (start == N) { start = 0; } //把消息存到结束坐标里 msgs[end] = msg; //将这条消息存储到这个类的成员变量里 this.msg = msg; //结束坐标+1 end++; } /** * 把消息列表转为ArrayList……当时为啥要写这个方法来着? * 改成获取重复消息列表吧。 * @return 消息列表 */ public ArrayList<CqMsg> getRepeatList() { ArrayList<CqMsg> result = new ArrayList<>(); //根据循环队列情况不同进行遍历 if (start < end) { for (int i = 0; i < end; i++) { if (isThisRepeat(i)) { result.add(msgs[i]); } } } else { for (int i = end; i < msgs.length; i++) { if (isThisRepeat(i)) { result.add(msgs[i]); } } for (int i = 0; i < start - 1; i++) { if (isThisRepeat(i)) { result.add(msgs[i]); } } } return result; } /** * 根据QQ从循环队列中提取消息 * * @param QQ 给的QQ号 * @return 消息列表 */ public ArrayList<CqMsg> getMsgsByQQ(Long QQ) { ArrayList<CqMsg> result = new ArrayList<>(); if (start < end) { for (int i = 0; i < end; i++) { if (QQ.equals(msgs[i].getUserId())) { result.add(msgs[i]); } } } else { for (int i = end; i < msgs.length; i++) { if (QQ.equals(msgs[i].getUserId())) { result.add(msgs[i]); } } for (int i = 0; i < start - 1; i++) { if (QQ.equals(msgs[i].getUserId())) { result.add(msgs[i]); } } //目前会引发一个问题,当容器刚启动,这个群还没有消息的时候,调用这个会出NPE //但是我并不打算去用if,毕竟几乎不可能出现这个问题…… } return result; } /** * 判断最近的一条消息是否重复 * * @param i 循环队列里的坐标 * @return 该消息是否算作复读 */ private boolean isThisRepeat(int i) { Matcher cmdMatcher = RegularPattern.REG_CMD_REGEX.matcher(msg.getMessage()); if (cmdMatcher.find()) { //如果是命令,直接false return false; } Matcher singleImgMatcher = CQCodePattern.SINGLE_IMG.matcher(msg.getMessage()); if (singleImgMatcher.find()) { //如果是纯图片,直接false return false; } String msgFromArray = CQCodePattern.SINGLE_IMG.matcher( RegularPattern.REPEAT_FILTER_REGEX.matcher(msgs[i].getMessage()).replaceAll("")) .replaceAll(""); String msgFromGroup = CQCodePattern.SINGLE_IMG.matcher( RegularPattern.REPEAT_FILTER_REGEX.matcher(msg.getMessage()).replaceAll("")) .replaceAll(""); if ("".equals(msgFromArray)) { msgFromArray = msgs[i].getMessage(); } if("".equals(msgFromGroup)){ msgFromGroup = msg.getMessage(); } //目前的问题是:图片+符号会被判定复读, //流程是先去掉干扰,如果去干扰后是空串就恢复,然后判断去干扰后的消息是否相等+原消息是否是纯图片+原消息长度是否大于等于3 //应改为先去掉图片,是空串则 return msgFromArray.equals(msgFromGroup) && msg.getMessage().length() >= 3; } }
true
31877_14
package cn.chahuyun.session.manage; import cn.chahuyun.session.config.BlackListData; import cn.chahuyun.session.HuYanSession; import cn.chahuyun.session.controller.BlackHouseAction; import cn.chahuyun.session.controller.BlackListAction; import cn.chahuyun.session.data.ApplyClusterInfo; import cn.chahuyun.session.data.StaticData; import cn.chahuyun.session.dialogue.DialogueImpl; import cn.chahuyun.session.entity.*; import cn.chahuyun.session.enums.Mate; import cn.chahuyun.session.utils.DynamicMessageUtil; import cn.chahuyun.session.utils.HibernateUtil; import cn.chahuyun.session.utils.ScopeUtil; import cn.chahuyun.session.utils.ShareUtils; import kotlin.coroutines.EmptyCoroutineContext; import net.mamoe.mirai.Bot; import net.mamoe.mirai.contact.*; import net.mamoe.mirai.event.*; import net.mamoe.mirai.event.events.*; import net.mamoe.mirai.message.data.*; import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.JpaCriteriaQuery; import org.hibernate.query.criteria.JpaRoot; import xyz.cssxsh.mirai.hibernate.MiraiHibernateRecorder; import xyz.cssxsh.mirai.hibernate.entry.MessageRecord; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import static cn.chahuyun.session.HuYanSession.LOGGER; /** * GroupManager * 群管理类 * * @author Moyuyanli * @date 2022/8/15 12:52 */ public class GroupManager { public final static GroupManager INSTANCE = new GroupManager(); public final static Map<String, ApplyClusterInfo> map = new HashMap<>(); private static int doorNumber = 0; /** * 有人申请入群 * * @param event 群事件 * @author Moyuyanli * @date 2022/8/22 10:41 */ public static void userRequestGroup(MemberJoinRequestEvent event) { Group group = event.getGroup(); String fromNick = event.getFromNick(); long fromId = event.getFromId(); String message = event.getMessage(); Long invitorId = event.getInvitorId(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat.format(new Date()); Map<Integer, Long> eventMap = new HashMap<>(); eventMap.put(doorNumber, event.getEventId()); MessageChainBuilder messageChain = new MessageChainBuilder(); messageChain.append(new PlainText("来人啦~!\n" + "门牌号:" + doorNumber++ + "\n" + "时间:" + format + "\n" + "敲门人:" + fromNick + "(" + fromId + ")")); if (message.isEmpty()) { messageChain.append("\n敲门口令:(这个人啥也没说!)"); } else { messageChain.append("\n敲门口令:").append(message); } try { if (invitorId != null) { messageChain.append("\n指路人:").append(group.get(invitorId).getNick()).append("(").append(String.valueOf(invitorId)).append(")"); } } catch (Exception e) { LOGGER.warning("新人加群申请-欢迎消息构造失败!"); } assert group != null; group.sendMessage(messageChain.build()); EventChannel<GroupMessageEvent> channel = GlobalEventChannel.INSTANCE.parentScope(HuYanSession.INSTANCE) .filterIsInstance(GroupMessageEvent.class) .filter(nextGroup -> nextGroup.getGroup() == group) .filter(nextEvent -> { String toString = nextEvent.getMessage().contentToString(); return Pattern.matches("(同意|拒绝|开门|关门) +(\\d+|all)|[!!]申请列表", toString); }); map.put(event.getGroupId() + "." + event.getFromId(), new ApplyClusterInfo() {{ setJoinRequestEvent(event); }}); //手动控制监听什么时候结束 channel.subscribe(GroupMessageEvent.class, EmptyCoroutineContext.INSTANCE, ConcurrencyKind.LOCKED, EventPriority.HIGH, messageEvent -> AgreeOrRefuseToApply(event, messageEvent, eventMap)); } /** * 有人入群 * * @param event 群事件 * @author Moyuyanli * @date 2022/8/22 10:39 */ public static void userJoinGroup(MemberJoinEvent event) { Bot bot = event.getBot(); Group group = event.getGroup(); List<GroupWelcomeInfo> welcomeInfoList = null; try { welcomeInfoList = HibernateUtil.factory.fromTransaction(session -> { HibernateCriteriaBuilder builder = session.getCriteriaBuilder(); JpaCriteriaQuery<GroupWelcomeInfo> query = builder.createQuery(GroupWelcomeInfo.class); JpaRoot<GroupWelcomeInfo> from = query.from(GroupWelcomeInfo.class); query.select(from); query.where(builder.equal(from.get("bot"), bot.getId())); return session.createQuery(query).list(); }); } catch (Exception e) { LOGGER.error("出错啦!", e); } GroupWelcomeInfo groupWelcomeInfo = null; boolean next = true; assert welcomeInfoList != null; for (GroupWelcomeInfo groupWelcome : welcomeInfoList) { Scope scope = ScopeUtil.getScope(groupWelcome.getScopeMark()); assert scope != null; if (ShareUtils.mateScope(bot, group, scope)) { next = false; groupWelcomeInfo = groupWelcome; break; } } if (next) { return; } String mark = group.getId() + "." + event.getMember().getId(); if (map.containsKey(mark)) { map.get(mark).setJoinEvent(event); } else { ApplyClusterInfo applyClusterInfo = new ApplyClusterInfo(); applyClusterInfo.setJoinEvent(event); map.put(mark, applyClusterInfo); } DialogueImpl.INSTANCE.dialogueSession(event, groupWelcomeInfo); } /** * 踢人 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/23 21:50 */ public static void kick(MessageEvent event) { Contact subject = event.getSubject(); MessageChain message = event.getMessage(); String code = message.serializeToMiraiCode(); Group group = null; if (subject instanceof Group) { group = (Group) subject; } long userId = 0; for (SingleMessage singleMessage : message) { if (singleMessage instanceof At) { userId = ((At) singleMessage).getTarget(); } } assert group != null; NormalMember member = group.get(userId); if (member == null) { LOGGER.warning("该群员不存在!"); return; } String nameCard = member.getNick(); String nick = event.getSender().getNick(); String[] split = code.split(" +"); if (split.length > 1) { String s = split[1]; if ("hmd".equals(s)) { member.kick("再也不见!", true); } else { member.kick("送你飞机票~"); } } group.sendMessage(String.format("%s被%s送走了....", nameCard, nick)); } /** * 有人加群时检测黑名单用户 * * @param event 加群事件 * @return boolean * @author Moyuyanli * @date 2022/8/24 23:04 */ public static boolean detectBlackList(MemberJoinEvent event) { Group group = event.getGroup(); NormalMember member = event.getMember(); Bot bot = event.getBot(); List<Blacklist> blacklists; try { blacklists = HibernateUtil.factory.fromTransaction(session -> { HibernateCriteriaBuilder builder = session.getCriteriaBuilder(); JpaCriteriaQuery<Blacklist> query = builder.createQuery(Blacklist.class); JpaRoot<Blacklist> from = query.from(Blacklist.class); query.select(from); query.where(builder.equal(from.get("bot"), bot.getId())); query.where(builder.equal(from.get("blackQQ"), member.getId())); List<Blacklist> list = session.createQuery(query).list(); for (Blacklist blacklist : list) { if (blacklist.getScope() == null) { blacklist.setScope(ScopeUtil.getScope(blacklist.getScopeMark())); } } return list; }); } catch (Exception e) { LOGGER.error("出错啦~", e); return false; } if (blacklists == null || blacklists.isEmpty()) { return false; } for (Blacklist blacklist : blacklists) { if (ShareUtils.mateScope(bot, group, blacklist.getScope())) { group.sendMessage("检测到黑名单用户: " + member.getId() + " ,封禁理由:" + blacklist.getReason()); member.kick(blacklist.getReason()); return true; } } return false; } /** * 有人加群时检测黑名单用户 * * @param event 加群事件 * @return boolean * @author Moyuyanli * @date 2022/8/24 23:04 */ public static boolean detectBlackList(MemberJoinRequestEvent event) { Group group = event.getGroup(); assert group != null; long member = event.getFromId(); Bot bot = event.getBot(); List<Blacklist> blacklists; try { blacklists = HibernateUtil.factory.fromTransaction(session -> { HibernateCriteriaBuilder builder = session.getCriteriaBuilder(); JpaCriteriaQuery<Blacklist> query = builder.createQuery(Blacklist.class); JpaRoot<Blacklist> from = query.from(Blacklist.class); query.select(from); query.where(builder.equal(from.get("bot"), bot.getId())); query.where(builder.equal(from.get("blackQQ"), member)); List<Blacklist> list = session.createQuery(query).list(); for (Blacklist blacklist : list) { if (blacklist.getScope() == null) { blacklist.setScope(ScopeUtil.getScope(blacklist.getScopeMark())); } } return list; }); } catch (Exception e) { LOGGER.error("出错啦~", e); return false; } if (blacklists == null || blacklists.isEmpty()) { return false; } for (Blacklist blacklist : blacklists) { if (ShareUtils.mateScope(bot, group, blacklist.getScope())) { group.sendMessage("检测到黑名单用户: " + member + " ,封禁理由:" + blacklist.getReason()); event.reject(); return true; } } return false; } /** * 自动加入黑名单 * * @param event 退群事件 * @author Moyuyanli * @date 2022/8/24 23:36 */ public static void autoAddBlackList(MemberLeaveEvent event) { long botId = event.getBot().getId(); Member member = event.getMember(); long userId = member.getId(); Group group = event.getGroup(); long groupId = group.getId(); Scope scope = new Scope(botId, "当前", false, false, groupId, "null"); Blacklist blacklist = new Blacklist(botId, userId, BlackListData.INSTANCE.getAutoBlackListReason(), scope); BlackListAction.saveBlackList(blacklist, scope); group.sendMessage(String.format("%s(%d) 离开了我们,已经加入黑名单!", member.getNick(), userId)); } /** * 同意或拒绝这个请求 * * @param apply 申请 * @param event 消息 * @return net.mamoe.mirai.event.ListeningStatus * @author Moyuyanli * @date 2022/8/22 11:10 */ private static ListeningStatus AgreeOrRefuseToApply(MemberJoinRequestEvent apply, GroupMessageEvent event, Map<Integer, Long> numbers) { Group group = event.getGroup(); Member sender = event.getSender(); Bot bot = event.getBot(); //权限用户识别符 String powerString = group.getId() + "." + sender.getId(); Map<String, Power> powerMap = StaticData.getPowerMap(bot); MemberPermission permission = event.getGroup().get(event.getSender().getId()).getPermission(); boolean owner = HuYanSession.CONFIG.getOwner() == sender.getId(); if (!owner && permission == MemberPermission.MEMBER) { if (!powerMap.containsKey(powerString)) { return ListeningStatus.LISTENING; } Power power = powerMap.get(powerString); /* 不是机器人管理员 不是群管理员 没有欢迎词操作权限 继续监听 */ if (!power.isAdmin() && !power.isGroupManage() && !power.isGroupHyc()) { return ListeningStatus.LISTENING; } } String content = event.getMessage().contentToString(); if (Pattern.matches("同意 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("开门 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { event.getSubject().sendMessage("好的,我这就开门"); apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("开门 all", content)) { event.getSubject().sendMessage("大门开着的,都进来了"); apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else if (Pattern.matches("同意 all", content)) { apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else if (Pattern.matches("拒绝 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("关门 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { event.getSubject().sendMessage("门我反锁了!"); apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("拒绝 all", content)) { apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else if (Pattern.matches("锁大门", content)) { event.getSubject().sendMessage("大门我上锁了!"); apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else { String fromNick = apply.getFromNick(); long fromId = apply.getFromId(); String message = apply.getMessage(); Long invitorId = apply.getInvitorId(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat.format(new Date()); MessageChainBuilder messageChain = new MessageChainBuilder(); messageChain.append(new PlainText("门外还有人呢!\n" + "门牌号:" + doorNumber + "\n" + "时间:" + format + "\n" + "敲门人:" + fromNick + "(" + fromId + ")")); if (message.isEmpty()) { messageChain.append("\n敲门口令:(这个人啥也没说!)"); } else { messageChain.append("\n敲门口令:").append(message); } try { if (invitorId != null) { messageChain.append("\n指路人:").append(group.get(invitorId).getNick()).append("(").append(String.valueOf(invitorId)).append(")"); } } catch (Exception e) { LOGGER.warning("新人加群申请-欢迎消息构造失败!"); } group.sendMessage(messageChain.build()); } return ListeningStatus.LISTENING; } /** * @param event 消息事件 * @description 解禁言 * @author Moyuyanli * @date 2022/6/21 16:44 */ public void prohibit(MessageEvent event) { Contact subject = event.getSubject(); String code = event.getMessage().serializeToMiraiCode(); Bot bot = event.getBot(); //判断bot的权限 Group group = (Group) subject; boolean botIsAdmin = group.getBotPermission() == MemberPermission.MEMBER; if (botIsAdmin) { subject.sendMessage("人家还不是管理员哦~"); return; } //获取群友对象 Long qq = null; for (SingleMessage s : event.getMessage()) { if (s instanceof At) { qq = ((At) s).getTarget(); } } if (qq == null) { subject.sendMessage("禁言失败,没有这个人呢!"); return; } NormalMember member = Objects.requireNonNull(bot.getGroup(event.getSubject().getId())).get(qq); //获取参数 String[] split = code.split(" "); String param = split[1]; //分解参数 String type = param.substring(param.length() - 1); int timeParam = Integer.parseInt(param.substring(0, param.length() - 1)); if (timeParam == 0) { assert member != null; member.unmute(); subject.sendMessage("解禁成功!"); return; } //禁言时间计算 int time = 0; MessageChainBuilder messages = new MessageChainBuilder().append("禁言成功!"); switch (type) { case "s": time = timeParam; messages.append("禁言:").append(String.valueOf(timeParam)).append("秒"); break; case "m": time = timeParam * 60; messages.append("禁言:").append(String.valueOf(timeParam)).append("分钟"); break; case "h": time = timeParam * 60 * 60; messages.append("禁言:").append(String.valueOf(timeParam)).append("小时"); break; case "d": time = timeParam * 60 * 60 * 24; messages.append("禁言:").append(String.valueOf(timeParam)).append("天"); break; default: break; } //禁言 assert member != null; member.mute(time); subject.sendMessage(messages.build()); } /** * 三种形式撤回消息 * !recall 撤回上一条 * !recall 5 撤回不带本条的前 5 条消息 * !recall 0-5 撤回从本条消息开始算起的总共6条消息 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/15 17:15 */ public void recall(MessageEvent event) { //!recall 0? - 0? String code = event.getMessage().serializeToMiraiCode(); Contact subject = event.getSubject(); //只有是群的情况下才会触发 Group group; if (subject instanceof Group) { group = (Group) subject; } else { return; } //如果不是管理员,就直接不反应 boolean botIsAdmin = group.getBotPermission() == MemberPermission.MEMBER; if (botIsAdmin) { return; } //拿到所有本群的所有消息 List<MessageRecord> records = MiraiHibernateRecorder.INSTANCE.get(group).collect(Collectors.toList()); //识别参数并分割消息 String[] split = code.split(" +"); if (split.length == 1) { records = records.subList(1, 2); } else if (split.length == 2) { String string = split[1]; if (string.contains("-") || string.contains("~")) { String[] strings = string.split("[~-]"); int start = Integer.parseInt(strings[0]); int end = Integer.parseInt(strings[1]); LOGGER.info("s-" + start + " e-" + end); records = records.subList(start, end); } else { int end = Integer.parseInt(split[1]); records = records.subList(1, end); } } //循环撤回 for (MessageRecord record : records) { try { MessageSource.recall(record.toMessageSource()); } catch (PermissionDeniedException e) { LOGGER.warning("消息撤回冲突-无权操作"); } catch (IllegalStateException e) { LOGGER.warning("消息撤回冲突-已被撤回 或 消息未找到"); } catch (Exception e) { subject.sendMessage("消息撤回失败!"); LOGGER.error("出错啦~", e); } } } /** * 赐予群友特殊头衔 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/27 18:57 */ public void editUserTitle(MessageEvent event) { //%@at xxx MessageChain message = event.getMessage(); String code = message.serializeToMiraiCode(); Contact subject = event.getSubject(); Bot bot = event.getBot(); Group group = bot.getGroup(subject.getId()); long userId = 0; for (SingleMessage singleMessage : message) { if (singleMessage instanceof At) { userId = ((At) singleMessage).getTarget(); } } if (userId == 0) { subject.sendMessage("没有这个人"); return; } String title = code.split(" +")[1]; if (group == null) { subject.sendMessage("没有这个群"); return; } NormalMember normalMember = group.get(userId); if (normalMember == null) { subject.sendMessage("没有这个人"); return; } if (group.getBotPermission() != MemberPermission.OWNER) { subject.sendMessage("你的机器人不是群主,无法使用此功能!"); return; } normalMember.setSpecialTitle(title); subject.sendMessage("修改头衔成功!"); } //todo 添加群管理操作 //============================================================================== /** * 判断是否是违禁词 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/16 17:26 */ public boolean isProhibited(MessageEvent event) { String code = event.getMessage().serializeToMiraiCode(); Contact subject = event.getSubject(); User sender = event.getSender(); Bot bot = event.getBot(); if (!(subject instanceof Group)) { return false; } Group group = (Group) subject; MemberPermission botPermission = group.getBotPermission(); if (botPermission == MemberPermission.MEMBER) { return false; } GroupProhibited groupProhibited = null; Map<Scope, List<GroupProhibited>> prohibitedMap = StaticData.getProhibitedMap(bot); for (Scope scope : prohibitedMap.keySet()) { if (ShareUtils.mateScope(event, scope)) { List<GroupProhibited> groupProhibits = prohibitedMap.get(scope); for (GroupProhibited prohibited : groupProhibits) { int mateType = prohibited.getMateType(); Mate mate = Mate.VAGUE; String trigger = prohibited.getKeywords(); if (mateType == 1) { mate = Mate.ACCURATE; } else if (mateType == 3) { mate = Mate.START; } else if (mateType == 4) { mate = Mate.END; } else if (mateType == 5) { mate = Mate.PATTERN; } if (ShareUtils.mateMate(code, mate, trigger,code)) { groupProhibited = prohibited; } } } } if (groupProhibited == null) { return false; } //撤回 if (groupProhibited.isWithdraw()) { try { MessageSource.recall(event.getMessage()); } catch (PermissionDeniedException e) { LOGGER.warning("违禁词撤回失败-权限不足"); } catch (Exception e) { e.printStackTrace(); } } //禁言 if (groupProhibited.isProhibit()) { Member member = (Member) sender; if (groupProhibited.getProhibitTime() > 0) { member.mute(groupProhibited.getProhibitTime()); } } BlackHouseAction blackHouseAction = new BlackHouseAction(); if (groupProhibited.isAccumulate()) { BlackHouse blackHouse = blackHouseAction.getBlackHouse(bot, sender.getId()); if (blackHouse == null) { blackHouse = new BlackHouse(bot.getId(), sender.getId(), groupProhibited.getId(), 1); } else { blackHouse.setNumber(blackHouse.getNumber() + 1); } if (blackHouse.getNumber() >= groupProhibited.getAccumulateNumber()) { subject.sendMessage(sender.getNick() + "已经到达违禁词触发次数,将被踢出本群!"); bot.getGroup(subject.getId()).get(sender.getId()).kick(sender.getNick() + "已经到达违禁词触发次数,将被踢出本群!"); return true; } subject.sendMessage(MessageUtils.newChain() .plus(new At(sender.getId())) .plus(new PlainText("你已经违规 " + blackHouse.getNumber() + " 次,当违规 " + groupProhibited.getAccumulateNumber() + " 次就会被踢出!"))); blackHouseAction.saveOrUpdate(blackHouse); } //回复消息 MessageChain messages = DynamicMessageUtil.parseMessageParameter(event, groupProhibited.getReply(), groupProhibited); if (messages != null) { subject.sendMessage(messages); } return true; } }
Moyuyanli/HuYanSession
src/main/java/cn/chahuyun/session/manage/GroupManager.java
6,762
//获取参数
line_comment
zh-cn
package cn.chahuyun.session.manage; import cn.chahuyun.session.config.BlackListData; import cn.chahuyun.session.HuYanSession; import cn.chahuyun.session.controller.BlackHouseAction; import cn.chahuyun.session.controller.BlackListAction; import cn.chahuyun.session.data.ApplyClusterInfo; import cn.chahuyun.session.data.StaticData; import cn.chahuyun.session.dialogue.DialogueImpl; import cn.chahuyun.session.entity.*; import cn.chahuyun.session.enums.Mate; import cn.chahuyun.session.utils.DynamicMessageUtil; import cn.chahuyun.session.utils.HibernateUtil; import cn.chahuyun.session.utils.ScopeUtil; import cn.chahuyun.session.utils.ShareUtils; import kotlin.coroutines.EmptyCoroutineContext; import net.mamoe.mirai.Bot; import net.mamoe.mirai.contact.*; import net.mamoe.mirai.event.*; import net.mamoe.mirai.event.events.*; import net.mamoe.mirai.message.data.*; import org.hibernate.query.criteria.HibernateCriteriaBuilder; import org.hibernate.query.criteria.JpaCriteriaQuery; import org.hibernate.query.criteria.JpaRoot; import xyz.cssxsh.mirai.hibernate.MiraiHibernateRecorder; import xyz.cssxsh.mirai.hibernate.entry.MessageRecord; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import static cn.chahuyun.session.HuYanSession.LOGGER; /** * GroupManager * 群管理类 * * @author Moyuyanli * @date 2022/8/15 12:52 */ public class GroupManager { public final static GroupManager INSTANCE = new GroupManager(); public final static Map<String, ApplyClusterInfo> map = new HashMap<>(); private static int doorNumber = 0; /** * 有人申请入群 * * @param event 群事件 * @author Moyuyanli * @date 2022/8/22 10:41 */ public static void userRequestGroup(MemberJoinRequestEvent event) { Group group = event.getGroup(); String fromNick = event.getFromNick(); long fromId = event.getFromId(); String message = event.getMessage(); Long invitorId = event.getInvitorId(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat.format(new Date()); Map<Integer, Long> eventMap = new HashMap<>(); eventMap.put(doorNumber, event.getEventId()); MessageChainBuilder messageChain = new MessageChainBuilder(); messageChain.append(new PlainText("来人啦~!\n" + "门牌号:" + doorNumber++ + "\n" + "时间:" + format + "\n" + "敲门人:" + fromNick + "(" + fromId + ")")); if (message.isEmpty()) { messageChain.append("\n敲门口令:(这个人啥也没说!)"); } else { messageChain.append("\n敲门口令:").append(message); } try { if (invitorId != null) { messageChain.append("\n指路人:").append(group.get(invitorId).getNick()).append("(").append(String.valueOf(invitorId)).append(")"); } } catch (Exception e) { LOGGER.warning("新人加群申请-欢迎消息构造失败!"); } assert group != null; group.sendMessage(messageChain.build()); EventChannel<GroupMessageEvent> channel = GlobalEventChannel.INSTANCE.parentScope(HuYanSession.INSTANCE) .filterIsInstance(GroupMessageEvent.class) .filter(nextGroup -> nextGroup.getGroup() == group) .filter(nextEvent -> { String toString = nextEvent.getMessage().contentToString(); return Pattern.matches("(同意|拒绝|开门|关门) +(\\d+|all)|[!!]申请列表", toString); }); map.put(event.getGroupId() + "." + event.getFromId(), new ApplyClusterInfo() {{ setJoinRequestEvent(event); }}); //手动控制监听什么时候结束 channel.subscribe(GroupMessageEvent.class, EmptyCoroutineContext.INSTANCE, ConcurrencyKind.LOCKED, EventPriority.HIGH, messageEvent -> AgreeOrRefuseToApply(event, messageEvent, eventMap)); } /** * 有人入群 * * @param event 群事件 * @author Moyuyanli * @date 2022/8/22 10:39 */ public static void userJoinGroup(MemberJoinEvent event) { Bot bot = event.getBot(); Group group = event.getGroup(); List<GroupWelcomeInfo> welcomeInfoList = null; try { welcomeInfoList = HibernateUtil.factory.fromTransaction(session -> { HibernateCriteriaBuilder builder = session.getCriteriaBuilder(); JpaCriteriaQuery<GroupWelcomeInfo> query = builder.createQuery(GroupWelcomeInfo.class); JpaRoot<GroupWelcomeInfo> from = query.from(GroupWelcomeInfo.class); query.select(from); query.where(builder.equal(from.get("bot"), bot.getId())); return session.createQuery(query).list(); }); } catch (Exception e) { LOGGER.error("出错啦!", e); } GroupWelcomeInfo groupWelcomeInfo = null; boolean next = true; assert welcomeInfoList != null; for (GroupWelcomeInfo groupWelcome : welcomeInfoList) { Scope scope = ScopeUtil.getScope(groupWelcome.getScopeMark()); assert scope != null; if (ShareUtils.mateScope(bot, group, scope)) { next = false; groupWelcomeInfo = groupWelcome; break; } } if (next) { return; } String mark = group.getId() + "." + event.getMember().getId(); if (map.containsKey(mark)) { map.get(mark).setJoinEvent(event); } else { ApplyClusterInfo applyClusterInfo = new ApplyClusterInfo(); applyClusterInfo.setJoinEvent(event); map.put(mark, applyClusterInfo); } DialogueImpl.INSTANCE.dialogueSession(event, groupWelcomeInfo); } /** * 踢人 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/23 21:50 */ public static void kick(MessageEvent event) { Contact subject = event.getSubject(); MessageChain message = event.getMessage(); String code = message.serializeToMiraiCode(); Group group = null; if (subject instanceof Group) { group = (Group) subject; } long userId = 0; for (SingleMessage singleMessage : message) { if (singleMessage instanceof At) { userId = ((At) singleMessage).getTarget(); } } assert group != null; NormalMember member = group.get(userId); if (member == null) { LOGGER.warning("该群员不存在!"); return; } String nameCard = member.getNick(); String nick = event.getSender().getNick(); String[] split = code.split(" +"); if (split.length > 1) { String s = split[1]; if ("hmd".equals(s)) { member.kick("再也不见!", true); } else { member.kick("送你飞机票~"); } } group.sendMessage(String.format("%s被%s送走了....", nameCard, nick)); } /** * 有人加群时检测黑名单用户 * * @param event 加群事件 * @return boolean * @author Moyuyanli * @date 2022/8/24 23:04 */ public static boolean detectBlackList(MemberJoinEvent event) { Group group = event.getGroup(); NormalMember member = event.getMember(); Bot bot = event.getBot(); List<Blacklist> blacklists; try { blacklists = HibernateUtil.factory.fromTransaction(session -> { HibernateCriteriaBuilder builder = session.getCriteriaBuilder(); JpaCriteriaQuery<Blacklist> query = builder.createQuery(Blacklist.class); JpaRoot<Blacklist> from = query.from(Blacklist.class); query.select(from); query.where(builder.equal(from.get("bot"), bot.getId())); query.where(builder.equal(from.get("blackQQ"), member.getId())); List<Blacklist> list = session.createQuery(query).list(); for (Blacklist blacklist : list) { if (blacklist.getScope() == null) { blacklist.setScope(ScopeUtil.getScope(blacklist.getScopeMark())); } } return list; }); } catch (Exception e) { LOGGER.error("出错啦~", e); return false; } if (blacklists == null || blacklists.isEmpty()) { return false; } for (Blacklist blacklist : blacklists) { if (ShareUtils.mateScope(bot, group, blacklist.getScope())) { group.sendMessage("检测到黑名单用户: " + member.getId() + " ,封禁理由:" + blacklist.getReason()); member.kick(blacklist.getReason()); return true; } } return false; } /** * 有人加群时检测黑名单用户 * * @param event 加群事件 * @return boolean * @author Moyuyanli * @date 2022/8/24 23:04 */ public static boolean detectBlackList(MemberJoinRequestEvent event) { Group group = event.getGroup(); assert group != null; long member = event.getFromId(); Bot bot = event.getBot(); List<Blacklist> blacklists; try { blacklists = HibernateUtil.factory.fromTransaction(session -> { HibernateCriteriaBuilder builder = session.getCriteriaBuilder(); JpaCriteriaQuery<Blacklist> query = builder.createQuery(Blacklist.class); JpaRoot<Blacklist> from = query.from(Blacklist.class); query.select(from); query.where(builder.equal(from.get("bot"), bot.getId())); query.where(builder.equal(from.get("blackQQ"), member)); List<Blacklist> list = session.createQuery(query).list(); for (Blacklist blacklist : list) { if (blacklist.getScope() == null) { blacklist.setScope(ScopeUtil.getScope(blacklist.getScopeMark())); } } return list; }); } catch (Exception e) { LOGGER.error("出错啦~", e); return false; } if (blacklists == null || blacklists.isEmpty()) { return false; } for (Blacklist blacklist : blacklists) { if (ShareUtils.mateScope(bot, group, blacklist.getScope())) { group.sendMessage("检测到黑名单用户: " + member + " ,封禁理由:" + blacklist.getReason()); event.reject(); return true; } } return false; } /** * 自动加入黑名单 * * @param event 退群事件 * @author Moyuyanli * @date 2022/8/24 23:36 */ public static void autoAddBlackList(MemberLeaveEvent event) { long botId = event.getBot().getId(); Member member = event.getMember(); long userId = member.getId(); Group group = event.getGroup(); long groupId = group.getId(); Scope scope = new Scope(botId, "当前", false, false, groupId, "null"); Blacklist blacklist = new Blacklist(botId, userId, BlackListData.INSTANCE.getAutoBlackListReason(), scope); BlackListAction.saveBlackList(blacklist, scope); group.sendMessage(String.format("%s(%d) 离开了我们,已经加入黑名单!", member.getNick(), userId)); } /** * 同意或拒绝这个请求 * * @param apply 申请 * @param event 消息 * @return net.mamoe.mirai.event.ListeningStatus * @author Moyuyanli * @date 2022/8/22 11:10 */ private static ListeningStatus AgreeOrRefuseToApply(MemberJoinRequestEvent apply, GroupMessageEvent event, Map<Integer, Long> numbers) { Group group = event.getGroup(); Member sender = event.getSender(); Bot bot = event.getBot(); //权限用户识别符 String powerString = group.getId() + "." + sender.getId(); Map<String, Power> powerMap = StaticData.getPowerMap(bot); MemberPermission permission = event.getGroup().get(event.getSender().getId()).getPermission(); boolean owner = HuYanSession.CONFIG.getOwner() == sender.getId(); if (!owner && permission == MemberPermission.MEMBER) { if (!powerMap.containsKey(powerString)) { return ListeningStatus.LISTENING; } Power power = powerMap.get(powerString); /* 不是机器人管理员 不是群管理员 没有欢迎词操作权限 继续监听 */ if (!power.isAdmin() && !power.isGroupManage() && !power.isGroupHyc()) { return ListeningStatus.LISTENING; } } String content = event.getMessage().contentToString(); if (Pattern.matches("同意 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("开门 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { event.getSubject().sendMessage("好的,我这就开门"); apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("开门 all", content)) { event.getSubject().sendMessage("大门开着的,都进来了"); apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else if (Pattern.matches("同意 all", content)) { apply.accept(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else if (Pattern.matches("拒绝 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("关门 \\d+", content)) { int number = Integer.parseInt(content.substring(3)); if (!numbers.containsKey(number)) { return ListeningStatus.LISTENING; } Long eventId = numbers.get(number); if (apply.getEventId() == eventId) { event.getSubject().sendMessage("门我反锁了!"); apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); } return ListeningStatus.STOPPED; } else if (Pattern.matches("拒绝 all", content)) { apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else if (Pattern.matches("锁大门", content)) { event.getSubject().sendMessage("大门我上锁了!"); apply.reject(); map.get(apply.getGroupId() + "." + apply.getFromId()).setMessageEvent(event); return ListeningStatus.STOPPED; } else { String fromNick = apply.getFromNick(); long fromId = apply.getFromId(); String message = apply.getMessage(); Long invitorId = apply.getInvitorId(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = simpleDateFormat.format(new Date()); MessageChainBuilder messageChain = new MessageChainBuilder(); messageChain.append(new PlainText("门外还有人呢!\n" + "门牌号:" + doorNumber + "\n" + "时间:" + format + "\n" + "敲门人:" + fromNick + "(" + fromId + ")")); if (message.isEmpty()) { messageChain.append("\n敲门口令:(这个人啥也没说!)"); } else { messageChain.append("\n敲门口令:").append(message); } try { if (invitorId != null) { messageChain.append("\n指路人:").append(group.get(invitorId).getNick()).append("(").append(String.valueOf(invitorId)).append(")"); } } catch (Exception e) { LOGGER.warning("新人加群申请-欢迎消息构造失败!"); } group.sendMessage(messageChain.build()); } return ListeningStatus.LISTENING; } /** * @param event 消息事件 * @description 解禁言 * @author Moyuyanli * @date 2022/6/21 16:44 */ public void prohibit(MessageEvent event) { Contact subject = event.getSubject(); String code = event.getMessage().serializeToMiraiCode(); Bot bot = event.getBot(); //判断bot的权限 Group group = (Group) subject; boolean botIsAdmin = group.getBotPermission() == MemberPermission.MEMBER; if (botIsAdmin) { subject.sendMessage("人家还不是管理员哦~"); return; } //获取群友对象 Long qq = null; for (SingleMessage s : event.getMessage()) { if (s instanceof At) { qq = ((At) s).getTarget(); } } if (qq == null) { subject.sendMessage("禁言失败,没有这个人呢!"); return; } NormalMember member = Objects.requireNonNull(bot.getGroup(event.getSubject().getId())).get(qq); //获取 <SUF> String[] split = code.split(" "); String param = split[1]; //分解参数 String type = param.substring(param.length() - 1); int timeParam = Integer.parseInt(param.substring(0, param.length() - 1)); if (timeParam == 0) { assert member != null; member.unmute(); subject.sendMessage("解禁成功!"); return; } //禁言时间计算 int time = 0; MessageChainBuilder messages = new MessageChainBuilder().append("禁言成功!"); switch (type) { case "s": time = timeParam; messages.append("禁言:").append(String.valueOf(timeParam)).append("秒"); break; case "m": time = timeParam * 60; messages.append("禁言:").append(String.valueOf(timeParam)).append("分钟"); break; case "h": time = timeParam * 60 * 60; messages.append("禁言:").append(String.valueOf(timeParam)).append("小时"); break; case "d": time = timeParam * 60 * 60 * 24; messages.append("禁言:").append(String.valueOf(timeParam)).append("天"); break; default: break; } //禁言 assert member != null; member.mute(time); subject.sendMessage(messages.build()); } /** * 三种形式撤回消息 * !recall 撤回上一条 * !recall 5 撤回不带本条的前 5 条消息 * !recall 0-5 撤回从本条消息开始算起的总共6条消息 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/15 17:15 */ public void recall(MessageEvent event) { //!recall 0? - 0? String code = event.getMessage().serializeToMiraiCode(); Contact subject = event.getSubject(); //只有是群的情况下才会触发 Group group; if (subject instanceof Group) { group = (Group) subject; } else { return; } //如果不是管理员,就直接不反应 boolean botIsAdmin = group.getBotPermission() == MemberPermission.MEMBER; if (botIsAdmin) { return; } //拿到所有本群的所有消息 List<MessageRecord> records = MiraiHibernateRecorder.INSTANCE.get(group).collect(Collectors.toList()); //识别参数并分割消息 String[] split = code.split(" +"); if (split.length == 1) { records = records.subList(1, 2); } else if (split.length == 2) { String string = split[1]; if (string.contains("-") || string.contains("~")) { String[] strings = string.split("[~-]"); int start = Integer.parseInt(strings[0]); int end = Integer.parseInt(strings[1]); LOGGER.info("s-" + start + " e-" + end); records = records.subList(start, end); } else { int end = Integer.parseInt(split[1]); records = records.subList(1, end); } } //循环撤回 for (MessageRecord record : records) { try { MessageSource.recall(record.toMessageSource()); } catch (PermissionDeniedException e) { LOGGER.warning("消息撤回冲突-无权操作"); } catch (IllegalStateException e) { LOGGER.warning("消息撤回冲突-已被撤回 或 消息未找到"); } catch (Exception e) { subject.sendMessage("消息撤回失败!"); LOGGER.error("出错啦~", e); } } } /** * 赐予群友特殊头衔 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/27 18:57 */ public void editUserTitle(MessageEvent event) { //%@at xxx MessageChain message = event.getMessage(); String code = message.serializeToMiraiCode(); Contact subject = event.getSubject(); Bot bot = event.getBot(); Group group = bot.getGroup(subject.getId()); long userId = 0; for (SingleMessage singleMessage : message) { if (singleMessage instanceof At) { userId = ((At) singleMessage).getTarget(); } } if (userId == 0) { subject.sendMessage("没有这个人"); return; } String title = code.split(" +")[1]; if (group == null) { subject.sendMessage("没有这个群"); return; } NormalMember normalMember = group.get(userId); if (normalMember == null) { subject.sendMessage("没有这个人"); return; } if (group.getBotPermission() != MemberPermission.OWNER) { subject.sendMessage("你的机器人不是群主,无法使用此功能!"); return; } normalMember.setSpecialTitle(title); subject.sendMessage("修改头衔成功!"); } //todo 添加群管理操作 //============================================================================== /** * 判断是否是违禁词 * * @param event 消息事件 * @author Moyuyanli * @date 2022/8/16 17:26 */ public boolean isProhibited(MessageEvent event) { String code = event.getMessage().serializeToMiraiCode(); Contact subject = event.getSubject(); User sender = event.getSender(); Bot bot = event.getBot(); if (!(subject instanceof Group)) { return false; } Group group = (Group) subject; MemberPermission botPermission = group.getBotPermission(); if (botPermission == MemberPermission.MEMBER) { return false; } GroupProhibited groupProhibited = null; Map<Scope, List<GroupProhibited>> prohibitedMap = StaticData.getProhibitedMap(bot); for (Scope scope : prohibitedMap.keySet()) { if (ShareUtils.mateScope(event, scope)) { List<GroupProhibited> groupProhibits = prohibitedMap.get(scope); for (GroupProhibited prohibited : groupProhibits) { int mateType = prohibited.getMateType(); Mate mate = Mate.VAGUE; String trigger = prohibited.getKeywords(); if (mateType == 1) { mate = Mate.ACCURATE; } else if (mateType == 3) { mate = Mate.START; } else if (mateType == 4) { mate = Mate.END; } else if (mateType == 5) { mate = Mate.PATTERN; } if (ShareUtils.mateMate(code, mate, trigger,code)) { groupProhibited = prohibited; } } } } if (groupProhibited == null) { return false; } //撤回 if (groupProhibited.isWithdraw()) { try { MessageSource.recall(event.getMessage()); } catch (PermissionDeniedException e) { LOGGER.warning("违禁词撤回失败-权限不足"); } catch (Exception e) { e.printStackTrace(); } } //禁言 if (groupProhibited.isProhibit()) { Member member = (Member) sender; if (groupProhibited.getProhibitTime() > 0) { member.mute(groupProhibited.getProhibitTime()); } } BlackHouseAction blackHouseAction = new BlackHouseAction(); if (groupProhibited.isAccumulate()) { BlackHouse blackHouse = blackHouseAction.getBlackHouse(bot, sender.getId()); if (blackHouse == null) { blackHouse = new BlackHouse(bot.getId(), sender.getId(), groupProhibited.getId(), 1); } else { blackHouse.setNumber(blackHouse.getNumber() + 1); } if (blackHouse.getNumber() >= groupProhibited.getAccumulateNumber()) { subject.sendMessage(sender.getNick() + "已经到达违禁词触发次数,将被踢出本群!"); bot.getGroup(subject.getId()).get(sender.getId()).kick(sender.getNick() + "已经到达违禁词触发次数,将被踢出本群!"); return true; } subject.sendMessage(MessageUtils.newChain() .plus(new At(sender.getId())) .plus(new PlainText("你已经违规 " + blackHouse.getNumber() + " 次,当违规 " + groupProhibited.getAccumulateNumber() + " 次就会被踢出!"))); blackHouseAction.saveOrUpdate(blackHouse); } //回复消息 MessageChain messages = DynamicMessageUtil.parseMessageParameter(event, groupProhibited.getReply(), groupProhibited); if (messages != null) { subject.sendMessage(messages); } return true; } }
false
39178_0
package com.guiguli.string_ArrayList; import java.util.ArrayList; /* 案例 集合存储自定义元素并遍历 需求:定义电影类(名称 分值 演员) 创建三个电影对象 代表三部影片 《肖申克的救赎》 9.7 罗宾斯 《霸王别姬》 9.6 张国荣 张丰毅 《阿甘正传》 9.5 汤姆.汉克斯 */ public class ArrayListMovie { public static void main(String[] args) { Movie m1=new Movie("《肖申克的救赎》",9.7,"罗宾斯"); Movie m2=new Movie("《霸王别姬》",9.7,"张国荣、张丰毅"); Movie m3=new Movie("《阿甘正传》",9.5,"汤姆.汉克斯"); ArrayList<Movie>movies=new ArrayList<>(); movies.add(m1); movies.add(m2); movies.add(m3); //遍历 for(int i=0;i<movies.size();i++){ Movie m =movies.get(i); System.out.println("电影名称:"+m.getName()); System.out.println("电影得分:"+m.getScore()); System.out.println("电影主演:"+m.getActotor()); System.out.println("---------------"); } } }
Mq-b/-2022-5-4-
Java/基础/ArrayLIst/ArrayListMovie.java
374
/* 案例 集合存储自定义元素并遍历 需求:定义电影类(名称 分值 演员) 创建三个电影对象 代表三部影片 《肖申克的救赎》 9.7 罗宾斯 《霸王别姬》 9.6 张国荣 张丰毅 《阿甘正传》 9.5 汤姆.汉克斯 */
block_comment
zh-cn
package com.guiguli.string_ArrayList; import java.util.ArrayList; /* 案例 <SUF>*/ public class ArrayListMovie { public static void main(String[] args) { Movie m1=new Movie("《肖申克的救赎》",9.7,"罗宾斯"); Movie m2=new Movie("《霸王别姬》",9.7,"张国荣、张丰毅"); Movie m3=new Movie("《阿甘正传》",9.5,"汤姆.汉克斯"); ArrayList<Movie>movies=new ArrayList<>(); movies.add(m1); movies.add(m2); movies.add(m3); //遍历 for(int i=0;i<movies.size();i++){ Movie m =movies.get(i); System.out.println("电影名称:"+m.getName()); System.out.println("电影得分:"+m.getScore()); System.out.println("电影主演:"+m.getActotor()); System.out.println("---------------"); } } }
false
55270_2
package com.guigu.domain.info; public class Talk { String talk_id;//谈话编号 String talk_person;//谈话人编号 String talk_time;//谈话日期 public String getTalk_id() { return talk_id; } public void setTalk_id(String talk_id) { this.talk_id = talk_id; } public String getTalk_person() { return talk_person; } public void setTalk_person(String talk_person) { this.talk_person = talk_person; } public String getTalk_time() { return talk_time; } public void setTalk_time(String talk_time) { this.talk_time = talk_time; } @Override public String toString() { return "Talk [talk_id=" + talk_id + ", talk_person=" + talk_person + ", talk_time=" + talk_time + "]"; } public Talk(String talk_id, String talk_person, String talk_time) { super(); this.talk_id = talk_id; this.talk_person = talk_person; this.talk_time = talk_time; } public Talk() { super(); } }
Mr-Orang/StuMgr-Java
guigu_domain/src/main/java/com/guigu/domain/info/Talk.java
331
//谈话日期
line_comment
zh-cn
package com.guigu.domain.info; public class Talk { String talk_id;//谈话编号 String talk_person;//谈话人编号 String talk_time;//谈话 <SUF> public String getTalk_id() { return talk_id; } public void setTalk_id(String talk_id) { this.talk_id = talk_id; } public String getTalk_person() { return talk_person; } public void setTalk_person(String talk_person) { this.talk_person = talk_person; } public String getTalk_time() { return talk_time; } public void setTalk_time(String talk_time) { this.talk_time = talk_time; } @Override public String toString() { return "Talk [talk_id=" + talk_id + ", talk_person=" + talk_person + ", talk_time=" + talk_time + "]"; } public Talk(String talk_id, String talk_person, String talk_time) { super(); this.talk_id = talk_id; this.talk_person = talk_person; this.talk_time = talk_time; } public Talk() { super(); } }
false
2294_4
package cn.lger.web; import cn.lger.service.MemberService; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; /** * Code that Changed the World * Pro said * Created by Pro on 2017-12-20. */ @Controller @PropertySource("classpath:emailConfig.properties") public class BirthdayWarningController { @Resource private MemberService memberService; @Value("${email.account}") private String emailAccount; @Value("${email.password}") private String emailPassword; @Value("${email.smtp}") private String emailSmtp; @GetMapping("/birthdayWarning") public String getBirthdayWarningView(Map<String, Object> model){ if (memberService.findBirthdayToday().size()==0){ model.put("msg", "null"); } return "birthdayWarning"; } @PostMapping("/birthdayWarning") @ResponseBody public String birthdayWarning(String content){ try { // System.out.println(content); Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", emailSmtp); // 发件人的邮箱的 SMTP 服务器地址 props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 Session session = Session.getInstance(props); session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log List<String> receiveMailAccounts = memberService.findBirthdayToday(); for (String receiveMailAccount : receiveMailAccounts){ Transport transport = session.getTransport(); MimeMessage message = createMimeMessage(session, emailAccount, receiveMailAccount,content); transport.connect(emailAccount, emailPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } } catch (Exception e) { e.printStackTrace(); return "error"; } return "success"; } private MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String content) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sendMail, "测试JMail", "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "亲爱的 先生/小姐", "UTF-8")); message.setSubject("生日快乐", "UTF-8"); message.setContent(content, "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); return message; } }
Mr-Pro/membership
src/main/java/cn/lger/web/BirthdayWarningController.java
802
// 发件人的邮箱的 SMTP 服务器地址
line_comment
zh-cn
package cn.lger.web; import cn.lger.service.MemberService; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Properties; /** * Code that Changed the World * Pro said * Created by Pro on 2017-12-20. */ @Controller @PropertySource("classpath:emailConfig.properties") public class BirthdayWarningController { @Resource private MemberService memberService; @Value("${email.account}") private String emailAccount; @Value("${email.password}") private String emailPassword; @Value("${email.smtp}") private String emailSmtp; @GetMapping("/birthdayWarning") public String getBirthdayWarningView(Map<String, Object> model){ if (memberService.findBirthdayToday().size()==0){ model.put("msg", "null"); } return "birthdayWarning"; } @PostMapping("/birthdayWarning") @ResponseBody public String birthdayWarning(String content){ try { // System.out.println(content); Properties props = new Properties(); // 参数配置 props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求) props.setProperty("mail.smtp.host", emailSmtp); // 发件 <SUF> props.setProperty("mail.smtp.auth", "true"); // 需要请求认证 Session session = Session.getInstance(props); session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log List<String> receiveMailAccounts = memberService.findBirthdayToday(); for (String receiveMailAccount : receiveMailAccounts){ Transport transport = session.getTransport(); MimeMessage message = createMimeMessage(session, emailAccount, receiveMailAccount,content); transport.connect(emailAccount, emailPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } } catch (Exception e) { e.printStackTrace(); return "error"; } return "success"; } private MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String content) throws Exception { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sendMail, "测试JMail", "UTF-8")); message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "亲爱的 先生/小姐", "UTF-8")); message.setSubject("生日快乐", "UTF-8"); message.setContent(content, "text/html;charset=UTF-8"); message.setSentDate(new Date()); message.saveChanges(); return message; } }
true
56335_3
package xiaoliang.ltool.bean; import android.graphics.Color; import java.io.Serializable; /** * Created by Liuj on 2016/11/4. * 记事本的Bean */ public class NoteBean implements Serializable { public int id; public String title;//标题 public String note;//内容 public float money;//金额 public boolean income = false;//是否是收入 public long startTime;//开始时间 public long endTime;//结束时间 public long createTime;//创建时间 public long advance;//提前时间 public int noteType;//颜色ID public int color;//颜色色值 public boolean alert;//提醒 public boolean oneDay;//一整天 public String address;//地址 public NoteBean() { this(-1,"","",0,false,-1,-1,-1,-1,Color.BLACK,false,false,"",0); } public NoteBean(int id,String title, String note, float money, boolean income, long startTime, long endTime, long advance, int noteType, int color, boolean alert, boolean oneDay, String address,long createTime) { this.id = id; this.title = title; this.note = note; this.money = money; this.income = income; this.startTime = startTime; this.endTime = endTime; this.advance = advance; this.noteType = noteType; this.color = color; this.alert = alert; this.oneDay = oneDay; this.address = address; this.createTime = createTime; } }
Mr-XiaoLiang/LTool
app/src/main/java/xiaoliang/ltool/bean/NoteBean.java
367
//结束时间
line_comment
zh-cn
package xiaoliang.ltool.bean; import android.graphics.Color; import java.io.Serializable; /** * Created by Liuj on 2016/11/4. * 记事本的Bean */ public class NoteBean implements Serializable { public int id; public String title;//标题 public String note;//内容 public float money;//金额 public boolean income = false;//是否是收入 public long startTime;//开始时间 public long endTime;//结束 <SUF> public long createTime;//创建时间 public long advance;//提前时间 public int noteType;//颜色ID public int color;//颜色色值 public boolean alert;//提醒 public boolean oneDay;//一整天 public String address;//地址 public NoteBean() { this(-1,"","",0,false,-1,-1,-1,-1,Color.BLACK,false,false,"",0); } public NoteBean(int id,String title, String note, float money, boolean income, long startTime, long endTime, long advance, int noteType, int color, boolean alert, boolean oneDay, String address,long createTime) { this.id = id; this.title = title; this.note = note; this.money = money; this.income = income; this.startTime = startTime; this.endTime = endTime; this.advance = advance; this.noteType = noteType; this.color = color; this.alert = alert; this.oneDay = oneDay; this.address = address; this.createTime = createTime; } }
false
22160_5
package com.l.j.view; import java.util.Calendar; import com.l.j.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.FontMetrics; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class LCalendarView extends View { /** * 年份 */ private int year; /** * 月份 */ private int month; /** * 日期数组 9组,代表了8个方向所有可能滑动的方向 */ private int[] days, leftTopDays, rightTopDays, leftBottomDays, rightBottomDays, leftDays, topDays, rightDays, bottomDays; /** * 今天 */ private int today = 0, thisYear = 0, thisMonth = 0; /** * 选中日期 */ private int selectedDay = 0; /** * 字体大小 */ private float textSize; /** * 字体中心点 */ private float textY; /** * 选中颜色 */ private int selectColor; /** * 数字颜色 */ private int textColor; /** * 星期颜色 */ private int weekColor; /** * 背景色 */ private int backgroundColor; /** * 今天颜色 */ private int todayColor;; /** * 文字的画笔 */ private Paint textPaint; /** * 点的画笔 */ private Paint pointPaint; /** * 今天画笔 */ private Paint todayPaint; /** * 背景笔 */ private Paint backgroundPaint; /** * 日历计算类 */ private Calendar getDaysCalendar = Calendar.getInstance(); /** * 星期 */ private String[] weeks = { "日", "一", "二", "三", "四", "五", "六" }; /** * 单元格的宽度 */ int width = 0; /** * 单元格的高度 */ int height = 0; /** * 日期选择监听器 */ private CalendarViewListener calendarViewListener; /** * 偏移量 */ private int offsetX = 0, offsetY = 0; /** * 按下位置 */ private float downX, downY; /** * 手指是否抬起 */ private boolean isTouchUp = true; /** * 速度 */ private float speed = 0.8F; /** * 滑动类型 * @author LiuJ * */ public enum SlideType{ Vertical, Horizontal, Both } /** * 当前滑动类型 */ private SlideType slideType = SlideType.Both; /** * 起始年 */ private int startYear = -1; /** * 起始月 */ private int startMonth = -1; /** * 起始天 */ private int startDay = -1; public interface CalendarViewListener { public void calendarSelected(int year, int month,int d); public void calendarChange(int year, int month); } public LCalendarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); days = new int[42]; year = 2015; month = 9; today = 0; textSize = 0; textY = 0; selectColor = Color.parseColor("#99c9f2"); textColor = Color.BLACK; weekColor = Color.GRAY; backgroundColor = Color.parseColor("#50EEEEEE"); todayColor = Color.parseColor("#50000000"); /** * 获得我们所定义的自定义样式属性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.calendarview, defStyleAttr, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.calendarview_background_color: backgroundColor = a.getColor(attr, Color.parseColor("#ebebeb")); break; case R.styleable.calendarview_month: month = a.getInt(attr, 0); break; case R.styleable.calendarview_selected: selectedDay = a.getInt(attr, 0); break; case R.styleable.calendarview_selected_color: selectColor = a.getColor(attr, Color.parseColor("#99c9f2")); break; case R.styleable.calendarview_today: today = a.getInt(attr, 0); break; case R.styleable.calendarview_text_color: textColor = a.getColor(attr, Color.BLACK); break; case R.styleable.calendarview_today_color: todayColor = a.getColor(attr, Color.parseColor("#50000000")); break; case R.styleable.calendarview_weeks_color: weekColor = a.getColor(attr, Color.GRAY); break; case R.styleable.calendarview_year: year = a.getColor(attr, 0); break; } } a.recycle(); init(); initPaint(); } public LCalendarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LCalendarView(Context context) { this(context, null); } @Override protected void onDraw(Canvas canvas) { width = getWidth() / 7; height = getHeight() / 7; if (textSize == 0) { textSize = height * 0.5f; textPaint.setTextSize(textSize); } // 绘制当月 drawText(canvas, days, offsetX, offsetY, year, month); // 绘制其他月,选择性绘制,避免浪费 if (offsetX > 0) { if (leftDays == null) leftDays = getDays(year, month - 1); drawText(canvas, leftDays, offsetX - getWidth(), offsetY, year, month - 1); if (offsetY > 0) { if (leftTopDays == null) leftDays = getDays(year - 1, month - 1); drawText(canvas, leftTopDays, offsetX - getWidth(), offsetY - getHeight(), year - 1, month - 1); } if (offsetY < 0) { if (leftBottomDays == null) leftBottomDays = getDays(year + 1, month - 1); drawText(canvas, leftBottomDays, offsetX - getWidth(), offsetY + getHeight(), year + 1, month - 1); } } if (offsetX < 0) { if (rightDays == null) rightDays = getDays(year, month + 1); drawText(canvas, rightDays, offsetX + getWidth(), offsetY, year, month + 1); if (offsetY > 0) { if (rightTopDays == null) rightTopDays = getDays(year - 1, month + 1); drawText(canvas, rightTopDays, offsetX + getWidth(), offsetY - getHeight(), year - 1, month + 1); } if (offsetY < 0) { if (rightBottomDays == null) rightBottomDays = getDays(year + 1, month + 1); drawText(canvas, rightBottomDays, offsetX + getWidth(), offsetY + getHeight(), year + 1, month + 1); } } if (offsetY > 0) { if (topDays == null) topDays = getDays(year - 1, month); drawText(canvas, topDays, offsetX, offsetY - getHeight(), year - 1, month); } if (offsetY < 0) { if (bottomDays == null) bottomDays = getDays(year + 1, month); drawText(canvas, bottomDays, offsetX, offsetY + getHeight(), year + 1, month); } if (isTouchUp) { // if (Math.abs(offsetX) > getWidth() / 2) { // if (offsetX > 0) { // offsetX -= getWidth(); // month--; // if (month < 1) { // month = 12; // year--; // } // } else { // offsetX += getWidth(); // month++; // if (month > 12) { // month = 1; // year++; // } // } // if (calendarViewListener != null) { // calendarViewListener.calendarChange(year, month); // } // getDay(0); // } // if (Math.abs(offsetY) > getHeight() / 2) { // if (offsetY > 0) { // offsetY -= getHeight(); // year--; // } else { // offsetY += getHeight(); // year++; // } // if (calendarViewListener != null) { // calendarViewListener.calendarChange(year, month); // } // getDay(0); // } offsetX *= speed; offsetY *= speed; if (Math.abs(offsetX) < 1) { offsetX = 0; invalidate(); } if (Math.abs(offsetY) < 1) { offsetY = 0; invalidate(); } if (Math.abs(offsetX) > 1 || Math.abs(offsetY) > 1) { invalidate(); } else { leftTopDays = null; rightTopDays = null; leftBottomDays = null; rightBottomDays = null; leftDays = null; topDays = null; rightDays = null; bottomDays = null; } } // super.onDraw(canvas); } /** * 获取对应的日历数组 * @param i 对应T9键盘的位置 * 1 2 3 * 4 5 6 * 7 8 9 */ private void getDay(int i) { switch (i) { case 1: leftTopDays = getDays(year - 1, month - 1); break; case 2: switch (slideType) { case Both: topDays = getDays(year - 1, month); break; case Vertical: topDays = getDays(year, month - 1); break; } break; case 3: rightTopDays = getDays(year - 1, month + 1); break; case 4: leftDays = getDays(year, month - 1); break; case 5: days = getDays(year, month); break; case 6: rightDays = getDays(year, month + 1); break; case 7: leftBottomDays = getDays(year + 1, month - 1); break; case 8: switch (slideType) { case Both: bottomDays = getDays(year + 1, month); break; case Vertical: bottomDays = getDays(year, month + 1); break; } break; case 9: rightBottomDays = getDays(year + 1, month + 1); break; default: days = getDays(year, month); if (offsetX > 0) { leftDays = getDays(year, month - 1); if (offsetY > 0) { leftTopDays = getDays(year - 1, month - 1); } if (offsetY < 0) { leftBottomDays = getDays(year + 1, month - 1); } } if (offsetX < 0) { rightDays = getDays(year, month + 1); if (offsetY > 0) { rightTopDays = getDays(year - 1, month + 1); } if (offsetY < 0) { rightBottomDays = getDays(year + 1, month + 1); } } if (offsetY > 0) { switch (slideType) { case Both: topDays = getDays(year - 1, month); break; case Vertical: topDays = getDays(year, month - 1); break; } } if (offsetY < 0) { switch (slideType) { case Both: bottomDays = getDays(year + 1, month); break; case Vertical: bottomDays = getDays(year, month + 1); break; } } break; } } private void drawText(Canvas canvas, int[] daysArray, int xOffset, int yOffset, int y, int m) { if (daysArray == null) { return; } if(xOffset!=0||yOffset!=0){ if((y+m)%2>0){ backgroundPaint.setColor(backgroundColor); }else{ backgroundPaint.setColor(Color.WHITE); } RectF rect = new RectF(xOffset, yOffset, getWidth()+xOffset, getHeight()+yOffset); canvas.drawRect(rect, backgroundPaint); } FontMetrics fm = textPaint.getFontMetrics(); textY = height / 2 - fm.descent + (fm.descent - fm.ascent) / 2; textPaint.setColor(weekColor); for (int j = 0; j < 7; j++) { canvas.drawText(weeks[j], (width * j) + width / 2 + xOffset, textY + yOffset, textPaint); } textPaint.setColor(textColor); for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (daysArray[i * 7 + j] == 0) { continue; } if (today != 0 && daysArray[i * 7 + j] == today && thisYear == y && thisMonth == m) { canvas.drawCircle((width * j) + width / 2 + xOffset, (height * (i + 1)) + height / 2 + yOffset, textSize * 1f, todayPaint); } if (selectedDay != 0 && daysArray[i * 7 + j] == selectedDay && year == y && month == m) { canvas.drawCircle((width * j) + width / 2 + xOffset, (height * (i + 1)) + height / 2 + yOffset, textSize * 1f, pointPaint); } canvas.drawText(daysArray[i * 7 + j] + "", (width * j) + width / 2 + xOffset, (height * (i + 1)) + textY + yOffset, textPaint); } } } /** * 获取指定月份的日历数组 * * @param year * @param month * @return */ private int[] getDays(int year, int month) { int[] daysArray = new int[42]; getDaysCalendar.set(Calendar.YEAR, year); getDaysCalendar.set(Calendar.MONTH, month - 1); getDaysCalendar.set(Calendar.DAY_OF_MONTH, getDaysCalendar.getActualMinimum(Calendar.DAY_OF_MONTH)); int start = getDaysCalendar.get(Calendar.DAY_OF_WEEK) - 1; int end = getDaysCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); int day = 1; if(year<startYear||(year==startYear&&month<startMonth)){ return null; } if(year==startYear&&month==startMonth){ for (int i = 0; i < days.length; i++) { if (i < start || day > end) { daysArray[i] = 0; } else { if(day>=startDay){ daysArray[i] = day; } day++; } } return daysArray; } for (int i = 0; i < days.length; i++) { if (i < start || day > end) { daysArray[i] = 0; } else { daysArray[i] = day; day++; } } return daysArray; } private void init() { Calendar calendar = Calendar.getInstance(); if (year == 0) { year = calendar.get(Calendar.YEAR); } if (month == 0) { month = calendar.get(Calendar.MONTH); } days = getDays(year, month); invalidate(); } private void initPaint(){ textPaint = new Paint(); textPaint.setTextSize(textSize); textPaint.setAntiAlias(true); textPaint.setTextAlign(Align.CENTER); pointPaint = new Paint(); pointPaint.setColor(selectColor); pointPaint.setAntiAlias(true); todayPaint = new Paint(); todayPaint.setColor(todayColor); todayPaint.setAntiAlias(true); backgroundPaint = new Paint(); backgroundPaint.setColor(backgroundColor); backgroundPaint.setAntiAlias(true); } @Override public boolean onTouchEvent(MotionEvent event) { int x = 0; int y = 0; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: x = (int) event.getX() / width; y = (int) event.getY() / height; /** * 判断是不是在我们的日历里面 */ if (y >= 1 && x >= 0 && y < 7 && x < 7 && days[((y - 1) * 7) + x] != 0) { selectedDay = days[((y - 1) * 7) + x]; } // 按下位置 downX = event.getX(); downY = event.getY(); isTouchUp = false; break; case MotionEvent.ACTION_MOVE: switch (slideType) { case Vertical: offsetY = (int) (event.getY() - downY); break; case Horizontal: offsetX = (int) (event.getX() - downX); break; case Both: offsetX = (int) (event.getX() - downX); offsetY = (int) (event.getY() - downY); break; } if (Math.abs(offsetX) > getWidth() / 2) { if (offsetX > 0) { if(year>startYear||(year==startYear&&month>startMonth)){ offsetX -= getWidth(); downX += getWidth(); month--; if (month < 1) { month = 12; year--; } } } else { offsetX += getWidth(); downX -= getWidth(); month++; if (month > 12) { month = 1; year++; } } getDay(0); if (calendarViewListener != null) { calendarViewListener.calendarChange(year, month); } } if (Math.abs(offsetY) > getHeight() / 2) { if (offsetY > 0) { if(year>startYear||(year==startYear&&month>startMonth)){ offsetY -= getHeight(); downY += getHeight(); switch (slideType) { case Vertical: month--; if (month < 1) { month = 12; year--; } break; case Both: year--; if(year<startYear){ year++; } break; } } } else { offsetY += getHeight(); downY -= getHeight(); switch (slideType) { case Vertical: month++; if (month > 12) { month = 1; year++; } break; case Both: year++; break; } } getDay(0); if (calendarViewListener != null) { calendarViewListener.calendarChange(year, month); } } break; case MotionEvent.ACTION_UP: isTouchUp = true; break; } if (calendarViewListener != null) { calendarViewListener.calendarSelected(year,month,selectedDay); } invalidate(); return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = (int) (textSize * 11) + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = (int) (textSize * 11) + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } /** * 获取年份 * * @return */ public int getYear() { return year; } /** * 设置年份 * * @param year */ public void setYear(int year) { this.year = year; init(); } /** * 获取月份 * * @return */ public int getMonth() { return month; } /** * 设置月份 * * @param month */ public void setMonth(int month) { this.month = month; init(); } /** * 获取今天 * * @return */ public int getToday() { return today; } /** * 设置今天 * * @param today */ public void setToday(int today, int year, int month) { this.today = today; this.thisYear = year; this.thisMonth = month; init(); } /** * 获取选中日期 * * @return */ public int getSelectedDay() { return selectedDay; } /** * 设置选中日期 * * @param selectedDay */ public void setSelectedDay(int selectedDay) { this.selectedDay = selectedDay; init(); } /** * 获取字体大小 * * @return */ public float getTextSize() { return textSize; } /** * 设置字体大小 * * @param textSize */ public void setTextSize(float textSize) { this.textSize = textSize; initPaint(); init(); } /** * 获取选中背景色 * * @return */ public int getSelectColor() { return selectColor; } /** * 设置选中背景色 * * @param selectColor */ public void setSelectColor(int selectColor) { this.selectColor = selectColor; initPaint(); init(); } /** * 获取字体颜色 * * @return */ public int getTextColor() { return textColor; } /** * 设置字体颜色 * * @param textColor */ public void setTextColor(int textColor) { this.textColor = textColor; initPaint(); init(); } /** * 获取星期颜色 * * @return */ public int getWeekColor() { return weekColor; } /** * 设置星期颜色 * * @param weekColor */ public void setWeekColor(int weekColor) { this.weekColor = weekColor; initPaint(); init(); } /** * \ 获取背景色 * * @return */ public int getBackgroundColor() { return backgroundColor; } /** * 设置背景颜色 */ public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; initPaint(); init(); } /** * 获取今天背景色 * * @return */ public int getTodayColor() { return todayColor; } /** * 设置今天背景色 * * @param todayColor */ public void setTodayColor(int todayColor) { this.todayColor = todayColor; initPaint(); init(); } /** * 获取日历选择监听器 * * @return */ public CalendarViewListener getCalendarViewListener() { return calendarViewListener; } /** * 设置日历选择监听器 * * @param calendarViewListener */ public void setCalendarViewListener(CalendarViewListener calendarViewListener) { this.calendarViewListener = calendarViewListener; } /** * 更新日期 * * @param year * @param month * @param today * @param selected */ public void setData(int year, int month, int today, int selected, int thisyear, int thismonth) { this.year = year; this.month = month; this.today = today; this.selectedDay = selected; this.thisYear = thisyear; this.thisMonth = thismonth; init(); } /** * 设置可选项 传入可选项的范围 * * @param min * @param max */ public void setItems(int min, int max) { if (max < min) { max = min; } int[] items = new int[days.length]; for (int i = 0; i < items.length; i++) { items[i] = 0; } for (int i = min; i <= max; i++) { B: for (int j = 0; j < days.length; j++) { if (days[j] == i) { items[j] = i; break B; } } } days = items; invalidate(); } /** * 设置可选项 * * @param items * 传入可选项的数组 */ public void setItems(int[] item) { int[] items = new int[days.length]; for (int i = 0; i < items.length; i++) { items[i] = 0; } for (int i = 0; i < item.length; i++) { B: for (int j = 0; j < days.length; j++) { if (days[j] == item[i]) { items[j] = item[i]; break B; } } } days = items; invalidate(); } public SlideType getSlideType() { return slideType; } public void setSlideType(SlideType slideType) { this.slideType = slideType; } /** * 设置起始日期 * @param startYear * @param startMonth * @param startDay */ public void setStart(int startYear, int startMonth, int startDay) { this.startYear = startYear; this.startMonth = startMonth; this.startDay = startDay; getDay(0); invalidate(); } }
Mr-XiaoLiang/LView
src/com/l/j/view/LCalendarView.java
7,389
/** * 字体大小 */
block_comment
zh-cn
package com.l.j.view; import java.util.Calendar; import com.l.j.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.FontMetrics; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; public class LCalendarView extends View { /** * 年份 */ private int year; /** * 月份 */ private int month; /** * 日期数组 9组,代表了8个方向所有可能滑动的方向 */ private int[] days, leftTopDays, rightTopDays, leftBottomDays, rightBottomDays, leftDays, topDays, rightDays, bottomDays; /** * 今天 */ private int today = 0, thisYear = 0, thisMonth = 0; /** * 选中日期 */ private int selectedDay = 0; /** * 字体大 <SUF>*/ private float textSize; /** * 字体中心点 */ private float textY; /** * 选中颜色 */ private int selectColor; /** * 数字颜色 */ private int textColor; /** * 星期颜色 */ private int weekColor; /** * 背景色 */ private int backgroundColor; /** * 今天颜色 */ private int todayColor;; /** * 文字的画笔 */ private Paint textPaint; /** * 点的画笔 */ private Paint pointPaint; /** * 今天画笔 */ private Paint todayPaint; /** * 背景笔 */ private Paint backgroundPaint; /** * 日历计算类 */ private Calendar getDaysCalendar = Calendar.getInstance(); /** * 星期 */ private String[] weeks = { "日", "一", "二", "三", "四", "五", "六" }; /** * 单元格的宽度 */ int width = 0; /** * 单元格的高度 */ int height = 0; /** * 日期选择监听器 */ private CalendarViewListener calendarViewListener; /** * 偏移量 */ private int offsetX = 0, offsetY = 0; /** * 按下位置 */ private float downX, downY; /** * 手指是否抬起 */ private boolean isTouchUp = true; /** * 速度 */ private float speed = 0.8F; /** * 滑动类型 * @author LiuJ * */ public enum SlideType{ Vertical, Horizontal, Both } /** * 当前滑动类型 */ private SlideType slideType = SlideType.Both; /** * 起始年 */ private int startYear = -1; /** * 起始月 */ private int startMonth = -1; /** * 起始天 */ private int startDay = -1; public interface CalendarViewListener { public void calendarSelected(int year, int month,int d); public void calendarChange(int year, int month); } public LCalendarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); days = new int[42]; year = 2015; month = 9; today = 0; textSize = 0; textY = 0; selectColor = Color.parseColor("#99c9f2"); textColor = Color.BLACK; weekColor = Color.GRAY; backgroundColor = Color.parseColor("#50EEEEEE"); todayColor = Color.parseColor("#50000000"); /** * 获得我们所定义的自定义样式属性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.calendarview, defStyleAttr, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.calendarview_background_color: backgroundColor = a.getColor(attr, Color.parseColor("#ebebeb")); break; case R.styleable.calendarview_month: month = a.getInt(attr, 0); break; case R.styleable.calendarview_selected: selectedDay = a.getInt(attr, 0); break; case R.styleable.calendarview_selected_color: selectColor = a.getColor(attr, Color.parseColor("#99c9f2")); break; case R.styleable.calendarview_today: today = a.getInt(attr, 0); break; case R.styleable.calendarview_text_color: textColor = a.getColor(attr, Color.BLACK); break; case R.styleable.calendarview_today_color: todayColor = a.getColor(attr, Color.parseColor("#50000000")); break; case R.styleable.calendarview_weeks_color: weekColor = a.getColor(attr, Color.GRAY); break; case R.styleable.calendarview_year: year = a.getColor(attr, 0); break; } } a.recycle(); init(); initPaint(); } public LCalendarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public LCalendarView(Context context) { this(context, null); } @Override protected void onDraw(Canvas canvas) { width = getWidth() / 7; height = getHeight() / 7; if (textSize == 0) { textSize = height * 0.5f; textPaint.setTextSize(textSize); } // 绘制当月 drawText(canvas, days, offsetX, offsetY, year, month); // 绘制其他月,选择性绘制,避免浪费 if (offsetX > 0) { if (leftDays == null) leftDays = getDays(year, month - 1); drawText(canvas, leftDays, offsetX - getWidth(), offsetY, year, month - 1); if (offsetY > 0) { if (leftTopDays == null) leftDays = getDays(year - 1, month - 1); drawText(canvas, leftTopDays, offsetX - getWidth(), offsetY - getHeight(), year - 1, month - 1); } if (offsetY < 0) { if (leftBottomDays == null) leftBottomDays = getDays(year + 1, month - 1); drawText(canvas, leftBottomDays, offsetX - getWidth(), offsetY + getHeight(), year + 1, month - 1); } } if (offsetX < 0) { if (rightDays == null) rightDays = getDays(year, month + 1); drawText(canvas, rightDays, offsetX + getWidth(), offsetY, year, month + 1); if (offsetY > 0) { if (rightTopDays == null) rightTopDays = getDays(year - 1, month + 1); drawText(canvas, rightTopDays, offsetX + getWidth(), offsetY - getHeight(), year - 1, month + 1); } if (offsetY < 0) { if (rightBottomDays == null) rightBottomDays = getDays(year + 1, month + 1); drawText(canvas, rightBottomDays, offsetX + getWidth(), offsetY + getHeight(), year + 1, month + 1); } } if (offsetY > 0) { if (topDays == null) topDays = getDays(year - 1, month); drawText(canvas, topDays, offsetX, offsetY - getHeight(), year - 1, month); } if (offsetY < 0) { if (bottomDays == null) bottomDays = getDays(year + 1, month); drawText(canvas, bottomDays, offsetX, offsetY + getHeight(), year + 1, month); } if (isTouchUp) { // if (Math.abs(offsetX) > getWidth() / 2) { // if (offsetX > 0) { // offsetX -= getWidth(); // month--; // if (month < 1) { // month = 12; // year--; // } // } else { // offsetX += getWidth(); // month++; // if (month > 12) { // month = 1; // year++; // } // } // if (calendarViewListener != null) { // calendarViewListener.calendarChange(year, month); // } // getDay(0); // } // if (Math.abs(offsetY) > getHeight() / 2) { // if (offsetY > 0) { // offsetY -= getHeight(); // year--; // } else { // offsetY += getHeight(); // year++; // } // if (calendarViewListener != null) { // calendarViewListener.calendarChange(year, month); // } // getDay(0); // } offsetX *= speed; offsetY *= speed; if (Math.abs(offsetX) < 1) { offsetX = 0; invalidate(); } if (Math.abs(offsetY) < 1) { offsetY = 0; invalidate(); } if (Math.abs(offsetX) > 1 || Math.abs(offsetY) > 1) { invalidate(); } else { leftTopDays = null; rightTopDays = null; leftBottomDays = null; rightBottomDays = null; leftDays = null; topDays = null; rightDays = null; bottomDays = null; } } // super.onDraw(canvas); } /** * 获取对应的日历数组 * @param i 对应T9键盘的位置 * 1 2 3 * 4 5 6 * 7 8 9 */ private void getDay(int i) { switch (i) { case 1: leftTopDays = getDays(year - 1, month - 1); break; case 2: switch (slideType) { case Both: topDays = getDays(year - 1, month); break; case Vertical: topDays = getDays(year, month - 1); break; } break; case 3: rightTopDays = getDays(year - 1, month + 1); break; case 4: leftDays = getDays(year, month - 1); break; case 5: days = getDays(year, month); break; case 6: rightDays = getDays(year, month + 1); break; case 7: leftBottomDays = getDays(year + 1, month - 1); break; case 8: switch (slideType) { case Both: bottomDays = getDays(year + 1, month); break; case Vertical: bottomDays = getDays(year, month + 1); break; } break; case 9: rightBottomDays = getDays(year + 1, month + 1); break; default: days = getDays(year, month); if (offsetX > 0) { leftDays = getDays(year, month - 1); if (offsetY > 0) { leftTopDays = getDays(year - 1, month - 1); } if (offsetY < 0) { leftBottomDays = getDays(year + 1, month - 1); } } if (offsetX < 0) { rightDays = getDays(year, month + 1); if (offsetY > 0) { rightTopDays = getDays(year - 1, month + 1); } if (offsetY < 0) { rightBottomDays = getDays(year + 1, month + 1); } } if (offsetY > 0) { switch (slideType) { case Both: topDays = getDays(year - 1, month); break; case Vertical: topDays = getDays(year, month - 1); break; } } if (offsetY < 0) { switch (slideType) { case Both: bottomDays = getDays(year + 1, month); break; case Vertical: bottomDays = getDays(year, month + 1); break; } } break; } } private void drawText(Canvas canvas, int[] daysArray, int xOffset, int yOffset, int y, int m) { if (daysArray == null) { return; } if(xOffset!=0||yOffset!=0){ if((y+m)%2>0){ backgroundPaint.setColor(backgroundColor); }else{ backgroundPaint.setColor(Color.WHITE); } RectF rect = new RectF(xOffset, yOffset, getWidth()+xOffset, getHeight()+yOffset); canvas.drawRect(rect, backgroundPaint); } FontMetrics fm = textPaint.getFontMetrics(); textY = height / 2 - fm.descent + (fm.descent - fm.ascent) / 2; textPaint.setColor(weekColor); for (int j = 0; j < 7; j++) { canvas.drawText(weeks[j], (width * j) + width / 2 + xOffset, textY + yOffset, textPaint); } textPaint.setColor(textColor); for (int i = 0; i < 6; i++) { for (int j = 0; j < 7; j++) { if (daysArray[i * 7 + j] == 0) { continue; } if (today != 0 && daysArray[i * 7 + j] == today && thisYear == y && thisMonth == m) { canvas.drawCircle((width * j) + width / 2 + xOffset, (height * (i + 1)) + height / 2 + yOffset, textSize * 1f, todayPaint); } if (selectedDay != 0 && daysArray[i * 7 + j] == selectedDay && year == y && month == m) { canvas.drawCircle((width * j) + width / 2 + xOffset, (height * (i + 1)) + height / 2 + yOffset, textSize * 1f, pointPaint); } canvas.drawText(daysArray[i * 7 + j] + "", (width * j) + width / 2 + xOffset, (height * (i + 1)) + textY + yOffset, textPaint); } } } /** * 获取指定月份的日历数组 * * @param year * @param month * @return */ private int[] getDays(int year, int month) { int[] daysArray = new int[42]; getDaysCalendar.set(Calendar.YEAR, year); getDaysCalendar.set(Calendar.MONTH, month - 1); getDaysCalendar.set(Calendar.DAY_OF_MONTH, getDaysCalendar.getActualMinimum(Calendar.DAY_OF_MONTH)); int start = getDaysCalendar.get(Calendar.DAY_OF_WEEK) - 1; int end = getDaysCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); int day = 1; if(year<startYear||(year==startYear&&month<startMonth)){ return null; } if(year==startYear&&month==startMonth){ for (int i = 0; i < days.length; i++) { if (i < start || day > end) { daysArray[i] = 0; } else { if(day>=startDay){ daysArray[i] = day; } day++; } } return daysArray; } for (int i = 0; i < days.length; i++) { if (i < start || day > end) { daysArray[i] = 0; } else { daysArray[i] = day; day++; } } return daysArray; } private void init() { Calendar calendar = Calendar.getInstance(); if (year == 0) { year = calendar.get(Calendar.YEAR); } if (month == 0) { month = calendar.get(Calendar.MONTH); } days = getDays(year, month); invalidate(); } private void initPaint(){ textPaint = new Paint(); textPaint.setTextSize(textSize); textPaint.setAntiAlias(true); textPaint.setTextAlign(Align.CENTER); pointPaint = new Paint(); pointPaint.setColor(selectColor); pointPaint.setAntiAlias(true); todayPaint = new Paint(); todayPaint.setColor(todayColor); todayPaint.setAntiAlias(true); backgroundPaint = new Paint(); backgroundPaint.setColor(backgroundColor); backgroundPaint.setAntiAlias(true); } @Override public boolean onTouchEvent(MotionEvent event) { int x = 0; int y = 0; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: x = (int) event.getX() / width; y = (int) event.getY() / height; /** * 判断是不是在我们的日历里面 */ if (y >= 1 && x >= 0 && y < 7 && x < 7 && days[((y - 1) * 7) + x] != 0) { selectedDay = days[((y - 1) * 7) + x]; } // 按下位置 downX = event.getX(); downY = event.getY(); isTouchUp = false; break; case MotionEvent.ACTION_MOVE: switch (slideType) { case Vertical: offsetY = (int) (event.getY() - downY); break; case Horizontal: offsetX = (int) (event.getX() - downX); break; case Both: offsetX = (int) (event.getX() - downX); offsetY = (int) (event.getY() - downY); break; } if (Math.abs(offsetX) > getWidth() / 2) { if (offsetX > 0) { if(year>startYear||(year==startYear&&month>startMonth)){ offsetX -= getWidth(); downX += getWidth(); month--; if (month < 1) { month = 12; year--; } } } else { offsetX += getWidth(); downX -= getWidth(); month++; if (month > 12) { month = 1; year++; } } getDay(0); if (calendarViewListener != null) { calendarViewListener.calendarChange(year, month); } } if (Math.abs(offsetY) > getHeight() / 2) { if (offsetY > 0) { if(year>startYear||(year==startYear&&month>startMonth)){ offsetY -= getHeight(); downY += getHeight(); switch (slideType) { case Vertical: month--; if (month < 1) { month = 12; year--; } break; case Both: year--; if(year<startYear){ year++; } break; } } } else { offsetY += getHeight(); downY -= getHeight(); switch (slideType) { case Vertical: month++; if (month > 12) { month = 1; year++; } break; case Both: year++; break; } } getDay(0); if (calendarViewListener != null) { calendarViewListener.calendarChange(year, month); } } break; case MotionEvent.ACTION_UP: isTouchUp = true; break; } if (calendarViewListener != null) { calendarViewListener.calendarSelected(year,month,selectedDay); } invalidate(); return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec)); } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = (int) (textSize * 11) + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = (int) (textSize * 11) + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } /** * 获取年份 * * @return */ public int getYear() { return year; } /** * 设置年份 * * @param year */ public void setYear(int year) { this.year = year; init(); } /** * 获取月份 * * @return */ public int getMonth() { return month; } /** * 设置月份 * * @param month */ public void setMonth(int month) { this.month = month; init(); } /** * 获取今天 * * @return */ public int getToday() { return today; } /** * 设置今天 * * @param today */ public void setToday(int today, int year, int month) { this.today = today; this.thisYear = year; this.thisMonth = month; init(); } /** * 获取选中日期 * * @return */ public int getSelectedDay() { return selectedDay; } /** * 设置选中日期 * * @param selectedDay */ public void setSelectedDay(int selectedDay) { this.selectedDay = selectedDay; init(); } /** * 获取字体大小 * * @return */ public float getTextSize() { return textSize; } /** * 设置字体大小 * * @param textSize */ public void setTextSize(float textSize) { this.textSize = textSize; initPaint(); init(); } /** * 获取选中背景色 * * @return */ public int getSelectColor() { return selectColor; } /** * 设置选中背景色 * * @param selectColor */ public void setSelectColor(int selectColor) { this.selectColor = selectColor; initPaint(); init(); } /** * 获取字体颜色 * * @return */ public int getTextColor() { return textColor; } /** * 设置字体颜色 * * @param textColor */ public void setTextColor(int textColor) { this.textColor = textColor; initPaint(); init(); } /** * 获取星期颜色 * * @return */ public int getWeekColor() { return weekColor; } /** * 设置星期颜色 * * @param weekColor */ public void setWeekColor(int weekColor) { this.weekColor = weekColor; initPaint(); init(); } /** * \ 获取背景色 * * @return */ public int getBackgroundColor() { return backgroundColor; } /** * 设置背景颜色 */ public void setBackgroundColor(int backgroundColor) { this.backgroundColor = backgroundColor; initPaint(); init(); } /** * 获取今天背景色 * * @return */ public int getTodayColor() { return todayColor; } /** * 设置今天背景色 * * @param todayColor */ public void setTodayColor(int todayColor) { this.todayColor = todayColor; initPaint(); init(); } /** * 获取日历选择监听器 * * @return */ public CalendarViewListener getCalendarViewListener() { return calendarViewListener; } /** * 设置日历选择监听器 * * @param calendarViewListener */ public void setCalendarViewListener(CalendarViewListener calendarViewListener) { this.calendarViewListener = calendarViewListener; } /** * 更新日期 * * @param year * @param month * @param today * @param selected */ public void setData(int year, int month, int today, int selected, int thisyear, int thismonth) { this.year = year; this.month = month; this.today = today; this.selectedDay = selected; this.thisYear = thisyear; this.thisMonth = thismonth; init(); } /** * 设置可选项 传入可选项的范围 * * @param min * @param max */ public void setItems(int min, int max) { if (max < min) { max = min; } int[] items = new int[days.length]; for (int i = 0; i < items.length; i++) { items[i] = 0; } for (int i = min; i <= max; i++) { B: for (int j = 0; j < days.length; j++) { if (days[j] == i) { items[j] = i; break B; } } } days = items; invalidate(); } /** * 设置可选项 * * @param items * 传入可选项的数组 */ public void setItems(int[] item) { int[] items = new int[days.length]; for (int i = 0; i < items.length; i++) { items[i] = 0; } for (int i = 0; i < item.length; i++) { B: for (int j = 0; j < days.length; j++) { if (days[j] == item[i]) { items[j] = item[i]; break B; } } } days = items; invalidate(); } public SlideType getSlideType() { return slideType; } public void setSlideType(SlideType slideType) { this.slideType = slideType; } /** * 设置起始日期 * @param startYear * @param startMonth * @param startDay */ public void setStart(int startYear, int startMonth, int startDay) { this.startYear = startYear; this.startMonth = startMonth; this.startDay = startDay; getDay(0); invalidate(); } }
false
62248_2
package hello; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * Created by acer on 2019/1/31. */ public class TestCyclicBarrier { static Integer count = 0; public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(20, () -> { if (count == 0) { System.out.println("班车准备开始运营~"); count++; }else{ System.out.println("车上座位已经满,请等待下一班!"); count++; } }); //公寓有一百个人 for (int i = 0; i < 100; i++) { new Thread(() -> { try { //模拟起床耗时 Thread.sleep((long) (Math.random() * 1000)); barrier.await(); System.out.println(Thread.currentThread().getName() + " 赶上了第 " + count + "趟班车。。。"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } }
Mr-yangaimin/overview_java
Java 语言基础/多线程与并发/三个好用的并发工具类/hellox/src/hello/TestCyclicBarrier.java
301
//模拟起床耗时
line_comment
zh-cn
package hello; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * Created by acer on 2019/1/31. */ public class TestCyclicBarrier { static Integer count = 0; public static void main(String[] args) { CyclicBarrier barrier = new CyclicBarrier(20, () -> { if (count == 0) { System.out.println("班车准备开始运营~"); count++; }else{ System.out.println("车上座位已经满,请等待下一班!"); count++; } }); //公寓有一百个人 for (int i = 0; i < 100; i++) { new Thread(() -> { try { //模拟 <SUF> Thread.sleep((long) (Math.random() * 1000)); barrier.await(); System.out.println(Thread.currentThread().getName() + " 赶上了第 " + count + "趟班车。。。"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } }
true
29971_19
package org.example; import org.example.Uitls.CompKeyUtil; import org.example.Uitls.DataInit; import java.io.File; import java.util.*; public class Main { public static void main(String[] args) throws Exception { //,"好喝","好玩","开心","春天","大地","太阳","头发","奔跑","柴火","闪电","祝福","山川","心脏","月亮" String[] keys = {"好吃", "好喝", "好玩", "开心", "春天", "大地", "太阳", "头发", "奔跑", "柴火", "闪电", "祝福", "山川", "心脏", "月亮"}; String[] no_use_args = {"的", "吗", "什么", "有", "一个", "是"}; // 初始化数据处理类 DataInit dataInit = new DataInit( "res/user_tag_query.10W.TRAIN", keys, no_use_args, "res/output.txt", true ); CompKeyUtil compKeyUtil = new CompKeyUtil(dataInit); //遍历种子关键词 // for(String key : keys){ // Map<String, Double> compareMap = new HashMap<>(); // // List<Map.Entry<String, Integer>> middleKeys = compKeyUtil.findMiddle(key); // 得到中间关键词及其在output中出现次数(sa) // middleKeys.remove(0); // 将自身排除 // } // //进行数据处理 int[] lines = new int[15]; // lines[n]表示第n个关键词出现的次数(s) try { dataInit.doInit(lines); } catch (Exception e) { e.printStackTrace(); } // 测试第n个关键词出现次数的统计 // for(int line : lines){ // System.out.println(line); // } // // CompKeyUtil compKeyUtil = new CompKeyUtil(dataInit); //遍历种子关键词 for ( String key : keys) { Map<String, Double> compareMap = new HashMap<>(); List<Map.Entry<String, Integer>> middleKeys = compKeyUtil.findMiddle(key); // 得到中间关键词及其在output中出现次数(sa) middleKeys.remove(0); // 将自身排除 /* * for (Map.Entry<String, Integer> middleKey : middleKeys) { * * middleKey.getKey() // 中间关键词 * * middleKey.getValue() // 权重(sa) * } * */ int[] counts = new int[CAPACITY]; // 储存第n个中间关键词在整体出现的次数(a) String[] middles = new String[CAPACITY]; // 储存第n个关键词本身 //遍历中间关键词得到竞争关键词 for (int i = 0; i < CAPACITY; i++) { Map.Entry<String, Integer> entry = middleKeys.get(i); String string = entry.getKey(); middles[i] = string; } /* // 测试中间关键词查找是否正确 for(String middle : middles){ System.out.println(middle); } */ // 查找各中间关键词在整体出现的次数(a) compKeyUtil.countMiddle(middles, counts); /* // 测试中间关键词查找是否正确 for(int count : counts){ System.out.println(count); } */ /* for (Map.Entry<String, Integer> middleKey : middleKeys) { System.out.println(middleKey.getKey()+":"+middleKey.getValue()); // 竞争关键词 } */ int count = 0; // 中间关键词序号计数器 for (String middle : middles) {// 遍历中间关键词 List<Map.Entry<String, Integer>> compareKeys = compKeyUtil.findCompare(middle); // 得到竞争关键词及其在原文件中出现次数(ka) compKeyUtil.calculateCompare(compareMap, middleKeys.get(count).getValue(), compareKeys, counts[count], lines); count++; } // 将LinkedHashMap转换为List List<Map.Entry<String, Double>> compareList = new ArrayList<>(compareMap.entrySet()); // 使用Comparator和stream进行值的降序排序 compareList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); // 排除本身 compareList.remove(0); // // 按竞争度从大到小显示当前种子关键词的竞争关键词,(调试用) // count = 0; // for(Map.Entry<String, Double> map : compareList){ // System.out.println(map.getKey() + ": "+ map.getValue()); // count ++; // if(count == CAPACITY) break; // } /* * 如上,此程序块的上一级程序块为一个for循环,而循环的内容是遍历种子关键词数组 * 即当前程序块是针对种子关键词数组中的某一个种子关键词 * 对于竞争关键词,已经使用compareList进行封装 * 该封装类型是一个List类,其中泛式为包含<String, Double>键值对的Map.Entry * 其中String为竞争关键词本身,Double为竞争该竞争关键词对于当前种子关键词的竞争度 * 详细使用见上方调试代码 * 在对compareList的遍历中,map.getKey()获得竞争关键词,map.getValue()获得竞争度,数据类型如上所述 * compareList不仅只含有10个数据,其数据非常多,但由于简化计算,故对其循环次数默认定为静态量CAPACITY(此量在下方代码有定义) * */ } } private static int CAPACITY = 10; }
MrBhite/ECProject
src/main/java/org/example/Main.java
1,457
//遍历中间关键词得到竞争关键词
line_comment
zh-cn
package org.example; import org.example.Uitls.CompKeyUtil; import org.example.Uitls.DataInit; import java.io.File; import java.util.*; public class Main { public static void main(String[] args) throws Exception { //,"好喝","好玩","开心","春天","大地","太阳","头发","奔跑","柴火","闪电","祝福","山川","心脏","月亮" String[] keys = {"好吃", "好喝", "好玩", "开心", "春天", "大地", "太阳", "头发", "奔跑", "柴火", "闪电", "祝福", "山川", "心脏", "月亮"}; String[] no_use_args = {"的", "吗", "什么", "有", "一个", "是"}; // 初始化数据处理类 DataInit dataInit = new DataInit( "res/user_tag_query.10W.TRAIN", keys, no_use_args, "res/output.txt", true ); CompKeyUtil compKeyUtil = new CompKeyUtil(dataInit); //遍历种子关键词 // for(String key : keys){ // Map<String, Double> compareMap = new HashMap<>(); // // List<Map.Entry<String, Integer>> middleKeys = compKeyUtil.findMiddle(key); // 得到中间关键词及其在output中出现次数(sa) // middleKeys.remove(0); // 将自身排除 // } // //进行数据处理 int[] lines = new int[15]; // lines[n]表示第n个关键词出现的次数(s) try { dataInit.doInit(lines); } catch (Exception e) { e.printStackTrace(); } // 测试第n个关键词出现次数的统计 // for(int line : lines){ // System.out.println(line); // } // // CompKeyUtil compKeyUtil = new CompKeyUtil(dataInit); //遍历种子关键词 for ( String key : keys) { Map<String, Double> compareMap = new HashMap<>(); List<Map.Entry<String, Integer>> middleKeys = compKeyUtil.findMiddle(key); // 得到中间关键词及其在output中出现次数(sa) middleKeys.remove(0); // 将自身排除 /* * for (Map.Entry<String, Integer> middleKey : middleKeys) { * * middleKey.getKey() // 中间关键词 * * middleKey.getValue() // 权重(sa) * } * */ int[] counts = new int[CAPACITY]; // 储存第n个中间关键词在整体出现的次数(a) String[] middles = new String[CAPACITY]; // 储存第n个关键词本身 //遍历 <SUF> for (int i = 0; i < CAPACITY; i++) { Map.Entry<String, Integer> entry = middleKeys.get(i); String string = entry.getKey(); middles[i] = string; } /* // 测试中间关键词查找是否正确 for(String middle : middles){ System.out.println(middle); } */ // 查找各中间关键词在整体出现的次数(a) compKeyUtil.countMiddle(middles, counts); /* // 测试中间关键词查找是否正确 for(int count : counts){ System.out.println(count); } */ /* for (Map.Entry<String, Integer> middleKey : middleKeys) { System.out.println(middleKey.getKey()+":"+middleKey.getValue()); // 竞争关键词 } */ int count = 0; // 中间关键词序号计数器 for (String middle : middles) {// 遍历中间关键词 List<Map.Entry<String, Integer>> compareKeys = compKeyUtil.findCompare(middle); // 得到竞争关键词及其在原文件中出现次数(ka) compKeyUtil.calculateCompare(compareMap, middleKeys.get(count).getValue(), compareKeys, counts[count], lines); count++; } // 将LinkedHashMap转换为List List<Map.Entry<String, Double>> compareList = new ArrayList<>(compareMap.entrySet()); // 使用Comparator和stream进行值的降序排序 compareList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder())); // 排除本身 compareList.remove(0); // // 按竞争度从大到小显示当前种子关键词的竞争关键词,(调试用) // count = 0; // for(Map.Entry<String, Double> map : compareList){ // System.out.println(map.getKey() + ": "+ map.getValue()); // count ++; // if(count == CAPACITY) break; // } /* * 如上,此程序块的上一级程序块为一个for循环,而循环的内容是遍历种子关键词数组 * 即当前程序块是针对种子关键词数组中的某一个种子关键词 * 对于竞争关键词,已经使用compareList进行封装 * 该封装类型是一个List类,其中泛式为包含<String, Double>键值对的Map.Entry * 其中String为竞争关键词本身,Double为竞争该竞争关键词对于当前种子关键词的竞争度 * 详细使用见上方调试代码 * 在对compareList的遍历中,map.getKey()获得竞争关键词,map.getValue()获得竞争度,数据类型如上所述 * compareList不仅只含有10个数据,其数据非常多,但由于简化计算,故对其循环次数默认定为静态量CAPACITY(此量在下方代码有定义) * */ } } private static int CAPACITY = 10; }
true
61055_4
/* * 类的成员之四:代码块(或初始化块) * * 1. 代码块的作用:用来初始化类、对象 * 2. 代码块如果有修饰的话,只能使用static. * 3. 分类:静态代码块 vs 非静态代码块 * * 4. 静态代码块 * >内部可以有输出语句 * >随着类的加载而执行,而且只执行一次 * >作用:初始化类的信息 * >如果一个类中定义了多个静态代码块,则按照声明的先后顺序执行 * >静态代码块的执行要优先于非静态代码块的执行 * >静态代码块内只能调用静态的属性、静态的方法,不能调用非静态的结构 * * 5. 非静态代码块 * >内部可以有输出语句 * >随着对象的创建而执行 * >每创建一个对象,就执行一次非静态代码块 * >作用:可以在创建对象时,对对象的属性等进行初始化 * >如果一个类中定义了多个非静态代码块,则按照声明的先后顺序执行 * >非静态代码块内可以调用静态的属性、静态的方法,或非静态的属性、非静态的方法 * */ public class BlockTest { public static void main(String[] args) { String desc = Person.desc; System.out.println(desc); Person p1 = new Person(); Person p2 = new Person(); System.out.println(p1.age); Person.info(); } } class Person{ //属性 String name; int age; static String desc = "我是一个人"; //构造器 public Person(){ } public Person(String name,int age){ this.name = name; this.age = age; } //非static的代码块 { System.out.println("hello, block - 2"); } { System.out.println("hello, block - 1"); //调用非静态结构 age = 1; eat(); //调用静态结构 desc = "我是一个爱学习的人1"; info(); } //static的代码块 static{ System.out.println("hello,static block-2"); } static{ System.out.println("hello,static block-1"); //调用静态结构 desc = "我是一个爱学习的人"; info(); //不可以调用非静态结构 // eat(); // name = "Tom"; } //方法 public void eat(){ System.out.println("吃饭"); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public static void info(){ System.out.println("我是一个快乐的人!"); } }
MrChangming/Java
代码块/BlockTest.java
734
//调用非静态结构
line_comment
zh-cn
/* * 类的成员之四:代码块(或初始化块) * * 1. 代码块的作用:用来初始化类、对象 * 2. 代码块如果有修饰的话,只能使用static. * 3. 分类:静态代码块 vs 非静态代码块 * * 4. 静态代码块 * >内部可以有输出语句 * >随着类的加载而执行,而且只执行一次 * >作用:初始化类的信息 * >如果一个类中定义了多个静态代码块,则按照声明的先后顺序执行 * >静态代码块的执行要优先于非静态代码块的执行 * >静态代码块内只能调用静态的属性、静态的方法,不能调用非静态的结构 * * 5. 非静态代码块 * >内部可以有输出语句 * >随着对象的创建而执行 * >每创建一个对象,就执行一次非静态代码块 * >作用:可以在创建对象时,对对象的属性等进行初始化 * >如果一个类中定义了多个非静态代码块,则按照声明的先后顺序执行 * >非静态代码块内可以调用静态的属性、静态的方法,或非静态的属性、非静态的方法 * */ public class BlockTest { public static void main(String[] args) { String desc = Person.desc; System.out.println(desc); Person p1 = new Person(); Person p2 = new Person(); System.out.println(p1.age); Person.info(); } } class Person{ //属性 String name; int age; static String desc = "我是一个人"; //构造器 public Person(){ } public Person(String name,int age){ this.name = name; this.age = age; } //非static的代码块 { System.out.println("hello, block - 2"); } { System.out.println("hello, block - 1"); //调用 <SUF> age = 1; eat(); //调用静态结构 desc = "我是一个爱学习的人1"; info(); } //static的代码块 static{ System.out.println("hello,static block-2"); } static{ System.out.println("hello,static block-1"); //调用静态结构 desc = "我是一个爱学习的人"; info(); //不可以调用非静态结构 // eat(); // name = "Tom"; } //方法 public void eat(){ System.out.println("吃饭"); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } public static void info(){ System.out.println("我是一个快乐的人!"); } }
true
55380_8
package com.ourbuaa.buaahelper; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.text.Html; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; public class DetailActivity extends Activity implements View.OnClickListener { private static SQLiteUtils SQLiteLink; public static void setSQLiteLink(SQLiteUtils link) { SQLiteLink = link; } protected long id; private boolean FAV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(android.R.style.Theme_Light_NoTitleBar); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_detail); TextView textView_Detail_title = (TextView) findViewById(R.id.Detail_title); TextView textView_Detail_updateat = (TextView) findViewById(R.id.Detail_updateat); TextView textView_Detail_content = (TextView) findViewById(R.id.Detail_content); final ImageButton Fav = (ImageButton) findViewById(R.id.fav); ImageButton getNext, getLast, ReturnToMain; getNext = (ImageButton) findViewById(R.id.getNext); getLast = (ImageButton) findViewById(R.id.getBefore); RelativeLayout Bottom_bar = (RelativeLayout) findViewById(R.id.bottom_bar_detail_act); ReturnToMain = (ImageButton) findViewById(R.id.goback); ReturnToMain.setOnClickListener(this); //Button button = (Button) findViewById(R.id.back); //button.setOnClickListener(this); Bundle bundle = getIntent().getExtras(); //BUAAItemTouchHelperCallback buaaItemTouchHelperCallback = NoticeListFragment.buaaItemTouchHelperCallback; //textView.setText("Position:" + bundle.getInt("Position") + " "+"ID:"+bundle.getLong("ID")+" "); id = bundle.getLong("ID"); String t = SQLiteLink.GetNotificationByID(id); try { JSONObject j = new JSONObject(t); textView_Detail_title.setText(j.getString("title")); textView_Detail_updateat.setText(SQLiteUtils.TimeStamp2Time(j.getLong("updated_at"))); textView_Detail_content.setText(Html.fromHtml(j.getString("content"))); if (j.getLong("star") == 1) { Fav.setImageResource(R.drawable.ic_star_black_24dp); FAV = true; } else { Fav.setImageResource(R.mipmap.ic_star_border_black_24dp); FAV = false; } /** * j.put("id", cursor.getLong(0)); j.put("updated_at", cursor.getLong(1)); j.put("title", cursor.getString(2)); j.put("author", cursor.getString(3)); j.put("content", cursor.getString(4)); j.put("files", cursor.getString(5)); j.put("star", cursor.getLong(6)); * * */ } catch (JSONException e) { e.printStackTrace(); } //TODO:由于这次讨论的结果是不做上下翻页,这里就留作以后用好了,就是hasMoreXXX方法不用写了(暂时) if (!hasMoreBeforeNotification()) getLast.setVisibility(View.GONE); if (!hasMoreNextNotification()) getNext.setVisibility(View.GONE); if (hasMoreNextNotification() && hasMoreBeforeNotification()) { Bottom_bar.setBackgroundColor(0XEEEEEE); } //TODO:完成以下三个监听事件,从上往下:上一个,下一个,收藏(前两个暂时不写) getLast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasMoreBeforeNotification()) { } } }); getNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasMoreNextNotification()) { } } }); Fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!FAV) { Fav.setImageResource(R.drawable.ic_star_black_24dp); FAV = true; new Thread(new Runnable() { @Override public void run() { ClientUtils.StarNotification(id); } }).start(); //第一次点击,收藏操作 } else { Fav.setImageResource(R.mipmap.ic_star_border_black_24dp); FAV = false; new Thread(new Runnable() { @Override public void run() { ClientUtils.UnstarNotification(id); } }).start(); //第二次点击,取消收藏 } } }); } @Override public void onClick(View view) { this.finish(); } private boolean hasMoreBeforeNotification() //TODO:前面是否还有(暂时不写) { return false; } private boolean hasMoreNextNotification() //TODO:后面是否还有(暂时不写) { return false; } }
MrCroxx/BUAAHELPER-DEPRECATED-VERSION
app/backup/DetailActivity.java
1,283
//第二次点击,取消收藏
line_comment
zh-cn
package com.ourbuaa.buaahelper; import android.app.Activity; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.helper.ItemTouchHelper; import android.text.Html; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; public class DetailActivity extends Activity implements View.OnClickListener { private static SQLiteUtils SQLiteLink; public static void setSQLiteLink(SQLiteUtils link) { SQLiteLink = link; } protected long id; private boolean FAV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(android.R.style.Theme_Light_NoTitleBar); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_detail); TextView textView_Detail_title = (TextView) findViewById(R.id.Detail_title); TextView textView_Detail_updateat = (TextView) findViewById(R.id.Detail_updateat); TextView textView_Detail_content = (TextView) findViewById(R.id.Detail_content); final ImageButton Fav = (ImageButton) findViewById(R.id.fav); ImageButton getNext, getLast, ReturnToMain; getNext = (ImageButton) findViewById(R.id.getNext); getLast = (ImageButton) findViewById(R.id.getBefore); RelativeLayout Bottom_bar = (RelativeLayout) findViewById(R.id.bottom_bar_detail_act); ReturnToMain = (ImageButton) findViewById(R.id.goback); ReturnToMain.setOnClickListener(this); //Button button = (Button) findViewById(R.id.back); //button.setOnClickListener(this); Bundle bundle = getIntent().getExtras(); //BUAAItemTouchHelperCallback buaaItemTouchHelperCallback = NoticeListFragment.buaaItemTouchHelperCallback; //textView.setText("Position:" + bundle.getInt("Position") + " "+"ID:"+bundle.getLong("ID")+" "); id = bundle.getLong("ID"); String t = SQLiteLink.GetNotificationByID(id); try { JSONObject j = new JSONObject(t); textView_Detail_title.setText(j.getString("title")); textView_Detail_updateat.setText(SQLiteUtils.TimeStamp2Time(j.getLong("updated_at"))); textView_Detail_content.setText(Html.fromHtml(j.getString("content"))); if (j.getLong("star") == 1) { Fav.setImageResource(R.drawable.ic_star_black_24dp); FAV = true; } else { Fav.setImageResource(R.mipmap.ic_star_border_black_24dp); FAV = false; } /** * j.put("id", cursor.getLong(0)); j.put("updated_at", cursor.getLong(1)); j.put("title", cursor.getString(2)); j.put("author", cursor.getString(3)); j.put("content", cursor.getString(4)); j.put("files", cursor.getString(5)); j.put("star", cursor.getLong(6)); * * */ } catch (JSONException e) { e.printStackTrace(); } //TODO:由于这次讨论的结果是不做上下翻页,这里就留作以后用好了,就是hasMoreXXX方法不用写了(暂时) if (!hasMoreBeforeNotification()) getLast.setVisibility(View.GONE); if (!hasMoreNextNotification()) getNext.setVisibility(View.GONE); if (hasMoreNextNotification() && hasMoreBeforeNotification()) { Bottom_bar.setBackgroundColor(0XEEEEEE); } //TODO:完成以下三个监听事件,从上往下:上一个,下一个,收藏(前两个暂时不写) getLast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasMoreBeforeNotification()) { } } }); getNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (hasMoreNextNotification()) { } } }); Fav.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (!FAV) { Fav.setImageResource(R.drawable.ic_star_black_24dp); FAV = true; new Thread(new Runnable() { @Override public void run() { ClientUtils.StarNotification(id); } }).start(); //第一次点击,收藏操作 } else { Fav.setImageResource(R.mipmap.ic_star_border_black_24dp); FAV = false; new Thread(new Runnable() { @Override public void run() { ClientUtils.UnstarNotification(id); } }).start(); //第二 <SUF> } } }); } @Override public void onClick(View view) { this.finish(); } private boolean hasMoreBeforeNotification() //TODO:前面是否还有(暂时不写) { return false; } private boolean hasMoreNextNotification() //TODO:后面是否还有(暂时不写) { return false; } }
true
35122_6
package nlpDemo; import com.hankcs.hanlp.classification.classifiers.IClassifier; import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier; import com.hankcs.hanlp.classification.models.NaiveBayesModel; import com.hankcs.hanlp.corpus.io.IOUtil; import java.io.File; import java.io.IOException; /** * 第一个demo,演示文本分类最基本的调用方式 * * @author hankcs */ public class DemoTextClassification { /** * 搜狗文本分类语料库5个类目,每个类目下1000篇文章,共计5000篇文章 */ public static final String CORPUS_FOLDER = TestUtility.ensureTestData("搜狗文本分类语料库迷你版", "http://file.hankcs.com/corpus/sogou-text-classification-corpus-mini.zip"); /** * 模型保存路径 */ public static final String MODEL_PATH = "data/test/classification-model.ser"; public static void main(String[] args) throws IOException { IClassifier classifier = new NaiveBayesClassifier(trainOrLoadModel()); predict(classifier, "C罗获2018环球足球奖最佳球员 德尚荣膺最佳教练"); predict(classifier, "英国造航母耗时8年仍未服役 被中国速度远远甩在身后"); predict(classifier, "研究生考录模式亟待进一步专业化"); predict(classifier, "如果真想用食物解压,建议可以食用燕麦"); predict(classifier, "通用及其部分竞争对手目前正在考虑解决库存问题"); predict(classifier,"那个客服人员一点都不客气"); } private static void predict(IClassifier classifier, String text) { System.out.printf("《%s》 属于分类 【%s】\n", text, classifier.classify(text)); } private static NaiveBayesModel trainOrLoadModel() throws IOException { NaiveBayesModel model = (NaiveBayesModel) IOUtil.readObjectFrom(MODEL_PATH); if (model != null) return model; File corpusFolder = new File(CORPUS_FOLDER); if (!corpusFolder.exists() || !corpusFolder.isDirectory()) { System.err.println("没有文本分类语料,请阅读IClassifier.train(java.lang.String)中定义的语料格式与语料下载:" + "https://github.com/hankcs/HanLP/wiki/%E6%96%87%E6%9C%AC%E5%88%86%E7%B1%BB%E4%B8%8E%E6%83%85%E6%84%9F%E5%88%86%E6%9E%90"); System.exit(1); } IClassifier classifier = new NaiveBayesClassifier(); // 创建分类器,更高级的功能请参考IClassifier的接口定义 classifier.train(CORPUS_FOLDER); // 训练后的模型支持持久化,下次就不必训练了 model = (NaiveBayesModel) classifier.getModel(); IOUtil.saveObjectTo(model, MODEL_PATH); return model; } }
MrEric125/louis-coub
hanlpmodule/src/main/java/nlpDemo/DemoTextClassification.java
829
// 训练后的模型支持持久化,下次就不必训练了
line_comment
zh-cn
package nlpDemo; import com.hankcs.hanlp.classification.classifiers.IClassifier; import com.hankcs.hanlp.classification.classifiers.NaiveBayesClassifier; import com.hankcs.hanlp.classification.models.NaiveBayesModel; import com.hankcs.hanlp.corpus.io.IOUtil; import java.io.File; import java.io.IOException; /** * 第一个demo,演示文本分类最基本的调用方式 * * @author hankcs */ public class DemoTextClassification { /** * 搜狗文本分类语料库5个类目,每个类目下1000篇文章,共计5000篇文章 */ public static final String CORPUS_FOLDER = TestUtility.ensureTestData("搜狗文本分类语料库迷你版", "http://file.hankcs.com/corpus/sogou-text-classification-corpus-mini.zip"); /** * 模型保存路径 */ public static final String MODEL_PATH = "data/test/classification-model.ser"; public static void main(String[] args) throws IOException { IClassifier classifier = new NaiveBayesClassifier(trainOrLoadModel()); predict(classifier, "C罗获2018环球足球奖最佳球员 德尚荣膺最佳教练"); predict(classifier, "英国造航母耗时8年仍未服役 被中国速度远远甩在身后"); predict(classifier, "研究生考录模式亟待进一步专业化"); predict(classifier, "如果真想用食物解压,建议可以食用燕麦"); predict(classifier, "通用及其部分竞争对手目前正在考虑解决库存问题"); predict(classifier,"那个客服人员一点都不客气"); } private static void predict(IClassifier classifier, String text) { System.out.printf("《%s》 属于分类 【%s】\n", text, classifier.classify(text)); } private static NaiveBayesModel trainOrLoadModel() throws IOException { NaiveBayesModel model = (NaiveBayesModel) IOUtil.readObjectFrom(MODEL_PATH); if (model != null) return model; File corpusFolder = new File(CORPUS_FOLDER); if (!corpusFolder.exists() || !corpusFolder.isDirectory()) { System.err.println("没有文本分类语料,请阅读IClassifier.train(java.lang.String)中定义的语料格式与语料下载:" + "https://github.com/hankcs/HanLP/wiki/%E6%96%87%E6%9C%AC%E5%88%86%E7%B1%BB%E4%B8%8E%E6%83%85%E6%84%9F%E5%88%86%E6%9E%90"); System.exit(1); } IClassifier classifier = new NaiveBayesClassifier(); // 创建分类器,更高级的功能请参考IClassifier的接口定义 classifier.train(CORPUS_FOLDER); // 训练 <SUF> model = (NaiveBayesModel) classifier.getModel(); IOUtil.saveObjectTo(model, MODEL_PATH); return model; } }
true
41425_1
package com.jian8.juc.lock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取共享资源应该可以同时进行。 * 但是 * 如果有一个线程象取写共享资源来,就不应该自由其他线程可以对资源进行读或写 * 总结 * 读读能共存 * 读写不能共存 * 写写不能共存 */ public class ReadWriteLockDemo { public static void main(String[] args) { MyCache myCache = new MyCache(); for (int i = 1; i <= 5; i++) { final int tempInt = i; new Thread(() -> { myCache.put(tempInt + "", tempInt + ""); }, "Thread " + i).start(); } for (int i = 1; i <= 5; i++) { final int tempInt = i; new Thread(() -> { myCache.get(tempInt + ""); }, "Thread " + i).start(); } for (int i = 1; i <= 5; i++) { final int tempInt = i; new Thread(() -> { myCache.put(tempInt + "", tempInt * 2); }, "Thread====" + i).start(); } } } class MyCache { private volatile Map<String, Object> map = new HashMap<>(); private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); /** * 写操作:原子+独占 * 整个过程必须是一个完整的统一体,中间不许被分割,不许被打断 * * @param key * @param value */ public void put(String key, Object value) { rwLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + "\t正在写入:" + key); TimeUnit.MILLISECONDS.sleep(300); map.put(key, value); System.out.println(Thread.currentThread().getName() + "\t写入完成"); } catch (Exception e) { e.printStackTrace(); } finally { rwLock.writeLock().unlock(); } } public void get(String key) { rwLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "\t正在读取:" + key); TimeUnit.MILLISECONDS.sleep(3000); Object result = map.get(key); System.out.println(Thread.currentThread().getName() + "\t读取完成: " + result); } catch (Exception e) { e.printStackTrace(); } finally { rwLock.readLock().unlock(); } } public void clear() { map.clear(); } }
MrJian8/ThreadDemo
src/main/java/com/jian8/juc/lock/ReadWriteLockDemo.java
694
/** * 写操作:原子+独占 * 整个过程必须是一个完整的统一体,中间不许被分割,不许被打断 * * @param key * @param value */
block_comment
zh-cn
package com.jian8.juc.lock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * 多个线程同时读一个资源类没有任何问题,所以为了满足并发量,读取共享资源应该可以同时进行。 * 但是 * 如果有一个线程象取写共享资源来,就不应该自由其他线程可以对资源进行读或写 * 总结 * 读读能共存 * 读写不能共存 * 写写不能共存 */ public class ReadWriteLockDemo { public static void main(String[] args) { MyCache myCache = new MyCache(); for (int i = 1; i <= 5; i++) { final int tempInt = i; new Thread(() -> { myCache.put(tempInt + "", tempInt + ""); }, "Thread " + i).start(); } for (int i = 1; i <= 5; i++) { final int tempInt = i; new Thread(() -> { myCache.get(tempInt + ""); }, "Thread " + i).start(); } for (int i = 1; i <= 5; i++) { final int tempInt = i; new Thread(() -> { myCache.put(tempInt + "", tempInt * 2); }, "Thread====" + i).start(); } } } class MyCache { private volatile Map<String, Object> map = new HashMap<>(); private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); /** * 写操作 <SUF>*/ public void put(String key, Object value) { rwLock.writeLock().lock(); try { System.out.println(Thread.currentThread().getName() + "\t正在写入:" + key); TimeUnit.MILLISECONDS.sleep(300); map.put(key, value); System.out.println(Thread.currentThread().getName() + "\t写入完成"); } catch (Exception e) { e.printStackTrace(); } finally { rwLock.writeLock().unlock(); } } public void get(String key) { rwLock.readLock().lock(); try { System.out.println(Thread.currentThread().getName() + "\t正在读取:" + key); TimeUnit.MILLISECONDS.sleep(3000); Object result = map.get(key); System.out.println(Thread.currentThread().getName() + "\t读取完成: " + result); } catch (Exception e) { e.printStackTrace(); } finally { rwLock.readLock().unlock(); } } public void clear() { map.clear(); } }
true
25040_3
package com.jackson.common.control; import com.jackson.common.source.CommonSource; import com.jackson.db.po.Proxy; import com.jackson.db.po.Url; import com.jackson.db.service.IDaoService; import com.jackson.db.service.ProxyService; import com.jackson.task.ITask; import com.jackson.reservoir.ProxyPool; import com.jackson.task.CreateTaskThread; import com.jackson.task.proxy.ProxyValidateOkTask; import com.jackson.task.proxy.ProxyValidateTask; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; /** * Created by Jackson on 2016/11/16. * 用来控制验证proxy是否可用的管理类 */ public class ProxyController { private final CommonSource source; private final CreateProxyTestTaskThread createProxyTestTaskThread; private final ScheduledThreadPoolExecutor threadPool; private final ProxyPool proxyPool; private final ProxyService proxyService; private final ProxyService proxyOkService; private boolean isOkServiceEnd = false; private Url url ; private ProxyController(ProxyService proxyService,Url testUrl) { this.proxyService = proxyService; this.url = testUrl; proxyOkService = new ProxyService(proxyService.getTableName() + "_ok", ProxyService.TakeMethod.MAX_SPEED); source = CommonSource.newInstance(); proxyPool = new ProxyPool(); threadPool = source.getThreadPool(); createProxyTestTaskThread = new CreateProxyTestTaskThread(proxyOkService, threadPool); proxyOkService.setDatabaseToQueueHandler(new ProxyService.DatabaseToQueueHandler() { @Override public void handle(List<Proxy> list, LinkedBlockingQueue queue) { if (list.size() == 0 &&queue.size()==0) { if (!createProxyTestTaskThread.isAlive()) { createProxyTestTaskThread.start(); } isOkServiceEnd = true; createProxyTestTaskThread.setService(ProxyController.this.proxyService); } } }); } public static ProxyController newInstance(ProxyService proxyService,Url testUrl){ return new ProxyController(proxyService,testUrl); } private ControlConfig controlConfig; private void initConfig() { if(controlConfig ==null){ controlConfig = getDefaultConfig(); } proxyService.setProxySize(controlConfig.getGetServiceCatchSize()) .setMinProxyCatch(controlConfig.getMinServiceCatch()); proxyOkService.setProxySize(controlConfig.getGetServiceCatchSize()) .setMinProxyCatch(controlConfig.getMinServiceCatch()); createProxyTestTaskThread.setMinTaskCache(controlConfig.getMinTaskCache()) .setMaxTaskCache(controlConfig.getMaxTaskCache()); threadPool.setCorePoolSize(controlConfig.getCorePoolSize()); } private void setControlConfig(ControlConfig controlConfig){ this.controlConfig = controlConfig; } /** * 在调用start()方法之前设置,否则无效 * @param threadSize * @return */ public ProxyController setThreadSize(int threadSize){ ControlConfig controlConfig = ControlConfig.builder() .setCorePoolSize(threadSize) .setMaxTaskCache(2*threadSize) .setMinTaskCache(threadSize+1) .setGetServiceCatchSize(5*threadSize) .setMinServiceCatch(threadSize+1) .build(); setControlConfig(controlConfig); return this; } private ControlConfig getDefaultConfig(){ return ControlConfig.builder() .setCorePoolSize(10) .setMaxTaskCache(80) .setMinTaskCache(20) .setGetServiceCatchSize(100) .setMinServiceCatch(20) .build(); } /** * 添加代理到数据库,非及时插入 * @param proxy */ public void insert(List<Proxy> proxy) { proxyService.insert(proxy); } public void start(){ initConfig(); createProxyTestTaskThread.start(); } public ProxyService getProxyOkService() { return proxyOkService; } /** * 用来创建 从没连接成功的ip 的验证任务 */ private class CreateProxyTestTaskThread extends CreateTaskThread<Proxy>{ public CreateProxyTestTaskThread(IDaoService<Proxy> service, ScheduledThreadPoolExecutor threadPool) { super(service, threadPool); } @Override protected Runnable getTask(Proxy obj) { return getProxyTestTask(obj); } @Override protected long getDelay(Proxy proxy) { return 0; } } private ITask getProxyTestTask(Proxy proxy){ if(isOkServiceEnd){ return new ProxyValidateTask(ProxyController.this,url,proxy); }else { return new ProxyValidateOkTask(ProxyController.this,url,proxy); } } public ProxyService getProxyService() { return proxyService; } /** * @return 存放可用proxy的池子 */ public ProxyPool getProxyPool() { return proxyPool; } public CommonSource getCommonSource() { return source; } }
MrJiao/SpiderJackson
SpiderJackson/src/com/jackson/common/control/ProxyController.java
1,213
/** * 用来创建 从没连接成功的ip 的验证任务 */
block_comment
zh-cn
package com.jackson.common.control; import com.jackson.common.source.CommonSource; import com.jackson.db.po.Proxy; import com.jackson.db.po.Url; import com.jackson.db.service.IDaoService; import com.jackson.db.service.ProxyService; import com.jackson.task.ITask; import com.jackson.reservoir.ProxyPool; import com.jackson.task.CreateTaskThread; import com.jackson.task.proxy.ProxyValidateOkTask; import com.jackson.task.proxy.ProxyValidateTask; import java.util.List; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; /** * Created by Jackson on 2016/11/16. * 用来控制验证proxy是否可用的管理类 */ public class ProxyController { private final CommonSource source; private final CreateProxyTestTaskThread createProxyTestTaskThread; private final ScheduledThreadPoolExecutor threadPool; private final ProxyPool proxyPool; private final ProxyService proxyService; private final ProxyService proxyOkService; private boolean isOkServiceEnd = false; private Url url ; private ProxyController(ProxyService proxyService,Url testUrl) { this.proxyService = proxyService; this.url = testUrl; proxyOkService = new ProxyService(proxyService.getTableName() + "_ok", ProxyService.TakeMethod.MAX_SPEED); source = CommonSource.newInstance(); proxyPool = new ProxyPool(); threadPool = source.getThreadPool(); createProxyTestTaskThread = new CreateProxyTestTaskThread(proxyOkService, threadPool); proxyOkService.setDatabaseToQueueHandler(new ProxyService.DatabaseToQueueHandler() { @Override public void handle(List<Proxy> list, LinkedBlockingQueue queue) { if (list.size() == 0 &&queue.size()==0) { if (!createProxyTestTaskThread.isAlive()) { createProxyTestTaskThread.start(); } isOkServiceEnd = true; createProxyTestTaskThread.setService(ProxyController.this.proxyService); } } }); } public static ProxyController newInstance(ProxyService proxyService,Url testUrl){ return new ProxyController(proxyService,testUrl); } private ControlConfig controlConfig; private void initConfig() { if(controlConfig ==null){ controlConfig = getDefaultConfig(); } proxyService.setProxySize(controlConfig.getGetServiceCatchSize()) .setMinProxyCatch(controlConfig.getMinServiceCatch()); proxyOkService.setProxySize(controlConfig.getGetServiceCatchSize()) .setMinProxyCatch(controlConfig.getMinServiceCatch()); createProxyTestTaskThread.setMinTaskCache(controlConfig.getMinTaskCache()) .setMaxTaskCache(controlConfig.getMaxTaskCache()); threadPool.setCorePoolSize(controlConfig.getCorePoolSize()); } private void setControlConfig(ControlConfig controlConfig){ this.controlConfig = controlConfig; } /** * 在调用start()方法之前设置,否则无效 * @param threadSize * @return */ public ProxyController setThreadSize(int threadSize){ ControlConfig controlConfig = ControlConfig.builder() .setCorePoolSize(threadSize) .setMaxTaskCache(2*threadSize) .setMinTaskCache(threadSize+1) .setGetServiceCatchSize(5*threadSize) .setMinServiceCatch(threadSize+1) .build(); setControlConfig(controlConfig); return this; } private ControlConfig getDefaultConfig(){ return ControlConfig.builder() .setCorePoolSize(10) .setMaxTaskCache(80) .setMinTaskCache(20) .setGetServiceCatchSize(100) .setMinServiceCatch(20) .build(); } /** * 添加代理到数据库,非及时插入 * @param proxy */ public void insert(List<Proxy> proxy) { proxyService.insert(proxy); } public void start(){ initConfig(); createProxyTestTaskThread.start(); } public ProxyService getProxyOkService() { return proxyOkService; } /** * 用来创 <SUF>*/ private class CreateProxyTestTaskThread extends CreateTaskThread<Proxy>{ public CreateProxyTestTaskThread(IDaoService<Proxy> service, ScheduledThreadPoolExecutor threadPool) { super(service, threadPool); } @Override protected Runnable getTask(Proxy obj) { return getProxyTestTask(obj); } @Override protected long getDelay(Proxy proxy) { return 0; } } private ITask getProxyTestTask(Proxy proxy){ if(isOkServiceEnd){ return new ProxyValidateTask(ProxyController.this,url,proxy); }else { return new ProxyValidateOkTask(ProxyController.this,url,proxy); } } public ProxyService getProxyService() { return proxyService; } /** * @return 存放可用proxy的池子 */ public ProxyPool getProxyPool() { return proxyPool; } public CommonSource getCommonSource() { return source; } }
true
63581_3
package com.performance.main; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; /** * 抽象类 * @author Kiven * 我们首先写一个类,将产生产者和消费者统一为 EndPoint类型的队列。不管是生产者还是消费者, 连接队列的代码都是一样的,这样可以通用一些。 */ public abstract class EndPoint{ public String host = "172.16.217.148"; public Channel channel; public Connection connection; public QueueingConsumer consumer ;; public String QUEUE_NAME = "ABC"; public String EXCHANGE_NAME = "ABC"; public String ROUTINGKEY = "ABC"; public EndPoint() throws IOException{ //Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //hostname of your rabbitmq server factory.setHost(host); // 创建一个新的消息队列服务器实体的连接 connection = factory.newConnection(); // 创建一个新的消息读写的通道 channel = connection.createChannel(); // 声明exchange模式并且为持久化exchange channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); channel.queueDeclare(QUEUE_NAME, true, false, false, null); //绑定 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTINGKEY); } /** * 关闭channel和connection。并非必须,因为隐含是自动调用的。 * @throws IOException */ public void close() throws IOException{ this.channel.close(); this.connection.close(); } }
MrKiven/rabbitmq-performance-test
RabbitMQ/src/com/performance/main/EndPoint.java
412
// 创建一个新的消息队列服务器实体的连接
line_comment
zh-cn
package com.performance.main; import java.io.IOException; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.QueueingConsumer; /** * 抽象类 * @author Kiven * 我们首先写一个类,将产生产者和消费者统一为 EndPoint类型的队列。不管是生产者还是消费者, 连接队列的代码都是一样的,这样可以通用一些。 */ public abstract class EndPoint{ public String host = "172.16.217.148"; public Channel channel; public Connection connection; public QueueingConsumer consumer ;; public String QUEUE_NAME = "ABC"; public String EXCHANGE_NAME = "ABC"; public String ROUTINGKEY = "ABC"; public EndPoint() throws IOException{ //Create a connection factory ConnectionFactory factory = new ConnectionFactory(); //hostname of your rabbitmq server factory.setHost(host); // 创建 <SUF> connection = factory.newConnection(); // 创建一个新的消息读写的通道 channel = connection.createChannel(); // 声明exchange模式并且为持久化exchange channel.exchangeDeclare(EXCHANGE_NAME, "topic", true); channel.queueDeclare(QUEUE_NAME, true, false, false, null); //绑定 channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTINGKEY); } /** * 关闭channel和connection。并非必须,因为隐含是自动调用的。 * @throws IOException */ public void close() throws IOException{ this.channel.close(); this.connection.close(); } }
true
5396_2
package Linked_List.easy; import Construct.ListNode; import java.util.HashSet; import java.util.Set; /** * @author: Junlin Chen * @Date: 2020/06/30 15:21 * @Describe: 快慢指针判断链表环 */ public class Linked_List_Cycle_141 { public boolean hasCycle3(ListNode head) { Set<ListNode> nodeSet=new HashSet<>(); while (head != null){ nodeSet.add(head); head=head.next; if (nodeSet.contains(head)) return true; } return false; } /* 官方 */ public boolean hasCycle2(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; // 因为判断条件为 != 所以要为.next while (slow != fast) { if (fast == null || fast.next == null) { return false; } slow = slow.next; fast = fast.next.next; } return true; } /* 注意这个因为只是环,判断,不用找中间结点 100 + 65 */ public boolean hasCycle(ListNode head) { if (head==null) return false; ListNode slow=head; // ListNode fast=head.next; 加不加都行,这里不加,因为环会相遇,如果是找中位数要加.next ListNode fast=head; // 保证了 fast.next!=null 那么 fast.next.next=null 没事 ,如果 null.next 就会报错 while (fast!=null && fast.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast) return true; } return false; } }
MrLin7363/leetcode-Lin
src/Linked_List/easy/Linked_List_Cycle_141.java
454
// 因为判断条件为 != 所以要为.next
line_comment
zh-cn
package Linked_List.easy; import Construct.ListNode; import java.util.HashSet; import java.util.Set; /** * @author: Junlin Chen * @Date: 2020/06/30 15:21 * @Describe: 快慢指针判断链表环 */ public class Linked_List_Cycle_141 { public boolean hasCycle3(ListNode head) { Set<ListNode> nodeSet=new HashSet<>(); while (head != null){ nodeSet.add(head); head=head.next; if (nodeSet.contains(head)) return true; } return false; } /* 官方 */ public boolean hasCycle2(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow = head; ListNode fast = head.next; // 因为 <SUF> while (slow != fast) { if (fast == null || fast.next == null) { return false; } slow = slow.next; fast = fast.next.next; } return true; } /* 注意这个因为只是环,判断,不用找中间结点 100 + 65 */ public boolean hasCycle(ListNode head) { if (head==null) return false; ListNode slow=head; // ListNode fast=head.next; 加不加都行,这里不加,因为环会相遇,如果是找中位数要加.next ListNode fast=head; // 保证了 fast.next!=null 那么 fast.next.next=null 没事 ,如果 null.next 就会报错 while (fast!=null && fast.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast) return true; } return false; } }
true
24362_3
package leetcode.simple.array; /** * @author [email protected] * @link <a>https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/</a> * @date 2018/7/29 下午4:15 */ public class BestTimeToBuyAndSellStock { public static void main(String[] args) { int[] prices = {7,1,5,3,6,4}; System.out.println(new BestTimeToBuyAndSellStock().maxProfitDp(prices , 0)); System.out.println(new BestTimeToBuyAndSellStock().maxProfit(prices)); } /** * 个人解法:(dp or 分治) 如果在第一天买入,则寻找最大差价;如果没有第一天买,则递归 * 131ms 23.61% * @param prices * @return */ public int maxProfitDp(int[] prices, int start) { // 递归结束 if (start >= prices.length - 1) { return 0; } // 第一天没有买,递归 int maxNot = maxProfitDp(prices, start + 1); // 第一天买了,求最大差 int maxYes = 0; int maxSub = 0; for (int i = start + 1; i < prices.length; i++) { maxSub = prices[i] - prices[start]; if (maxYes < maxSub) { maxYes = maxSub; } } return maxYes > maxNot ? maxYes : maxNot; } /** * 个人解法:买入的那天如果后面遇见价格更低的 肯定要重新选择 买入价格更低的那天 作为新的买入进行继续向后算 * 1ms 99.92% */ public int maxProfit(int[] prices) { int maxValue = 0; int sub = 0, start = 0; for (int i = 1; i < prices.length; i++) { sub = prices[i] - prices[start]; if (sub > maxValue) { maxValue = sub; } if (sub < 0) { start = i; } } return maxValue; } }
MrSorrow/cc-leetcode
src/leetcode/simple/array/BestTimeToBuyAndSellStock.java
601
// 第一天没有买,递归
line_comment
zh-cn
package leetcode.simple.array; /** * @author [email protected] * @link <a>https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/description/</a> * @date 2018/7/29 下午4:15 */ public class BestTimeToBuyAndSellStock { public static void main(String[] args) { int[] prices = {7,1,5,3,6,4}; System.out.println(new BestTimeToBuyAndSellStock().maxProfitDp(prices , 0)); System.out.println(new BestTimeToBuyAndSellStock().maxProfit(prices)); } /** * 个人解法:(dp or 分治) 如果在第一天买入,则寻找最大差价;如果没有第一天买,则递归 * 131ms 23.61% * @param prices * @return */ public int maxProfitDp(int[] prices, int start) { // 递归结束 if (start >= prices.length - 1) { return 0; } // 第一 <SUF> int maxNot = maxProfitDp(prices, start + 1); // 第一天买了,求最大差 int maxYes = 0; int maxSub = 0; for (int i = start + 1; i < prices.length; i++) { maxSub = prices[i] - prices[start]; if (maxYes < maxSub) { maxYes = maxSub; } } return maxYes > maxNot ? maxYes : maxNot; } /** * 个人解法:买入的那天如果后面遇见价格更低的 肯定要重新选择 买入价格更低的那天 作为新的买入进行继续向后算 * 1ms 99.92% */ public int maxProfit(int[] prices) { int maxValue = 0; int sub = 0, start = 0; for (int i = 1; i < prices.length; i++) { sub = prices[i] - prices[start]; if (sub > maxValue) { maxValue = sub; } if (sub < 0) { start = i; } } return maxValue; } }
true
48944_8
package problem_2_8; /*** 有9个因数的数 描述 Find the count of numbers less than N having exactly 9 divisors 1<=T<=1000,1<=N<=10^12 输入 First Line of Input contains the number of testcases. Only Line of each testcase contains the number of members N in the rival gang. 输出 Print the desired output. 输入样例 1 2 40 5 输出样例 1 1 0 思路: 对于这一类求 有n个因数的数 的题目,其本质是数学问题,即分解质因数 —— 任何一个正整数均可以分解为任意多个质数的次方乘积的形式,0和1不是质数 !!!!!Eg: N = P1 ^ a1 * P2 ^ a2 * ... * Pn ^ an,其中P1到Pn为互不相同的质数,a1到an为各自的次方数,分解之后 N 有 (a1 + 1) * (a2 + 1) * ... *(an + 1)个因数!!!!! 因此若求10个因数的数,要么:(1)(a1 + 1)*(a2 + 1)*...*(an + 1) = 10,而积为10的组合数只有2 * 5,因此a1 = 1, a2 = 4,那么N = P1 ^ 1 * P2 ^ 4; 要么: (2) N = P1 ^ 9,则N的10个因数为P1 ^ 0, P1 ^ 1,...P1 ^ 9共10个; 求某个范围内的素数的方法:(1)埃及筛选(假设初始全为素数,0 1除外,若扫描到为素数则将所有倍数改为非素数) (2)欧式筛选(设置非素数标记数组和储存素数数组,对当前扫描的数 * 已有素数表中所有素数 设为非素数,和素数的倍数为非素数一样的道理) https://blog.csdn.net/timelessx_x/article/details/112059930 */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; class Main { private static int[] prime = new int[1000000]; private static int primeIdx; public static void main(String[] args) throws FileNotFoundException { // Common input process //Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(new FileInputStream("C:\\Users\\97267\\Desktop\\input.txt")); int caseNum = sc.nextInt(); for(int caseIndex = 0; caseIndex < caseNum; caseIndex++) { long max = sc.nextLong(); // Process calPrimeArr((int)Math.sqrt(max)); System.out.print(getRequiredCnt(max)); if(caseIndex != caseNum - 1) System.out.print("\n"); } } // 求[2,max]内的素数存入prime数组,此处采用埃及筛选,即将所有素数的倍数均改为非素数 private static void calPrimeArr(int max) { // 用于存储是否为素数,先初始化全为0即首先假设全为素数,后续再对素数的倍数修改为1代表非素数 int[] isPrime = new int[max + 1]; // 0 1非素数 isPrime[0] = 1; isPrime[1] = 1; primeIdx = 0; for(int i = 2; i <= max; i++) { if(isPrime[i] == 0) { // 将i记录进素数数组 prime[primeIdx++] = i; // 素数的倍数为非素数 for(int j = 2; i * j <= max; j++) { isPrime[i * j] = 1; } } } } private static int getRequiredCnt(long max) { int res = 0; // 1.计算两个素数的平方积是否小于max,采用双指针扫描对所有素数两两互异组合 for(int i = 0; i < primeIdx - 1; i++) { for(int j = i + 1; j < primeIdx; j++) { if(Math.pow(prime[i], 2) * Math.pow(prime[j], 2) < max) res++; else break; } } // 2.计算素数的8次方是否小于max for(int i = 0; i < primeIdx && Math.pow(prime[i], 8) < max; i++) res++; return res; } }
MrVanGoghYang/Nju_AdvancedAlgorithm
src/problem_2_8/Main.java
1,200
// 素数的倍数为非素数
line_comment
zh-cn
package problem_2_8; /*** 有9个因数的数 描述 Find the count of numbers less than N having exactly 9 divisors 1<=T<=1000,1<=N<=10^12 输入 First Line of Input contains the number of testcases. Only Line of each testcase contains the number of members N in the rival gang. 输出 Print the desired output. 输入样例 1 2 40 5 输出样例 1 1 0 思路: 对于这一类求 有n个因数的数 的题目,其本质是数学问题,即分解质因数 —— 任何一个正整数均可以分解为任意多个质数的次方乘积的形式,0和1不是质数 !!!!!Eg: N = P1 ^ a1 * P2 ^ a2 * ... * Pn ^ an,其中P1到Pn为互不相同的质数,a1到an为各自的次方数,分解之后 N 有 (a1 + 1) * (a2 + 1) * ... *(an + 1)个因数!!!!! 因此若求10个因数的数,要么:(1)(a1 + 1)*(a2 + 1)*...*(an + 1) = 10,而积为10的组合数只有2 * 5,因此a1 = 1, a2 = 4,那么N = P1 ^ 1 * P2 ^ 4; 要么: (2) N = P1 ^ 9,则N的10个因数为P1 ^ 0, P1 ^ 1,...P1 ^ 9共10个; 求某个范围内的素数的方法:(1)埃及筛选(假设初始全为素数,0 1除外,若扫描到为素数则将所有倍数改为非素数) (2)欧式筛选(设置非素数标记数组和储存素数数组,对当前扫描的数 * 已有素数表中所有素数 设为非素数,和素数的倍数为非素数一样的道理) https://blog.csdn.net/timelessx_x/article/details/112059930 */ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.*; class Main { private static int[] prime = new int[1000000]; private static int primeIdx; public static void main(String[] args) throws FileNotFoundException { // Common input process //Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(new FileInputStream("C:\\Users\\97267\\Desktop\\input.txt")); int caseNum = sc.nextInt(); for(int caseIndex = 0; caseIndex < caseNum; caseIndex++) { long max = sc.nextLong(); // Process calPrimeArr((int)Math.sqrt(max)); System.out.print(getRequiredCnt(max)); if(caseIndex != caseNum - 1) System.out.print("\n"); } } // 求[2,max]内的素数存入prime数组,此处采用埃及筛选,即将所有素数的倍数均改为非素数 private static void calPrimeArr(int max) { // 用于存储是否为素数,先初始化全为0即首先假设全为素数,后续再对素数的倍数修改为1代表非素数 int[] isPrime = new int[max + 1]; // 0 1非素数 isPrime[0] = 1; isPrime[1] = 1; primeIdx = 0; for(int i = 2; i <= max; i++) { if(isPrime[i] == 0) { // 将i记录进素数数组 prime[primeIdx++] = i; // 素数 <SUF> for(int j = 2; i * j <= max; j++) { isPrime[i * j] = 1; } } } } private static int getRequiredCnt(long max) { int res = 0; // 1.计算两个素数的平方积是否小于max,采用双指针扫描对所有素数两两互异组合 for(int i = 0; i < primeIdx - 1; i++) { for(int j = i + 1; j < primeIdx; j++) { if(Math.pow(prime[i], 2) * Math.pow(prime[j], 2) < max) res++; else break; } } // 2.计算素数的8次方是否小于max for(int i = 0; i < primeIdx && Math.pow(prime[i], 8) < max; i++) res++; return res; } }
true
64448_3
package com.hansheng.csdnspider; import java.util.List; /** * Created by hansheng on 2016/7/14. */ public class Text { public static void main(String... args){ NewsItemBiz biz = new NewsItemBiz(); int currentPage = 1; try { /** * 业界 */ List<NewsItem> newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YEJIE, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 程序员杂志 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_CHENGXUYUAN, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 研发 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YANFA, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 移动 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YIDONG, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); } catch (CommonException e) { e.printStackTrace(); } } }
MrWu94/AndroidNote
java/src/main/java/com/hansheng/csdnspider/Text.java
371
/** * 研发 */
block_comment
zh-cn
package com.hansheng.csdnspider; import java.util.List; /** * Created by hansheng on 2016/7/14. */ public class Text { public static void main(String... args){ NewsItemBiz biz = new NewsItemBiz(); int currentPage = 1; try { /** * 业界 */ List<NewsItem> newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YEJIE, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 程序员杂志 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_CHENGXUYUAN, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 研发 <SUF>*/ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YANFA, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 移动 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YIDONG, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); } catch (CommonException e) { e.printStackTrace(); } } }
false
24535_3
package base; import android.os.Bundle; import android.os.Looper; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.okhttplib.HttpInfo; import com.okhttplib.OkHttpUtil; import com.okhttplib.callback.Callback; import java.io.IOException; import base.view.LoadingDialog; /** * Activity基类:支持网络请求、加载提示框 * @author zhousf */ public class HttpActivity extends AppCompatActivity implements BaseHandler.CallBack { private BaseHandler mainHandler; private LoadingDialog loadingDialog;//加载提示框 private final int SHOW_DIALOG = 0x001; private final int DISMISS_DIALOG = 0x002; private final int LOAD_SUCCEED = 0x003; private final int LOAD_FAILED = 0x004; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * 同步请求 * @param info 请求信息体 * @return HttpInfo */ protected HttpInfo doHttpSync(HttpInfo info) { //显示加载框 getMainHandler().sendEmptyMessage(SHOW_DIALOG); info = OkHttpUtil.getDefault(this).doSync(info); if(info.isSuccessful()){ //显示加载成功 getMainHandler().sendEmptyMessage(LOAD_SUCCEED); }else { //显示加载失败 getMainHandler().sendEmptyMessage(LOAD_FAILED); } //隐藏加载框 getMainHandler().sendEmptyMessageDelayed(DISMISS_DIALOG,1000); return info; } /** * 异步请求 * @param info 请求信息体 * @param callback 结果回调接口 */ protected void doHttpAsync(HttpInfo info, final Callback callback){ getMainHandler().sendEmptyMessage(SHOW_DIALOG); OkHttpUtil.getDefault(this).doAsync(info, new Callback() { @Override public void onSuccess(HttpInfo info) throws IOException { getLoadingDialog().dismiss(); callback.onSuccess(info); } @Override public void onFailure(HttpInfo info) throws IOException { getLoadingDialog().dismiss(); callback.onFailure(info); } }); } protected LoadingDialog getLoadingDialog(){ if(null == loadingDialog){ loadingDialog = new LoadingDialog(this); //点击空白处Dialog不消失 loadingDialog.setCanceledOnTouchOutside(false); } return loadingDialog; } /** * 获取通用句柄,自动释放 */ protected BaseHandler getMainHandler(){ if(null == mainHandler){ mainHandler = new BaseHandler(this, Looper.getMainLooper()); } return mainHandler; } @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_DIALOG: getLoadingDialog().showDialog(); break; case LOAD_SUCCEED: getLoadingDialog().succeed(); break; case LOAD_FAILED: getLoadingDialog().failed(); break; case DISMISS_DIALOG: getLoadingDialog().dismiss(); break; default: break; } } @Override protected void onDestroy() { if(null != mainHandler) mainHandler.removeCallbacksAndMessages(null); super.onDestroy(); } }
MrZhousf/OkHttp3
app/src/main/java/base/HttpActivity.java
794
//显示加载框
line_comment
zh-cn
package base; import android.os.Bundle; import android.os.Looper; import android.os.Message; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import com.okhttplib.HttpInfo; import com.okhttplib.OkHttpUtil; import com.okhttplib.callback.Callback; import java.io.IOException; import base.view.LoadingDialog; /** * Activity基类:支持网络请求、加载提示框 * @author zhousf */ public class HttpActivity extends AppCompatActivity implements BaseHandler.CallBack { private BaseHandler mainHandler; private LoadingDialog loadingDialog;//加载提示框 private final int SHOW_DIALOG = 0x001; private final int DISMISS_DIALOG = 0x002; private final int LOAD_SUCCEED = 0x003; private final int LOAD_FAILED = 0x004; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } /** * 同步请求 * @param info 请求信息体 * @return HttpInfo */ protected HttpInfo doHttpSync(HttpInfo info) { //显示 <SUF> getMainHandler().sendEmptyMessage(SHOW_DIALOG); info = OkHttpUtil.getDefault(this).doSync(info); if(info.isSuccessful()){ //显示加载成功 getMainHandler().sendEmptyMessage(LOAD_SUCCEED); }else { //显示加载失败 getMainHandler().sendEmptyMessage(LOAD_FAILED); } //隐藏加载框 getMainHandler().sendEmptyMessageDelayed(DISMISS_DIALOG,1000); return info; } /** * 异步请求 * @param info 请求信息体 * @param callback 结果回调接口 */ protected void doHttpAsync(HttpInfo info, final Callback callback){ getMainHandler().sendEmptyMessage(SHOW_DIALOG); OkHttpUtil.getDefault(this).doAsync(info, new Callback() { @Override public void onSuccess(HttpInfo info) throws IOException { getLoadingDialog().dismiss(); callback.onSuccess(info); } @Override public void onFailure(HttpInfo info) throws IOException { getLoadingDialog().dismiss(); callback.onFailure(info); } }); } protected LoadingDialog getLoadingDialog(){ if(null == loadingDialog){ loadingDialog = new LoadingDialog(this); //点击空白处Dialog不消失 loadingDialog.setCanceledOnTouchOutside(false); } return loadingDialog; } /** * 获取通用句柄,自动释放 */ protected BaseHandler getMainHandler(){ if(null == mainHandler){ mainHandler = new BaseHandler(this, Looper.getMainLooper()); } return mainHandler; } @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_DIALOG: getLoadingDialog().showDialog(); break; case LOAD_SUCCEED: getLoadingDialog().succeed(); break; case LOAD_FAILED: getLoadingDialog().failed(); break; case DISMISS_DIALOG: getLoadingDialog().dismiss(); break; default: break; } } @Override protected void onDestroy() { if(null != mainHandler) mainHandler.removeCallbacksAndMessages(null); super.onDestroy(); } }
true
4719_0
package com.zzj.blog.pojo; import javax.persistence.*; @Entity @Table(name="t_friend") public class Friend { @Id @GeneratedValue private Long id; private String nickname; private String occupation; private String description; @Basic(fetch = FetchType.LAZY) @Lob private String avatar; private String flag;//大佬,朋友,网站 private String website; public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Friend(String nickname, String occupation, String description, String avatar, String flag) { this.nickname = nickname; this.occupation = occupation; this.description = description; this.avatar = avatar; this.flag = flag; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } @Override public String toString() { return "Friend{" + "id=" + id + ", nickname='" + nickname + '\'' + ", occupation='" + occupation + '\'' + ", description='" + description + '\'' + ", avatar='" + avatar + '\'' + ", flag='" + flag + '\'' + '}'; } public Friend() { } }
Mretron/MyBlogWebSite
src/main/java/com/zzj/blog/pojo/Friend.java
475
//大佬,朋友,网站
line_comment
zh-cn
package com.zzj.blog.pojo; import javax.persistence.*; @Entity @Table(name="t_friend") public class Friend { @Id @GeneratedValue private Long id; private String nickname; private String occupation; private String description; @Basic(fetch = FetchType.LAZY) @Lob private String avatar; private String flag;//大佬 <SUF> private String website; public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Friend(String nickname, String occupation, String description, String avatar, String flag) { this.nickname = nickname; this.occupation = occupation; this.description = description; this.avatar = avatar; this.flag = flag; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } @Override public String toString() { return "Friend{" + "id=" + id + ", nickname='" + nickname + '\'' + ", occupation='" + occupation + '\'' + ", description='" + description + '\'' + ", avatar='" + avatar + '\'' + ", flag='" + flag + '\'' + '}'; } public Friend() { } }
false
57535_16
package com.feng.freader.constant; import com.feng.freader.app.App; import java.util.Arrays; import java.util.List; /** * @author Feng Zhaohao * Created on 2019/11/6 */ public class Constant { /* 热门榜单相关 */ // 男生热门榜单的榜单数 public static final int MALE_HOT_RANK_NUM = 5; // 男生热门榜单的 id private static String sZYHotRankId = "564d8003aca44f4f61850fcd"; // 掌阅热销榜 private static String sSQHotRankId = "564d80457408cfcd63ae2dd0"; // 书旗热搜榜 private static String sZHHotRankId = "54d430962c12d3740e4a3ed2"; // 纵横月票榜 private static String sZLHotRankId = "5732aac02dbb268b5f037fc4"; // 逐浪点击榜 private static String sBDHotRankId = "564ef4f985ed965d0280c9c2"; // 百度热搜榜 public static final List<String> MALE_HOT_RANK_ID = Arrays.asList(sZYHotRankId, sSQHotRankId, sZHHotRankId, sZLHotRankId, sBDHotRankId); // 男生热门榜单的榜单名字 public static final List<String> MALE_HOT_RANK_NAME = Arrays.asList("掌阅热销榜", "书旗热搜榜", "纵横月票榜", "逐浪点击榜", "百度热搜榜"); // 女生热门榜单的榜单数 public static final int FEMALE_HOT_RANK_NUM = 3; // 女生热门榜单的 id private static String sKHotRankId = "550b841715db45cd4b022107"; // 17K订阅榜 private static String sNZYHotRankId = "564d80d0e8c613016446c5aa"; // 掌阅热销榜 private static String sNSQHotRankId = "564d81151109835664770ad7"; // 书旗热搜榜 public static final List<String> FEMALE_HOT_RANK_ID = Arrays.asList( sKHotRankId, sNZYHotRankId, sNSQHotRankId); // 女生热门榜单的榜单名字 public static final List<String> FEMALE_HOT_RANK_NAME = Arrays.asList( "17K订阅榜", "掌阅热销榜", "书旗热搜榜"); /* 错误信息 */ // 小说源 api 没有找到相关小说 public static final String NOT_FOUND_NOVELS = "没有找到相关小说"; // 没有获取到相关目录信息 public static final String NOT_FOUND_CATALOG_INFO = "没有找到相关目录"; // json 格式错误 public static final String JSON_ERROR = "json 格式错误"; // 该小说已从本地删除 public static final String NOT_FOUND_FROM_LOCAL = "该小说已从本地删除"; /* 数据库相关 */ // 数据库名 public static final String DB_NAME = "FReader.db"; // 历史记录表 public static final String TABLE_HISTORY = "TABLE_HISTORY"; // 历史记录表的记录 public static final String TABLE_HISTORY_ID = "TABLE_HISTORY_ID"; // 自增 id(主键) public static final String TABLE_HISTORY_WORD = "TABLE_HISTORY_WORD"; // 搜索词 // 书架书籍表 public static final String TABLE_BOOKSHELF_NOVEL = "TABLE_BOOKSHELF_NOVEL"; // 书架书籍表的记录 public static final String TABLE_BOOKSHELF_NOVEL_NOVEL_URL = "TABLE_BOOKSHELF_NOVEL_NOVEL_URL"; // 小说 URL(主键) public static final String TABLE_BOOKSHELF_NOVEL_NAME = "TABLE_BOOKSHELF_NOVEL_NAME"; // 小说名 public static final String TABLE_BOOKSHELF_NOVEL_COVER = "TABLE_BOOKSHELF_NOVEL_COVER"; // 小说封面 // 章节索引:网络小说和本地 epub 小说为目录索引,本地 txt 小说无需该属性 public static final String TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX = "TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX"; // 位置索引(用于跳转到上一次进度):网络小说和 txt 是 String 文本的位置 public static final String TABLE_BOOKSHELF_NOVEL_POSITION = "TABLE_BOOKSHELF_NOVEL_POSITION"; // 第二位置索引(epub 解析用) public static final String TABLE_BOOKSHELF_NOVEL_SECOND_POSITION = "TABLE_BOOKSHELF_NOVEL_SECOND_POSITION"; // 类型:0 为网络小说, 1 为本地 txt 小说, 2 为本地 epub 小说 public static final String TABLE_BOOKSHELF_NOVEL_TYPE = "TABLE_BOOKSHELF_NOVEL_TYPE"; /* 文件存储 */ public static final String EPUB_SAVE_PATH = App.getContext().getFilesDir() + "/epubFile"; /* 分类小说相关 */ // gender public static final String CATEGORY_GENDER_MALE = "male"; // 男生 public static final String CATEGORY_GENDER_FEMALE = "female"; // 女生 public static final String CATEGORY_GENDER_PRESS = "press"; // 出版 public static final String CATEGORY_GENDER_MALE_TEXT = "男生"; public static final String CATEGORY_GENDER_FEMALE_TEXT = "女生"; public static final String CATEGORY_GENDER_PRESS_TEXT = "出版"; // type public static final String CATEGORY_TYPE_HOT = "hot"; // 热门 public static final String CATEGORY_TYPE_NEW = "new"; // 新书 public static final String CATEGORY_TYPE_REPUTATION = "reputation"; // 好评 public static final String CATEGORY_TYPE_OVER = "over"; // 完结 public static final String CATEGORY_TYPE_MONTH = "month"; // 包月 public static final String CATEGORY_TYPE_HOT_TEXT = "热门"; public static final String CATEGORY_TYPE_NEW_TEXT = "新书"; public static final String CATEGORY_TYPE_REPUTATION_TEXT = "好评"; public static final String CATEGORY_TYPE_OVER_TEXT = "完结"; public static final String CATEGORY_TYPE_MONTH_TEXT = "包月"; // major(男生) public static final String CATEGORY_MAJOR_XH = "玄幻"; public static final String CATEGORY_MAJOR_QH = "奇幻"; public static final String CATEGORY_MAJOR_WX = "武侠"; public static final String CATEGORY_MAJOR_XX = "仙侠"; public static final String CATEGORY_MAJOR_DS = "都市"; public static final String CATEGORY_MAJOR_ZC = "职场"; public static final String CATEGORY_MAJOR_LS = "历史"; public static final String CATEGORY_MAJOR_JS = "军事"; public static final String CATEGORY_MAJOR_YX = "游戏"; public static final String CATEGORY_MAJOR_JJ = "竞技"; public static final String CATEGORY_MAJOR_KH = "科幻"; public static final String CATEGORY_MAJOR_LY = "灵异"; public static final String CATEGORY_MAJOR_TR = "同人"; public static final String CATEGORY_MAJOR_QXS = "轻小说"; // major(女生) public static final String CATEGORY_MAJOR_GDYQ = "古代言情"; public static final String CATEGORY_MAJOR_XDYQ = "现代言情"; public static final String CATEGORY_MAJOR_QCXY = "青春校园"; public static final String CATEGORY_MAJOR_CA = "纯爱"; public static final String CATEGORY_MAJOR_XHQH = "玄幻奇幻"; public static final String CATEGORY_MAJOR_WXXX = "武侠仙侠"; // major(出版) public static final String CATEGORY_MAJOR_CBXS = "出版小说"; public static final String CATEGORY_MAJOR_ZJMZ = "传记名著"; public static final String CATEGORY_MAJOR_CGLZ = "成功励志"; public static final String CATEGORY_MAJOR_RWSK = "人文社科"; public static final String CATEGORY_MAJOR_JGLC = "经管理财"; public static final String CATEGORY_MAJOR_SHSS = "生活时尚"; public static final String CATEGORY_MAJOR_YEJK = "育儿健康"; public static final String CATEGORY_MAJOR_QCYQ = "青春言情"; public static final String CATEGORY_MAJOR_WWYB = "外文原版"; public static final String CATEGORY_MAJOR_ZZJS = "政治军事"; /* 全部小说 */ public static final int NOVEL_PAGE_NUM = 10; // 每页的小说数 }
Mrfzh/FReader
app/src/main/java/com/feng/freader/constant/Constant.java
2,425
/* 错误信息 */
block_comment
zh-cn
package com.feng.freader.constant; import com.feng.freader.app.App; import java.util.Arrays; import java.util.List; /** * @author Feng Zhaohao * Created on 2019/11/6 */ public class Constant { /* 热门榜单相关 */ // 男生热门榜单的榜单数 public static final int MALE_HOT_RANK_NUM = 5; // 男生热门榜单的 id private static String sZYHotRankId = "564d8003aca44f4f61850fcd"; // 掌阅热销榜 private static String sSQHotRankId = "564d80457408cfcd63ae2dd0"; // 书旗热搜榜 private static String sZHHotRankId = "54d430962c12d3740e4a3ed2"; // 纵横月票榜 private static String sZLHotRankId = "5732aac02dbb268b5f037fc4"; // 逐浪点击榜 private static String sBDHotRankId = "564ef4f985ed965d0280c9c2"; // 百度热搜榜 public static final List<String> MALE_HOT_RANK_ID = Arrays.asList(sZYHotRankId, sSQHotRankId, sZHHotRankId, sZLHotRankId, sBDHotRankId); // 男生热门榜单的榜单名字 public static final List<String> MALE_HOT_RANK_NAME = Arrays.asList("掌阅热销榜", "书旗热搜榜", "纵横月票榜", "逐浪点击榜", "百度热搜榜"); // 女生热门榜单的榜单数 public static final int FEMALE_HOT_RANK_NUM = 3; // 女生热门榜单的 id private static String sKHotRankId = "550b841715db45cd4b022107"; // 17K订阅榜 private static String sNZYHotRankId = "564d80d0e8c613016446c5aa"; // 掌阅热销榜 private static String sNSQHotRankId = "564d81151109835664770ad7"; // 书旗热搜榜 public static final List<String> FEMALE_HOT_RANK_ID = Arrays.asList( sKHotRankId, sNZYHotRankId, sNSQHotRankId); // 女生热门榜单的榜单名字 public static final List<String> FEMALE_HOT_RANK_NAME = Arrays.asList( "17K订阅榜", "掌阅热销榜", "书旗热搜榜"); /* 错误信 <SUF>*/ // 小说源 api 没有找到相关小说 public static final String NOT_FOUND_NOVELS = "没有找到相关小说"; // 没有获取到相关目录信息 public static final String NOT_FOUND_CATALOG_INFO = "没有找到相关目录"; // json 格式错误 public static final String JSON_ERROR = "json 格式错误"; // 该小说已从本地删除 public static final String NOT_FOUND_FROM_LOCAL = "该小说已从本地删除"; /* 数据库相关 */ // 数据库名 public static final String DB_NAME = "FReader.db"; // 历史记录表 public static final String TABLE_HISTORY = "TABLE_HISTORY"; // 历史记录表的记录 public static final String TABLE_HISTORY_ID = "TABLE_HISTORY_ID"; // 自增 id(主键) public static final String TABLE_HISTORY_WORD = "TABLE_HISTORY_WORD"; // 搜索词 // 书架书籍表 public static final String TABLE_BOOKSHELF_NOVEL = "TABLE_BOOKSHELF_NOVEL"; // 书架书籍表的记录 public static final String TABLE_BOOKSHELF_NOVEL_NOVEL_URL = "TABLE_BOOKSHELF_NOVEL_NOVEL_URL"; // 小说 URL(主键) public static final String TABLE_BOOKSHELF_NOVEL_NAME = "TABLE_BOOKSHELF_NOVEL_NAME"; // 小说名 public static final String TABLE_BOOKSHELF_NOVEL_COVER = "TABLE_BOOKSHELF_NOVEL_COVER"; // 小说封面 // 章节索引:网络小说和本地 epub 小说为目录索引,本地 txt 小说无需该属性 public static final String TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX = "TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX"; // 位置索引(用于跳转到上一次进度):网络小说和 txt 是 String 文本的位置 public static final String TABLE_BOOKSHELF_NOVEL_POSITION = "TABLE_BOOKSHELF_NOVEL_POSITION"; // 第二位置索引(epub 解析用) public static final String TABLE_BOOKSHELF_NOVEL_SECOND_POSITION = "TABLE_BOOKSHELF_NOVEL_SECOND_POSITION"; // 类型:0 为网络小说, 1 为本地 txt 小说, 2 为本地 epub 小说 public static final String TABLE_BOOKSHELF_NOVEL_TYPE = "TABLE_BOOKSHELF_NOVEL_TYPE"; /* 文件存储 */ public static final String EPUB_SAVE_PATH = App.getContext().getFilesDir() + "/epubFile"; /* 分类小说相关 */ // gender public static final String CATEGORY_GENDER_MALE = "male"; // 男生 public static final String CATEGORY_GENDER_FEMALE = "female"; // 女生 public static final String CATEGORY_GENDER_PRESS = "press"; // 出版 public static final String CATEGORY_GENDER_MALE_TEXT = "男生"; public static final String CATEGORY_GENDER_FEMALE_TEXT = "女生"; public static final String CATEGORY_GENDER_PRESS_TEXT = "出版"; // type public static final String CATEGORY_TYPE_HOT = "hot"; // 热门 public static final String CATEGORY_TYPE_NEW = "new"; // 新书 public static final String CATEGORY_TYPE_REPUTATION = "reputation"; // 好评 public static final String CATEGORY_TYPE_OVER = "over"; // 完结 public static final String CATEGORY_TYPE_MONTH = "month"; // 包月 public static final String CATEGORY_TYPE_HOT_TEXT = "热门"; public static final String CATEGORY_TYPE_NEW_TEXT = "新书"; public static final String CATEGORY_TYPE_REPUTATION_TEXT = "好评"; public static final String CATEGORY_TYPE_OVER_TEXT = "完结"; public static final String CATEGORY_TYPE_MONTH_TEXT = "包月"; // major(男生) public static final String CATEGORY_MAJOR_XH = "玄幻"; public static final String CATEGORY_MAJOR_QH = "奇幻"; public static final String CATEGORY_MAJOR_WX = "武侠"; public static final String CATEGORY_MAJOR_XX = "仙侠"; public static final String CATEGORY_MAJOR_DS = "都市"; public static final String CATEGORY_MAJOR_ZC = "职场"; public static final String CATEGORY_MAJOR_LS = "历史"; public static final String CATEGORY_MAJOR_JS = "军事"; public static final String CATEGORY_MAJOR_YX = "游戏"; public static final String CATEGORY_MAJOR_JJ = "竞技"; public static final String CATEGORY_MAJOR_KH = "科幻"; public static final String CATEGORY_MAJOR_LY = "灵异"; public static final String CATEGORY_MAJOR_TR = "同人"; public static final String CATEGORY_MAJOR_QXS = "轻小说"; // major(女生) public static final String CATEGORY_MAJOR_GDYQ = "古代言情"; public static final String CATEGORY_MAJOR_XDYQ = "现代言情"; public static final String CATEGORY_MAJOR_QCXY = "青春校园"; public static final String CATEGORY_MAJOR_CA = "纯爱"; public static final String CATEGORY_MAJOR_XHQH = "玄幻奇幻"; public static final String CATEGORY_MAJOR_WXXX = "武侠仙侠"; // major(出版) public static final String CATEGORY_MAJOR_CBXS = "出版小说"; public static final String CATEGORY_MAJOR_ZJMZ = "传记名著"; public static final String CATEGORY_MAJOR_CGLZ = "成功励志"; public static final String CATEGORY_MAJOR_RWSK = "人文社科"; public static final String CATEGORY_MAJOR_JGLC = "经管理财"; public static final String CATEGORY_MAJOR_SHSS = "生活时尚"; public static final String CATEGORY_MAJOR_YEJK = "育儿健康"; public static final String CATEGORY_MAJOR_QCYQ = "青春言情"; public static final String CATEGORY_MAJOR_WWYB = "外文原版"; public static final String CATEGORY_MAJOR_ZZJS = "政治军事"; /* 全部小说 */ public static final int NOVEL_PAGE_NUM = 10; // 每页的小说数 }
false
61334_17
package org.secbug.conf; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.secbug.util.ContextUtil; import org.secbug.vo.Feature; import org.secbug.vo.Result; public class Context { public static String[] args; public static String currpath = System.getProperty("user.dir")+"\\feature.json"; public static List<String> urls = new ArrayList<String>(); public static int jobid = 0; public static int i = 0; public static StringBuffer UrlMatch = new StringBuffer(); public static List<String> SUREURLS = new ArrayList<String>(); // 指纹识别成功的url public static List<String> urladds = new ArrayList<String>(); public static List<Feature> features = new ArrayList<Feature>(); public static int THREADCACHE = 5000; // 线程间隔,每执行1万次对象清除一下系统缓存,调用System.gc(); public static int THREADNUM = 50; // 线程数 public static int TASKCOUNT = 0; // 总任务数 public static int CURRENTNUM = 0; // 已完成任务总数 public static long STARTTIME = 0; // 系统初始化时间 public static int port = 80; // 端口 public static String protocol = "http"; // 协议 public static int model = 1; // 识别模式(1。快速模式 2.精准模式 3.人工判断 ) public static String outputPath = ""; // 结果输出到文件下 public static List<String> fastProbeList = new ArrayList<String>(); // 快速模式(单个域名或ip只出现一次) public static List<String> requestUrl = new ArrayList<String>(); // 自定义 // --设置请求url public static List<String> responseStr = new ArrayList<String>(); // 自定义 // --设置响应内容关键字 public static HashMap<String, String> resultHashMap = new HashMap<String, String>(); // 自定义模式 // 获取结果 public static List<Result> results = new ArrayList<Result>(); // 成功识别指纹临时库 /*** * 更新进度 */ public static synchronized void updatePercent() { Context.CURRENTNUM++; } public static synchronized int getTaskCount() { int urlCount = urladds.size(); if (features == null) { int requestUrlCount = requestUrl.size(); int responseStrCount = responseStr.size(); return urlCount * requestUrlCount * responseStrCount; } else { int fingerCount = features.size(); return urlCount * fingerCount; } } /** * 进度条类 * * @return 100.00% */ public static synchronized String getPercent() { double count = Context.getTaskCount(); double curent = Context.CURRENTNUM; System.out.print("count=" + count + " current=" + curent); NumberFormat format = NumberFormat.getPercentInstance();// 获取格式化类实例 format.setMinimumFractionDigits(2);// 设置小数位 String ret = format.format(curent / count);// 打印计算结果 System.out.print(" " + ret + "\r\n"); return ret; } /** * 设置初始化设置 * */ public static void INIT() { // 设置用户变量 ContextUtil.setJobOption(); // 程序开始运行时间 Context.STARTTIME = System.currentTimeMillis(); // 虚拟机退出时的hook ContextUtil.doShutDownWork(); } }
Ms0x0/Dayu
src/org/secbug/conf/Context.java
903
// 成功识别指纹临时库
line_comment
zh-cn
package org.secbug.conf; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.secbug.util.ContextUtil; import org.secbug.vo.Feature; import org.secbug.vo.Result; public class Context { public static String[] args; public static String currpath = System.getProperty("user.dir")+"\\feature.json"; public static List<String> urls = new ArrayList<String>(); public static int jobid = 0; public static int i = 0; public static StringBuffer UrlMatch = new StringBuffer(); public static List<String> SUREURLS = new ArrayList<String>(); // 指纹识别成功的url public static List<String> urladds = new ArrayList<String>(); public static List<Feature> features = new ArrayList<Feature>(); public static int THREADCACHE = 5000; // 线程间隔,每执行1万次对象清除一下系统缓存,调用System.gc(); public static int THREADNUM = 50; // 线程数 public static int TASKCOUNT = 0; // 总任务数 public static int CURRENTNUM = 0; // 已完成任务总数 public static long STARTTIME = 0; // 系统初始化时间 public static int port = 80; // 端口 public static String protocol = "http"; // 协议 public static int model = 1; // 识别模式(1。快速模式 2.精准模式 3.人工判断 ) public static String outputPath = ""; // 结果输出到文件下 public static List<String> fastProbeList = new ArrayList<String>(); // 快速模式(单个域名或ip只出现一次) public static List<String> requestUrl = new ArrayList<String>(); // 自定义 // --设置请求url public static List<String> responseStr = new ArrayList<String>(); // 自定义 // --设置响应内容关键字 public static HashMap<String, String> resultHashMap = new HashMap<String, String>(); // 自定义模式 // 获取结果 public static List<Result> results = new ArrayList<Result>(); // 成功 <SUF> /*** * 更新进度 */ public static synchronized void updatePercent() { Context.CURRENTNUM++; } public static synchronized int getTaskCount() { int urlCount = urladds.size(); if (features == null) { int requestUrlCount = requestUrl.size(); int responseStrCount = responseStr.size(); return urlCount * requestUrlCount * responseStrCount; } else { int fingerCount = features.size(); return urlCount * fingerCount; } } /** * 进度条类 * * @return 100.00% */ public static synchronized String getPercent() { double count = Context.getTaskCount(); double curent = Context.CURRENTNUM; System.out.print("count=" + count + " current=" + curent); NumberFormat format = NumberFormat.getPercentInstance();// 获取格式化类实例 format.setMinimumFractionDigits(2);// 设置小数位 String ret = format.format(curent / count);// 打印计算结果 System.out.print(" " + ret + "\r\n"); return ret; } /** * 设置初始化设置 * */ public static void INIT() { // 设置用户变量 ContextUtil.setJobOption(); // 程序开始运行时间 Context.STARTTIME = System.currentTimeMillis(); // 虚拟机退出时的hook ContextUtil.doShutDownWork(); } }
true
32582_3
package com.wxsf.fhr.model; import java.awt.Graphics; import com.wxsf.fhr.main.GamePanel; public class SuperObject { public SuperObject() { px = py = vx = vy = 0.0; frame = size = type = life = 0; color = 'r'; th = 0.0D; exist = false; anime = 0; } public static void gameObjectInit(GamePanel gamepanel) { p = gamepanel; } public void setData(double d, double d1, double d2, double d3, int i, int j, int k, int l, char c) { px = d; py = d1; vx = d2; vy = d3; size = i; frame = j; type = k; life = l; color = c; exist = true; }//th = Math.toRadians(-9D); public double setTh(double d, double d1) { if(d1 == 0.0D) th = Math.toRadians(90D); else th = Math.atan(d / d1); return th; } public double setTh(double d) { return th = d; } public void move() { px += vx; py += vy; frame++; //每次移动是frame+1 if(px < 0.0D || py < 0.0D || px > 640D || py > 640D) exist = false; } public void draw(Graphics g) { if(!exist) return; int c = 0; // boolean flag = false; if(color == 'g') //绿弹弹 c = 65; if(color == 'b') //蓝弹弹 c = 128; if(color == 'c') //笨蛋 c = 194; if(color == 'w') //巫女 c = 224; if(color == 'h') //小黑 c = 256; if(color == 'p') //噗噗 c = 320; if(color == 'x') c=10; /////////////////////////////////////TODO if(size <= 32) //小boss { int i = ((size / 4 - 1)) * 32; g.drawImage(p.image, (int)px - 16, (int)py - 16, (int)px + 16, (int)py + 16, c, i, c + 32, i + 32, null); } ////////////////////////////////////////////////////////大boss if(size==100){ //普通状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 195, 449, 255, 510, null); } else if(size>100&&size<200) //狂怒状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 259, 449, 319, 510, null); } public void erase() { exist = false; } public void eraseWithEffect() { if(!exist) return; if((tmp2 = p.effects.getEmpty()) != null) tmp2.setData(px, py, 0.0D, 0.0D, size / 2, 0, size / 4, 5, color); erase(); } public double getPx() { return px; } public double getPy() { return py; } public double getVx() { return vx; } public double getVy() { return vy; } public double getTh() { return th; } public int getSize() { return size; } public int getFrame() { return frame; } public int getType() { return type; } public int getLife() { return life; } public char getColor() { return color; } public boolean getExist() { return exist; } protected static GamePanel p; protected double px; protected double py; protected double vx; protected double vy; protected double th; protected int size; protected int frame; protected int type; protected int life; protected int anime; protected char color; protected boolean exist; protected SuperObject tmp; protected SuperObject tmp2; }
Mtora/Touhou-Rage-Danmaku
src/com/wxsf/fhr/model/SuperObject.java
1,180
//绿弹弹
line_comment
zh-cn
package com.wxsf.fhr.model; import java.awt.Graphics; import com.wxsf.fhr.main.GamePanel; public class SuperObject { public SuperObject() { px = py = vx = vy = 0.0; frame = size = type = life = 0; color = 'r'; th = 0.0D; exist = false; anime = 0; } public static void gameObjectInit(GamePanel gamepanel) { p = gamepanel; } public void setData(double d, double d1, double d2, double d3, int i, int j, int k, int l, char c) { px = d; py = d1; vx = d2; vy = d3; size = i; frame = j; type = k; life = l; color = c; exist = true; }//th = Math.toRadians(-9D); public double setTh(double d, double d1) { if(d1 == 0.0D) th = Math.toRadians(90D); else th = Math.atan(d / d1); return th; } public double setTh(double d) { return th = d; } public void move() { px += vx; py += vy; frame++; //每次移动是frame+1 if(px < 0.0D || py < 0.0D || px > 640D || py > 640D) exist = false; } public void draw(Graphics g) { if(!exist) return; int c = 0; // boolean flag = false; if(color == 'g') //绿弹 <SUF> c = 65; if(color == 'b') //蓝弹弹 c = 128; if(color == 'c') //笨蛋 c = 194; if(color == 'w') //巫女 c = 224; if(color == 'h') //小黑 c = 256; if(color == 'p') //噗噗 c = 320; if(color == 'x') c=10; /////////////////////////////////////TODO if(size <= 32) //小boss { int i = ((size / 4 - 1)) * 32; g.drawImage(p.image, (int)px - 16, (int)py - 16, (int)px + 16, (int)py + 16, c, i, c + 32, i + 32, null); } ////////////////////////////////////////////////////////大boss if(size==100){ //普通状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 195, 449, 255, 510, null); } else if(size>100&&size<200) //狂怒状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 259, 449, 319, 510, null); } public void erase() { exist = false; } public void eraseWithEffect() { if(!exist) return; if((tmp2 = p.effects.getEmpty()) != null) tmp2.setData(px, py, 0.0D, 0.0D, size / 2, 0, size / 4, 5, color); erase(); } public double getPx() { return px; } public double getPy() { return py; } public double getVx() { return vx; } public double getVy() { return vy; } public double getTh() { return th; } public int getSize() { return size; } public int getFrame() { return frame; } public int getType() { return type; } public int getLife() { return life; } public char getColor() { return color; } public boolean getExist() { return exist; } protected static GamePanel p; protected double px; protected double py; protected double vx; protected double vy; protected double th; protected int size; protected int frame; protected int type; protected int life; protected int anime; protected char color; protected boolean exist; protected SuperObject tmp; protected SuperObject tmp2; }
false
66709_22
package com.guet.ARC.service; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.guet.ARC.common.domain.PageInfo; import com.guet.ARC.common.domain.ResultCode; import com.guet.ARC.common.enmu.RedisCacheKey; import com.guet.ARC.common.exception.AlertException; import com.guet.ARC.dao.RoomRepository; import com.guet.ARC.dao.RoomReservationRepository; import com.guet.ARC.dao.UserRepository; import com.guet.ARC.dao.mybatis.RoomReservationQueryRepository; import com.guet.ARC.dao.mybatis.query.RoomReservationQuery; import com.guet.ARC.domain.Message; import com.guet.ARC.domain.Room; import com.guet.ARC.domain.RoomReservation; import com.guet.ARC.domain.User; import com.guet.ARC.domain.dto.apply.MyApplyQueryDTO; import com.guet.ARC.domain.dto.room.ApplyRoomDTO; import com.guet.ARC.domain.dto.room.RoomApplyDetailListQueryDTO; import com.guet.ARC.domain.dto.room.RoomReserveReviewedDTO; import com.guet.ARC.domain.dto.room.UserRoomReservationDetailQueryDTO; import com.guet.ARC.domain.enums.MessageType; import com.guet.ARC.domain.enums.ReservationState; import com.guet.ARC.domain.vo.room.RoomReservationAdminVo; import com.guet.ARC.domain.vo.room.RoomReservationUserVo; import com.guet.ARC.domain.vo.room.RoomReservationVo; import com.guet.ARC.util.CommonUtils; import com.guet.ARC.util.RedisCacheUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.beans.BeanCopier; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.transaction.Transactional; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @Service @Slf4j public class RoomReservationService { @Autowired private UserRepository userRepository; @Autowired private RoomReservationQueryRepository roomReservationQueryRepository; @Autowired private RoomReservationRepository roomReservationRepository; @Autowired private RoomReservationQuery roomReservationQuery; @Autowired private RoomRepository roomRepository; @Autowired private EmailService emailService; @Autowired private MessageService messageService; @Autowired private RedisCacheUtil<String> redisCacheUtil; public void cancelApply(String roomReservationId, String reason) { if (roomReservationId == null || roomReservationId.trim().isEmpty()) { throw new AlertException(ResultCode.PARAM_IS_BLANK); } Optional<RoomReservation> optionalRoomReservation = roomReservationRepository.findById(roomReservationId); if (optionalRoomReservation.isPresent()) { RoomReservation roomReservation = optionalRoomReservation.get(); roomReservation.setState(ReservationState.ROOM_RESERVE_CANCELED); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservation.setRemark(reason); roomReservationRepository.save(roomReservation); // 发送取消预约申请,给审核人发 Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); if (roomOptional.isPresent()) { Room room = roomOptional.get(); Optional<User> userOptional = userRepository.findById(room.getChargePersonId()); if (userOptional.isPresent()) { User user = userOptional.get(); CompletableFuture.runAsync(() -> { roomReservation.getState().sendReservationNoticeMessage(room, user, roomReservation); }); // 发送消息 userRepository.findById(roomReservation.getUserId()).ifPresent(curUser -> { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(roomReservation.getReserveStartTime())); String endTimeStr = sdf.format(new Date(roomReservation.getReserveEndTime())); Message message = new Message(); message.setMessageReceiverId(room.getChargePersonId()); message.setMessageType(MessageType.RESULT); message.setContent(curUser.getName() + "取消了房间" + room.getRoomName() + "的预约申请。预约时间:" + startTimeStr + "~" + endTimeStr + "。"); messageService.sendMessage(message); // 发送邮件提醒,发给房间负责人 if (!StrUtil.isEmpty(user.getMail())) { String content = "您收到来自" + curUser.getName() + "的" + room.getRoomName() + "房间预约申请取消通知,预约时间" + startTimeStr + "至" + endTimeStr + "。" + "取消理由:" + reason + "。"; emailService.sendSimpleMail(user.getMail(), curUser.getName() + "的" + room.getRoomName() + "预约申请取消通知", content); } }); } } } } //同步方法 @Transactional(rollbackOn = RuntimeException.class) public synchronized RoomReservation applyRoom(ApplyRoomDTO applyRoomDTO) { // 检测预约起始和预约结束时间 long subTime = applyRoomDTO.getEndTime() - applyRoomDTO.getStartTime(); long hour12 = 43200000; long halfHour = 1800000; if (subTime <= 0) { throw new AlertException(1000, "预约起始时间不能大于等于结束时间"); } else if (subTime > hour12) { throw new AlertException(1000, "单次房间的预约时间不能大于12小时"); } else if (subTime < halfHour) { throw new AlertException(1000, "单次房间的预约时间不能小于30分钟"); } // 检测是否已经预约 String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); // 是待审核状态且在这段预约时间内代表我已经预约过了, 预约起始时间不能在准备预约的时间范围内,结束时间不能在准备结束预约的时间范围内 List<RoomReservation> roomReservations = roomReservationQueryRepository.selectMany( roomReservationQuery.queryMyReservationListByTimeSql(applyRoomDTO, userId) ); if (!roomReservations.isEmpty()) { throw new AlertException(1000, "您已经预约过该房间,请勿重复操作,在我的预约中查看"); } long time = System.currentTimeMillis(); RoomReservation roomReservation = new RoomReservation(); roomReservation.setId(CommonUtils.generateUUID()); roomReservation.setRoomUsage(applyRoomDTO.getRoomUsage()); roomReservation.setReserveStartTime(applyRoomDTO.getStartTime()); roomReservation.setReserveEndTime(applyRoomDTO.getEndTime()); roomReservation.setState(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED); roomReservation.setCreateTime(time); roomReservation.setUpdateTime(time); roomReservation.setUserId(userId); roomReservation.setRoomId(applyRoomDTO.getRoomId()); roomReservationRepository.save(roomReservation); setRoomApplyNotifyCache(roomReservation, userId); Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); if (roomOptional.isPresent()) { Room room = roomOptional.get(); String chargePersonId = room.getChargePersonId(); Optional<User> userOptional = userRepository.findById(chargePersonId); Optional<User> curUserOptional = userRepository.findById(userId); if (userOptional.isPresent() && curUserOptional.isPresent()) { User user = userOptional.get(); String content = ""; // 发送审核邮件 if (!StrUtil.isEmpty(user.getMail())) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(applyRoomDTO.getStartTime())); String endTimeStr = sdf.format(new Date(applyRoomDTO.getEndTime())); content = "您收到来自" + curUserOptional.get().getName() + "的" + room.getRoomName() + "房间预约申请,预约时间" + startTimeStr + "至" + endTimeStr + ",请您及时处理。"; // 异步发送 emailService.sendHtmlMail(user.getMail(), curUserOptional.get().getName() + "房间预约申请待审核通知", content); } // 发送订阅消息 if (!StrUtil.isEmpty(user.getOpenId())) { // 绑定微信才可接受订阅消息 // 构建消息体,并异步发送 CompletableFuture.runAsync(() -> { // 因为需要房间管理者的openid,所有user要更改一下name未预约人 user.setName(curUserOptional.get().getName()); roomReservation.getState().sendReservationNoticeMessage(room, user, roomReservation); }); } // 发送系统消息 Message message = new Message(); message.setMessageReceiverId(room.getChargePersonId()); message.setMessageType(MessageType.TODO); message.setContent(content); messageService.sendMessage(message); } } return roomReservation; } public PageInfo<RoomReservationUserVo> queryRoomApplyDetailList(RoomApplyDetailListQueryDTO roomApplyDetailListQueryDTO) { String roomId = roomApplyDetailListQueryDTO.getRoomId(); Long startTime = roomApplyDetailListQueryDTO.getStartTime(); Long endTime = roomApplyDetailListQueryDTO.getEndTime(); Long[] standardTime = CommonUtils.getStandardStartTimeAndEndTime(startTime, endTime); // 获取startTime的凌晨00:00 long webAppDateStart = standardTime[0]; // 获取这endTime 23:59:59的毫秒值 long webAppDateEnd = standardTime[1]; // 检查时间跨度是否超过14天 if (webAppDateEnd - webAppDateStart <= 0) { throw new AlertException(1000, "结束时间不能小于等于开始时间"); } long days = (webAppDateEnd - webAppDateStart) / 1000 / 60 / 60 / 24; if (days > 30) { throw new AlertException(1000, "查询数据的时间跨度不允许超过30天"); } // 查询相应房间的所有预约记录 PageRequest pageRequest = PageRequest.of(roomApplyDetailListQueryDTO.getPage() - 1, roomApplyDetailListQueryDTO.getSize()); org.springframework.data.domain.Page<RoomReservation> queryPageData = roomReservationRepository.findByRoomIdAndReserveStartTimeBetweenOrderByCreateTimeDesc(roomId, webAppDateStart, webAppDateEnd, pageRequest); List<RoomReservation> roomReservationList = queryPageData.getContent(); List<RoomReservationUserVo> roomReservationUserVos = new ArrayList<>(); BeanCopier beanCopier = BeanCopier.create(RoomReservation.class, RoomReservationUserVo.class, false); // 添加每条预约记录的预约人姓名 for (RoomReservation roomReservation : roomReservationList) { RoomReservationUserVo roomReservationUserVo = new RoomReservationUserVo(); beanCopier.copy(roomReservation, roomReservationUserVo, null); Optional<User> optionalUser = userRepository.findById(roomReservation.getUserId()); if (optionalUser.isPresent()) { User user = optionalUser.get(); roomReservationUserVo.setName(user.getName()); } roomReservationUserVos.add(roomReservationUserVo); } PageInfo<RoomReservationUserVo> pageInfo = new PageInfo<>(); pageInfo.setPage(roomApplyDetailListQueryDTO.getPage()); pageInfo.setTotalSize(queryPageData.getTotalElements()); pageInfo.setPageData(roomReservationUserVos); return pageInfo; } public PageInfo<RoomReservationVo> queryMyApply(MyApplyQueryDTO myApplyQueryDTO) { String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Page<RoomReservationVo> queryPageData = PageHelper.startPage(myApplyQueryDTO.getPage(), myApplyQueryDTO.getSize()); List<RoomReservationVo> roomReservationVos = roomReservationQueryRepository.selectRoomReservationsVo( roomReservationQuery.queryMyApplySql(myApplyQueryDTO, userId) ); return new PageInfo<>(queryPageData); } public PageInfo<RoomReservationVo> queryUserReserveRecord(UserRoomReservationDetailQueryDTO queryDTO) { Page<RoomReservationVo> queryPageData = PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize()); List<RoomReservationVo> roomReservationVos = roomReservationQueryRepository.selectRoomReservationsVo( roomReservationQuery.queryUserReserveRecordSql(queryDTO) ); PageInfo<RoomReservationVo> roomReservationPageInfo = new PageInfo<>(); roomReservationPageInfo.setPage(queryDTO.getPage()); roomReservationPageInfo.setTotalSize(queryPageData.getTotal()); roomReservationPageInfo.setPageData(roomReservationVos); return roomReservationPageInfo; } // 获取待审核列表 public PageInfo<RoomReservationAdminVo> queryRoomReserveToBeReviewed(RoomReserveReviewedDTO queryDTO) { String currentUserId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Page<RoomReservationAdminVo> queryPageData = PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize()); if (!StrUtil.isEmpty(queryDTO.getStuNum())) { Optional<User> userOptional = userRepository.findByStuNum(queryDTO.getStuNum()); userOptional.ifPresent(user -> queryDTO.setApplyUserId(user.getId())); } List<RoomReservationAdminVo> filteredList = new ArrayList<>(); List<RoomReservationAdminVo> roomReservationAdminVos = roomReservationQueryRepository.selectRoomReservationsAdminVo(roomReservationQuery.queryRoomReserveToBeReviewedSql(queryDTO, currentUserId)); long now = System.currentTimeMillis(); for (RoomReservationAdminVo roomReservationAdminVo : roomReservationAdminVos) { Optional<User> optionalUser = userRepository.findById(roomReservationAdminVo.getUserId()); optionalUser.ifPresent(user -> { roomReservationAdminVo.setName(user.getName()); roomReservationAdminVo.setStuNum(user.getStuNum()); }); // fix:问题:只要现在的时间大于起始时间就会被认为超时未处理,应该要加上是否已经被处理,未被处理的才要判断是否超时 if (now > roomReservationAdminVo.getReserveStartTime() && roomReservationAdminVo.getState().equals(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED)) { handleTimeOutReservationAdmin(roomReservationAdminVo); // 被设置超时的房间预约信息,从列表中去除 continue; } filteredList.add(roomReservationAdminVo); } // 移除超市 PageInfo<RoomReservationAdminVo> roomReservationPageInfo = new PageInfo<>(); roomReservationPageInfo.setPage(queryDTO.getPage()); roomReservationPageInfo.setTotalSize(queryPageData.getTotal()); roomReservationPageInfo.setPageData(filteredList); return roomReservationPageInfo; } // 通过或者驳回预约 public void passOrRejectReserve(String reserveId, boolean pass, String reason) { if (!StringUtils.hasLength(reason)) { reason = ""; } String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Optional<RoomReservation> roomReservationOptional = roomReservationRepository.findById(reserveId); // 审核人 Optional<User> userOptional = userRepository.findById(userId); if (roomReservationOptional.isPresent() && userOptional.isPresent()) { RoomReservation roomReservation = roomReservationOptional.get(); User user = userOptional.get(); // 是否超出预约结束时间 if (System.currentTimeMillis() >= roomReservation.getReserveStartTime()) { throw new AlertException(1000, "已超过预约起始时间, 系统已自动更改申请状态,无法操作。请刷新页面。"); } // 发送通知邮件信息 // 发起请求的用户 Optional<User> roomReservationUserOptional = userRepository.findById(roomReservation.getUserId()); String toPersonMail = null; if (roomReservationUserOptional.isPresent()) { toPersonMail = roomReservationUserOptional.get().getMail(); } else { throw new AlertException(ResultCode.PARAM_IS_ILLEGAL); } Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); String roomName = null; if (roomOptional.isPresent()) { roomName = roomOptional.get().getRoomName(); } else { throw new AlertException(ResultCode.PARAM_IS_ILLEGAL); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(roomReservation.getReserveStartTime())); String endTimeStr = sdf.format(new Date(roomReservation.getReserveEndTime())); String createTimeStr = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(roomReservation.getCreateTime())); String content = ""; if (pass) { // 是否在相同时间内已经预约过了,也就是这段时间内是否有其他待审核预约、已审核预约,表示该房间已被站其他人占用,本次预约就不能再给通过了,已经是驳回状态 if (roomReservation.getState().equals(ReservationState.ROOM_RESERVE_TO_BE_REJECTED) && checkSameTimeReservationWithStatus(reserveId)) { throw new AlertException(1000, "用户在相同时间再次进行预约,无法从驳回进行通过操作"); } roomReservation.setRemark(reason); roomReservation.setState(ReservationState.ROOM_RESERVE_ALREADY_REVIEWED); // 发送通过邮件提醒 if (StringUtils.hasLength(toPersonMail)) { // 如果有邮箱就发送通知 content = "您" + createTimeStr + "发起的" + roomName + "预约申请,预约时间为" + startTimeStr + "至" + endTimeStr + ",已由审核员审核通过。"; emailService.sendSimpleMail(toPersonMail, roomName + "预约申请审核结果通知", content); } } else { roomReservation.setRemark(reason); roomReservation.setState(ReservationState.ROOM_RESERVE_TO_BE_REJECTED); // 发送通过邮件提醒 if (StringUtils.hasLength(toPersonMail)) { // 如果有邮箱就发送通知 content = "您" + createTimeStr + "发起的" + roomName + "预约申请,预约时间为" + startTimeStr + "至" + endTimeStr + ",审核不通过。原因为:" + reason + "。"; emailService.sendSimpleMail(toPersonMail, roomName + "预约申请审核结果通知", content); } } roomReservation.setVerifyUserName(user.getName()); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservationRepository.save(roomReservation); // 发送订阅消息 CompletableFuture.runAsync(() -> { roomReservation.getState().sendReservationNoticeMessage(roomOptional.get(), roomReservationUserOptional.get(), roomReservation); }); // 发送系统消息 Message message = new Message(); message.setMessageReceiverId(roomOptional.get().getChargePersonId()); message.setMessageType(MessageType.RESULT); message.setContent(content); messageService.sendMessage(message); } else { throw new AlertException(ResultCode.PARAM_IS_INVALID); } } // 删除预约记录 public void delRoomReservationRecord(String id) { roomReservationRepository.deleteById(id); } /** * 主要是用于处理已驳回是在进行通过的情况 * * @param reserveId * @return */ private boolean checkSameTimeReservationWithStatus(String reserveId) { // 这段时间内这个房间是否有其他待审核预约、已审核预约记录,这两个状态表示房间已经被占有 Optional<RoomReservation> roomReservationOptional = roomReservationRepository.findById(reserveId); if (roomReservationOptional.isPresent()) { RoomReservation roomReservation = roomReservationOptional.get(); // 预约起始和截止时间 Long reserveStartTime = roomReservation.getReserveStartTime(); Long reserveEndTime = roomReservation.getReserveEndTime(); String roomId = roomReservation.getRoomId(); List<ReservationState> reservationStates = new ArrayList<>(); reservationStates.add(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED); reservationStates.add(ReservationState.ROOM_RESERVE_ALREADY_REVIEWED); long count = roomReservationRepository.countByReserveStartTimeAndReserveEndTimeAndRoomIdAndStateIn( reserveStartTime, reserveEndTime, roomId, reservationStates ); // 表示有冲突,驳回后用户在这段时间尝试了重新预约 return count > 0; } else { throw new AlertException(ResultCode.ILLEGAL_OPERATION); } } private void handleTimeOutReservationAdmin(RoomReservationAdminVo roomReservationVo) { roomReservationVo.setState(ReservationState.ROOM_RESERVE_IS_TIME_OUT); BeanCopier copier = BeanCopier.create(RoomReservationAdminVo.class, RoomReservation.class, false); RoomReservation roomReservation = new RoomReservation(); copier.copy(roomReservationVo, roomReservation, null); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservationRepository.save(roomReservation); } /** * 包含两个提醒,发送时机就是key过期时,快要过期提醒审核,已过期提醒申请人超时未处理重新申请。 * @param roomReservation 房间预约实体 * @param userId 当前登陆人id */ private void setRoomApplyNotifyCache(RoomReservation roomReservation, String userId) { // 记录当前时间->房间预约起始时间,redis缓存,用于判断是否管理员超期未处理,自动更改状态,通知用户房间预约超期未处理,防止占用时间段,用户可以重新预约 long cacheTimeSecond = DateUtil.between(new Date(), new Date(roomReservation.getReserveStartTime()), DateUnit.SECOND); String roomOccupancyApplyKey = RedisCacheKey.ROOM_OCCUPANCY_APPLY_KEY.concatKey(roomReservation.getId()); redisCacheUtil.setCacheObject(roomOccupancyApplyKey, userId, cacheTimeSecond, TimeUnit.SECONDS); // 前一个小时提醒负责人审核。 预约间隔最少是30分钟 long cacheNotifyChargerSecond = cacheTimeSecond - (60 * 60); // 当前时间距离预约起始时间小于一个小时 if (cacheTimeSecond <= 3600L && cacheTimeSecond > 1800L) { // 不足一个小时,但是大于半个小时 cacheNotifyChargerSecond = cacheTimeSecond - (30 * 60); } else if (cacheTimeSecond < 1800L) { // 不设置通知审核人 return; } // 缓存 String notifyChargerKey = RedisCacheKey.ROOM_APPLY_TIMEOUT_NOTIFY_KEY.concatKey(roomReservation.getId()); redisCacheUtil.setCacheObject(notifyChargerKey, userId, cacheNotifyChargerSecond, TimeUnit.SECONDS); } }
MuShanYu/apply-room-record
src/main/java/com/guet/ARC/service/RoomReservationService.java
5,662
// 移除超市
line_comment
zh-cn
package com.guet.ARC.service; import cn.dev33.satoken.stp.StpUtil; import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.StrUtil; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import com.guet.ARC.common.domain.PageInfo; import com.guet.ARC.common.domain.ResultCode; import com.guet.ARC.common.enmu.RedisCacheKey; import com.guet.ARC.common.exception.AlertException; import com.guet.ARC.dao.RoomRepository; import com.guet.ARC.dao.RoomReservationRepository; import com.guet.ARC.dao.UserRepository; import com.guet.ARC.dao.mybatis.RoomReservationQueryRepository; import com.guet.ARC.dao.mybatis.query.RoomReservationQuery; import com.guet.ARC.domain.Message; import com.guet.ARC.domain.Room; import com.guet.ARC.domain.RoomReservation; import com.guet.ARC.domain.User; import com.guet.ARC.domain.dto.apply.MyApplyQueryDTO; import com.guet.ARC.domain.dto.room.ApplyRoomDTO; import com.guet.ARC.domain.dto.room.RoomApplyDetailListQueryDTO; import com.guet.ARC.domain.dto.room.RoomReserveReviewedDTO; import com.guet.ARC.domain.dto.room.UserRoomReservationDetailQueryDTO; import com.guet.ARC.domain.enums.MessageType; import com.guet.ARC.domain.enums.ReservationState; import com.guet.ARC.domain.vo.room.RoomReservationAdminVo; import com.guet.ARC.domain.vo.room.RoomReservationUserVo; import com.guet.ARC.domain.vo.room.RoomReservationVo; import com.guet.ARC.util.CommonUtils; import com.guet.ARC.util.RedisCacheUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cglib.beans.BeanCopier; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; import javax.transaction.Transactional; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; @Service @Slf4j public class RoomReservationService { @Autowired private UserRepository userRepository; @Autowired private RoomReservationQueryRepository roomReservationQueryRepository; @Autowired private RoomReservationRepository roomReservationRepository; @Autowired private RoomReservationQuery roomReservationQuery; @Autowired private RoomRepository roomRepository; @Autowired private EmailService emailService; @Autowired private MessageService messageService; @Autowired private RedisCacheUtil<String> redisCacheUtil; public void cancelApply(String roomReservationId, String reason) { if (roomReservationId == null || roomReservationId.trim().isEmpty()) { throw new AlertException(ResultCode.PARAM_IS_BLANK); } Optional<RoomReservation> optionalRoomReservation = roomReservationRepository.findById(roomReservationId); if (optionalRoomReservation.isPresent()) { RoomReservation roomReservation = optionalRoomReservation.get(); roomReservation.setState(ReservationState.ROOM_RESERVE_CANCELED); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservation.setRemark(reason); roomReservationRepository.save(roomReservation); // 发送取消预约申请,给审核人发 Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); if (roomOptional.isPresent()) { Room room = roomOptional.get(); Optional<User> userOptional = userRepository.findById(room.getChargePersonId()); if (userOptional.isPresent()) { User user = userOptional.get(); CompletableFuture.runAsync(() -> { roomReservation.getState().sendReservationNoticeMessage(room, user, roomReservation); }); // 发送消息 userRepository.findById(roomReservation.getUserId()).ifPresent(curUser -> { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(roomReservation.getReserveStartTime())); String endTimeStr = sdf.format(new Date(roomReservation.getReserveEndTime())); Message message = new Message(); message.setMessageReceiverId(room.getChargePersonId()); message.setMessageType(MessageType.RESULT); message.setContent(curUser.getName() + "取消了房间" + room.getRoomName() + "的预约申请。预约时间:" + startTimeStr + "~" + endTimeStr + "。"); messageService.sendMessage(message); // 发送邮件提醒,发给房间负责人 if (!StrUtil.isEmpty(user.getMail())) { String content = "您收到来自" + curUser.getName() + "的" + room.getRoomName() + "房间预约申请取消通知,预约时间" + startTimeStr + "至" + endTimeStr + "。" + "取消理由:" + reason + "。"; emailService.sendSimpleMail(user.getMail(), curUser.getName() + "的" + room.getRoomName() + "预约申请取消通知", content); } }); } } } } //同步方法 @Transactional(rollbackOn = RuntimeException.class) public synchronized RoomReservation applyRoom(ApplyRoomDTO applyRoomDTO) { // 检测预约起始和预约结束时间 long subTime = applyRoomDTO.getEndTime() - applyRoomDTO.getStartTime(); long hour12 = 43200000; long halfHour = 1800000; if (subTime <= 0) { throw new AlertException(1000, "预约起始时间不能大于等于结束时间"); } else if (subTime > hour12) { throw new AlertException(1000, "单次房间的预约时间不能大于12小时"); } else if (subTime < halfHour) { throw new AlertException(1000, "单次房间的预约时间不能小于30分钟"); } // 检测是否已经预约 String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); // 是待审核状态且在这段预约时间内代表我已经预约过了, 预约起始时间不能在准备预约的时间范围内,结束时间不能在准备结束预约的时间范围内 List<RoomReservation> roomReservations = roomReservationQueryRepository.selectMany( roomReservationQuery.queryMyReservationListByTimeSql(applyRoomDTO, userId) ); if (!roomReservations.isEmpty()) { throw new AlertException(1000, "您已经预约过该房间,请勿重复操作,在我的预约中查看"); } long time = System.currentTimeMillis(); RoomReservation roomReservation = new RoomReservation(); roomReservation.setId(CommonUtils.generateUUID()); roomReservation.setRoomUsage(applyRoomDTO.getRoomUsage()); roomReservation.setReserveStartTime(applyRoomDTO.getStartTime()); roomReservation.setReserveEndTime(applyRoomDTO.getEndTime()); roomReservation.setState(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED); roomReservation.setCreateTime(time); roomReservation.setUpdateTime(time); roomReservation.setUserId(userId); roomReservation.setRoomId(applyRoomDTO.getRoomId()); roomReservationRepository.save(roomReservation); setRoomApplyNotifyCache(roomReservation, userId); Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); if (roomOptional.isPresent()) { Room room = roomOptional.get(); String chargePersonId = room.getChargePersonId(); Optional<User> userOptional = userRepository.findById(chargePersonId); Optional<User> curUserOptional = userRepository.findById(userId); if (userOptional.isPresent() && curUserOptional.isPresent()) { User user = userOptional.get(); String content = ""; // 发送审核邮件 if (!StrUtil.isEmpty(user.getMail())) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(applyRoomDTO.getStartTime())); String endTimeStr = sdf.format(new Date(applyRoomDTO.getEndTime())); content = "您收到来自" + curUserOptional.get().getName() + "的" + room.getRoomName() + "房间预约申请,预约时间" + startTimeStr + "至" + endTimeStr + ",请您及时处理。"; // 异步发送 emailService.sendHtmlMail(user.getMail(), curUserOptional.get().getName() + "房间预约申请待审核通知", content); } // 发送订阅消息 if (!StrUtil.isEmpty(user.getOpenId())) { // 绑定微信才可接受订阅消息 // 构建消息体,并异步发送 CompletableFuture.runAsync(() -> { // 因为需要房间管理者的openid,所有user要更改一下name未预约人 user.setName(curUserOptional.get().getName()); roomReservation.getState().sendReservationNoticeMessage(room, user, roomReservation); }); } // 发送系统消息 Message message = new Message(); message.setMessageReceiverId(room.getChargePersonId()); message.setMessageType(MessageType.TODO); message.setContent(content); messageService.sendMessage(message); } } return roomReservation; } public PageInfo<RoomReservationUserVo> queryRoomApplyDetailList(RoomApplyDetailListQueryDTO roomApplyDetailListQueryDTO) { String roomId = roomApplyDetailListQueryDTO.getRoomId(); Long startTime = roomApplyDetailListQueryDTO.getStartTime(); Long endTime = roomApplyDetailListQueryDTO.getEndTime(); Long[] standardTime = CommonUtils.getStandardStartTimeAndEndTime(startTime, endTime); // 获取startTime的凌晨00:00 long webAppDateStart = standardTime[0]; // 获取这endTime 23:59:59的毫秒值 long webAppDateEnd = standardTime[1]; // 检查时间跨度是否超过14天 if (webAppDateEnd - webAppDateStart <= 0) { throw new AlertException(1000, "结束时间不能小于等于开始时间"); } long days = (webAppDateEnd - webAppDateStart) / 1000 / 60 / 60 / 24; if (days > 30) { throw new AlertException(1000, "查询数据的时间跨度不允许超过30天"); } // 查询相应房间的所有预约记录 PageRequest pageRequest = PageRequest.of(roomApplyDetailListQueryDTO.getPage() - 1, roomApplyDetailListQueryDTO.getSize()); org.springframework.data.domain.Page<RoomReservation> queryPageData = roomReservationRepository.findByRoomIdAndReserveStartTimeBetweenOrderByCreateTimeDesc(roomId, webAppDateStart, webAppDateEnd, pageRequest); List<RoomReservation> roomReservationList = queryPageData.getContent(); List<RoomReservationUserVo> roomReservationUserVos = new ArrayList<>(); BeanCopier beanCopier = BeanCopier.create(RoomReservation.class, RoomReservationUserVo.class, false); // 添加每条预约记录的预约人姓名 for (RoomReservation roomReservation : roomReservationList) { RoomReservationUserVo roomReservationUserVo = new RoomReservationUserVo(); beanCopier.copy(roomReservation, roomReservationUserVo, null); Optional<User> optionalUser = userRepository.findById(roomReservation.getUserId()); if (optionalUser.isPresent()) { User user = optionalUser.get(); roomReservationUserVo.setName(user.getName()); } roomReservationUserVos.add(roomReservationUserVo); } PageInfo<RoomReservationUserVo> pageInfo = new PageInfo<>(); pageInfo.setPage(roomApplyDetailListQueryDTO.getPage()); pageInfo.setTotalSize(queryPageData.getTotalElements()); pageInfo.setPageData(roomReservationUserVos); return pageInfo; } public PageInfo<RoomReservationVo> queryMyApply(MyApplyQueryDTO myApplyQueryDTO) { String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Page<RoomReservationVo> queryPageData = PageHelper.startPage(myApplyQueryDTO.getPage(), myApplyQueryDTO.getSize()); List<RoomReservationVo> roomReservationVos = roomReservationQueryRepository.selectRoomReservationsVo( roomReservationQuery.queryMyApplySql(myApplyQueryDTO, userId) ); return new PageInfo<>(queryPageData); } public PageInfo<RoomReservationVo> queryUserReserveRecord(UserRoomReservationDetailQueryDTO queryDTO) { Page<RoomReservationVo> queryPageData = PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize()); List<RoomReservationVo> roomReservationVos = roomReservationQueryRepository.selectRoomReservationsVo( roomReservationQuery.queryUserReserveRecordSql(queryDTO) ); PageInfo<RoomReservationVo> roomReservationPageInfo = new PageInfo<>(); roomReservationPageInfo.setPage(queryDTO.getPage()); roomReservationPageInfo.setTotalSize(queryPageData.getTotal()); roomReservationPageInfo.setPageData(roomReservationVos); return roomReservationPageInfo; } // 获取待审核列表 public PageInfo<RoomReservationAdminVo> queryRoomReserveToBeReviewed(RoomReserveReviewedDTO queryDTO) { String currentUserId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Page<RoomReservationAdminVo> queryPageData = PageHelper.startPage(queryDTO.getPage(), queryDTO.getSize()); if (!StrUtil.isEmpty(queryDTO.getStuNum())) { Optional<User> userOptional = userRepository.findByStuNum(queryDTO.getStuNum()); userOptional.ifPresent(user -> queryDTO.setApplyUserId(user.getId())); } List<RoomReservationAdminVo> filteredList = new ArrayList<>(); List<RoomReservationAdminVo> roomReservationAdminVos = roomReservationQueryRepository.selectRoomReservationsAdminVo(roomReservationQuery.queryRoomReserveToBeReviewedSql(queryDTO, currentUserId)); long now = System.currentTimeMillis(); for (RoomReservationAdminVo roomReservationAdminVo : roomReservationAdminVos) { Optional<User> optionalUser = userRepository.findById(roomReservationAdminVo.getUserId()); optionalUser.ifPresent(user -> { roomReservationAdminVo.setName(user.getName()); roomReservationAdminVo.setStuNum(user.getStuNum()); }); // fix:问题:只要现在的时间大于起始时间就会被认为超时未处理,应该要加上是否已经被处理,未被处理的才要判断是否超时 if (now > roomReservationAdminVo.getReserveStartTime() && roomReservationAdminVo.getState().equals(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED)) { handleTimeOutReservationAdmin(roomReservationAdminVo); // 被设置超时的房间预约信息,从列表中去除 continue; } filteredList.add(roomReservationAdminVo); } // 移除 <SUF> PageInfo<RoomReservationAdminVo> roomReservationPageInfo = new PageInfo<>(); roomReservationPageInfo.setPage(queryDTO.getPage()); roomReservationPageInfo.setTotalSize(queryPageData.getTotal()); roomReservationPageInfo.setPageData(filteredList); return roomReservationPageInfo; } // 通过或者驳回预约 public void passOrRejectReserve(String reserveId, boolean pass, String reason) { if (!StringUtils.hasLength(reason)) { reason = ""; } String userId = StpUtil.getSessionByLoginId(StpUtil.getLoginId()).getString("userId"); Optional<RoomReservation> roomReservationOptional = roomReservationRepository.findById(reserveId); // 审核人 Optional<User> userOptional = userRepository.findById(userId); if (roomReservationOptional.isPresent() && userOptional.isPresent()) { RoomReservation roomReservation = roomReservationOptional.get(); User user = userOptional.get(); // 是否超出预约结束时间 if (System.currentTimeMillis() >= roomReservation.getReserveStartTime()) { throw new AlertException(1000, "已超过预约起始时间, 系统已自动更改申请状态,无法操作。请刷新页面。"); } // 发送通知邮件信息 // 发起请求的用户 Optional<User> roomReservationUserOptional = userRepository.findById(roomReservation.getUserId()); String toPersonMail = null; if (roomReservationUserOptional.isPresent()) { toPersonMail = roomReservationUserOptional.get().getMail(); } else { throw new AlertException(ResultCode.PARAM_IS_ILLEGAL); } Optional<Room> roomOptional = roomRepository.findById(roomReservation.getRoomId()); String roomName = null; if (roomOptional.isPresent()) { roomName = roomOptional.get().getRoomName(); } else { throw new AlertException(ResultCode.PARAM_IS_ILLEGAL); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); String startTimeStr = sdf.format(new Date(roomReservation.getReserveStartTime())); String endTimeStr = sdf.format(new Date(roomReservation.getReserveEndTime())); String createTimeStr = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date(roomReservation.getCreateTime())); String content = ""; if (pass) { // 是否在相同时间内已经预约过了,也就是这段时间内是否有其他待审核预约、已审核预约,表示该房间已被站其他人占用,本次预约就不能再给通过了,已经是驳回状态 if (roomReservation.getState().equals(ReservationState.ROOM_RESERVE_TO_BE_REJECTED) && checkSameTimeReservationWithStatus(reserveId)) { throw new AlertException(1000, "用户在相同时间再次进行预约,无法从驳回进行通过操作"); } roomReservation.setRemark(reason); roomReservation.setState(ReservationState.ROOM_RESERVE_ALREADY_REVIEWED); // 发送通过邮件提醒 if (StringUtils.hasLength(toPersonMail)) { // 如果有邮箱就发送通知 content = "您" + createTimeStr + "发起的" + roomName + "预约申请,预约时间为" + startTimeStr + "至" + endTimeStr + ",已由审核员审核通过。"; emailService.sendSimpleMail(toPersonMail, roomName + "预约申请审核结果通知", content); } } else { roomReservation.setRemark(reason); roomReservation.setState(ReservationState.ROOM_RESERVE_TO_BE_REJECTED); // 发送通过邮件提醒 if (StringUtils.hasLength(toPersonMail)) { // 如果有邮箱就发送通知 content = "您" + createTimeStr + "发起的" + roomName + "预约申请,预约时间为" + startTimeStr + "至" + endTimeStr + ",审核不通过。原因为:" + reason + "。"; emailService.sendSimpleMail(toPersonMail, roomName + "预约申请审核结果通知", content); } } roomReservation.setVerifyUserName(user.getName()); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservationRepository.save(roomReservation); // 发送订阅消息 CompletableFuture.runAsync(() -> { roomReservation.getState().sendReservationNoticeMessage(roomOptional.get(), roomReservationUserOptional.get(), roomReservation); }); // 发送系统消息 Message message = new Message(); message.setMessageReceiverId(roomOptional.get().getChargePersonId()); message.setMessageType(MessageType.RESULT); message.setContent(content); messageService.sendMessage(message); } else { throw new AlertException(ResultCode.PARAM_IS_INVALID); } } // 删除预约记录 public void delRoomReservationRecord(String id) { roomReservationRepository.deleteById(id); } /** * 主要是用于处理已驳回是在进行通过的情况 * * @param reserveId * @return */ private boolean checkSameTimeReservationWithStatus(String reserveId) { // 这段时间内这个房间是否有其他待审核预约、已审核预约记录,这两个状态表示房间已经被占有 Optional<RoomReservation> roomReservationOptional = roomReservationRepository.findById(reserveId); if (roomReservationOptional.isPresent()) { RoomReservation roomReservation = roomReservationOptional.get(); // 预约起始和截止时间 Long reserveStartTime = roomReservation.getReserveStartTime(); Long reserveEndTime = roomReservation.getReserveEndTime(); String roomId = roomReservation.getRoomId(); List<ReservationState> reservationStates = new ArrayList<>(); reservationStates.add(ReservationState.ROOM_RESERVE_TO_BE_REVIEWED); reservationStates.add(ReservationState.ROOM_RESERVE_ALREADY_REVIEWED); long count = roomReservationRepository.countByReserveStartTimeAndReserveEndTimeAndRoomIdAndStateIn( reserveStartTime, reserveEndTime, roomId, reservationStates ); // 表示有冲突,驳回后用户在这段时间尝试了重新预约 return count > 0; } else { throw new AlertException(ResultCode.ILLEGAL_OPERATION); } } private void handleTimeOutReservationAdmin(RoomReservationAdminVo roomReservationVo) { roomReservationVo.setState(ReservationState.ROOM_RESERVE_IS_TIME_OUT); BeanCopier copier = BeanCopier.create(RoomReservationAdminVo.class, RoomReservation.class, false); RoomReservation roomReservation = new RoomReservation(); copier.copy(roomReservationVo, roomReservation, null); roomReservation.setUpdateTime(System.currentTimeMillis()); roomReservationRepository.save(roomReservation); } /** * 包含两个提醒,发送时机就是key过期时,快要过期提醒审核,已过期提醒申请人超时未处理重新申请。 * @param roomReservation 房间预约实体 * @param userId 当前登陆人id */ private void setRoomApplyNotifyCache(RoomReservation roomReservation, String userId) { // 记录当前时间->房间预约起始时间,redis缓存,用于判断是否管理员超期未处理,自动更改状态,通知用户房间预约超期未处理,防止占用时间段,用户可以重新预约 long cacheTimeSecond = DateUtil.between(new Date(), new Date(roomReservation.getReserveStartTime()), DateUnit.SECOND); String roomOccupancyApplyKey = RedisCacheKey.ROOM_OCCUPANCY_APPLY_KEY.concatKey(roomReservation.getId()); redisCacheUtil.setCacheObject(roomOccupancyApplyKey, userId, cacheTimeSecond, TimeUnit.SECONDS); // 前一个小时提醒负责人审核。 预约间隔最少是30分钟 long cacheNotifyChargerSecond = cacheTimeSecond - (60 * 60); // 当前时间距离预约起始时间小于一个小时 if (cacheTimeSecond <= 3600L && cacheTimeSecond > 1800L) { // 不足一个小时,但是大于半个小时 cacheNotifyChargerSecond = cacheTimeSecond - (30 * 60); } else if (cacheTimeSecond < 1800L) { // 不设置通知审核人 return; } // 缓存 String notifyChargerKey = RedisCacheKey.ROOM_APPLY_TIMEOUT_NOTIFY_KEY.concatKey(roomReservation.getId()); redisCacheUtil.setCacheObject(notifyChargerKey, userId, cacheNotifyChargerSecond, TimeUnit.SECONDS); } }
false
23148_1
package cse.ooad.project.model; import jakarta.persistence.*; import lombok.*; import java.sql.Timestamp; import java.util.Objects; /** * {@link Comment}用于表示评论信息的实体类,包括评论的基本信息和属性。<br> * 属性列表: * <ul> * <li>commentId: 评论ID,唯一标识评论。</li> * <li>title: 评论标题。</li> * <li>body: 评论内容。</li> * <li>userId: 评论发表者的帐户ID。老师和学生都可以评论。</li> * <li>postId: 评论所属的帖子ID。</li> * <li>creationTime: 评论创建时间。</li> * <li>disabled: 评论是否被禁用。</li> * <li>[映射][未使用]post: 评论所属的帖子。</li> * <li>[映射][未使用]replyList: 评论的回复列表。</li> * </ul> * 评论的嵌套方式:<br> * 每个房间拥有一条元评论,元评论的postId为0,userId为房间的ID。<br> * 对这个房间发起的评论视为对元评论的回复,其postId为元评论的commentId,userId为发起评论的用户ID。<br> * 若对评论发起的评论,其postId为被回复的评论的commentId,userId为发起评论的用户ID。<br> */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "comments", schema = "public", catalog = "cs309a") public class Comment { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column(name = "comment_id") private Long commentId; @Basic @Column(name = "title") private String title; @Basic @Column(name = "body") private String body; @Basic @Column(name = "user_id") private Long userId; @Basic @Column(name = "post_id") private Long postId; @Basic @Column(name = "creation_date") private Timestamp creationTime; @Basic @Column(name = "disabled") private Boolean disabled; /* 映射实体 */ // todo: 不加了 增加工作量 或者加上也可以?再说 // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "post_id", insertable = false, updatable = false) // private Comment post; // // @Exclude // @JsonIgnore // @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) // private List<Comment> replyList; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Comment comment = (Comment) o; return Objects.equals(commentId, comment.commentId) && Objects.equals(title, comment.title) && Objects.equals(body, comment.body) && Objects.equals(userId, comment.userId) && Objects.equals(postId, comment.postId) && Objects.equals(creationTime, comment.creationTime) && Objects.equals(disabled, comment.disabled); } @Override public int hashCode() { return Objects.hash(commentId, title, body, userId, postId, creationTime, disabled); } }
MuuuShin/CS309_23Fall_Project
project/project/model/Comment.java
860
/* 映射实体 */
block_comment
zh-cn
package cse.ooad.project.model; import jakarta.persistence.*; import lombok.*; import java.sql.Timestamp; import java.util.Objects; /** * {@link Comment}用于表示评论信息的实体类,包括评论的基本信息和属性。<br> * 属性列表: * <ul> * <li>commentId: 评论ID,唯一标识评论。</li> * <li>title: 评论标题。</li> * <li>body: 评论内容。</li> * <li>userId: 评论发表者的帐户ID。老师和学生都可以评论。</li> * <li>postId: 评论所属的帖子ID。</li> * <li>creationTime: 评论创建时间。</li> * <li>disabled: 评论是否被禁用。</li> * <li>[映射][未使用]post: 评论所属的帖子。</li> * <li>[映射][未使用]replyList: 评论的回复列表。</li> * </ul> * 评论的嵌套方式:<br> * 每个房间拥有一条元评论,元评论的postId为0,userId为房间的ID。<br> * 对这个房间发起的评论视为对元评论的回复,其postId为元评论的commentId,userId为发起评论的用户ID。<br> * 若对评论发起的评论,其postId为被回复的评论的commentId,userId为发起评论的用户ID。<br> */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "comments", schema = "public", catalog = "cs309a") public class Comment { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column(name = "comment_id") private Long commentId; @Basic @Column(name = "title") private String title; @Basic @Column(name = "body") private String body; @Basic @Column(name = "user_id") private Long userId; @Basic @Column(name = "post_id") private Long postId; @Basic @Column(name = "creation_date") private Timestamp creationTime; @Basic @Column(name = "disabled") private Boolean disabled; /* 映射实 <SUF>*/ // todo: 不加了 增加工作量 或者加上也可以?再说 // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "post_id", insertable = false, updatable = false) // private Comment post; // // @Exclude // @JsonIgnore // @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) // private List<Comment> replyList; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Comment comment = (Comment) o; return Objects.equals(commentId, comment.commentId) && Objects.equals(title, comment.title) && Objects.equals(body, comment.body) && Objects.equals(userId, comment.userId) && Objects.equals(postId, comment.postId) && Objects.equals(creationTime, comment.creationTime) && Objects.equals(disabled, comment.disabled); } @Override public int hashCode() { return Objects.hash(commentId, title, body, userId, postId, creationTime, disabled); } }
false
59147_5
package com.muxistudio.jinyixin.no10; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MainActivity extends ActionBarActivity { private HttpClient httpClient; private HttpGet httpGet; private String temp; private TextView content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); content = (TextView) findViewById(R.id.content); //网络连接的部分不允许写在主线程里面,一定要注意 new Thread(new Runnable() { @Override public void run() { httpClient = new DefaultHttpClient();// httpGet = new HttpGet("https://api.douban.com/v2/book/search?q=哈利波特&count=1");// //try一下,以防网络不稳定而挂掉 //buffer的内容如果不清楚书上有,我也有在tower上整理:关于输入输出的一个分享 try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); String line = null; StringBuilder builder = new StringBuilder(); while ((line = br.readLine()) != null) { builder.append(line); } temp = builder.toString(); Log.i("result", temp); //runOnUiThread是填写UI的方法,因为在非主线程不允许填写UI runOnUiThread(new Runnable() { @Override public void run() { content.setText(temp); } }); } } catch (IOException e) { //可以输出一个什么网络错误的提示 } } }).start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Muxi-Studio/AndroidHomework
jinyixin/NO10/app/src/main/java/com/muxistudio/jinyixin/no10/MainActivity.java
697
//可以输出一个什么网络错误的提示
line_comment
zh-cn
package com.muxistudio.jinyixin.no10; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class MainActivity extends ActionBarActivity { private HttpClient httpClient; private HttpGet httpGet; private String temp; private TextView content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); content = (TextView) findViewById(R.id.content); //网络连接的部分不允许写在主线程里面,一定要注意 new Thread(new Runnable() { @Override public void run() { httpClient = new DefaultHttpClient();// httpGet = new HttpGet("https://api.douban.com/v2/book/search?q=哈利波特&count=1");// //try一下,以防网络不稳定而挂掉 //buffer的内容如果不清楚书上有,我也有在tower上整理:关于输入输出的一个分享 try { HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); if (entity != null) { BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent())); String line = null; StringBuilder builder = new StringBuilder(); while ((line = br.readLine()) != null) { builder.append(line); } temp = builder.toString(); Log.i("result", temp); //runOnUiThread是填写UI的方法,因为在非主线程不允许填写UI runOnUiThread(new Runnable() { @Override public void run() { content.setText(temp); } }); } } catch (IOException e) { //可以 <SUF> } } }).start(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
true
55300_0
package com.lhm; /* 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的 是原来第几号的那位。 */ public class PeopleWeiCircle { public static void main(String[] args) { } public static void method(int n){ } }
MuziMin0222/muzimin-bigdata-study
muzimin-arithmetic-study/arithmetic-01/src/main/java/com/lhm/PeopleWeiCircle.java
98
/* 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的 是原来第几号的那位。 */
block_comment
zh-cn
package com.lhm; /* 有n个 <SUF>*/ public class PeopleWeiCircle { public static void main(String[] args) { } public static void method(int n){ } }
false
51544_7
package zliu.elliot.huawei; import java.util.Scanner; public class solution3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 地图大小 int n = scanner.nextInt(); // 怪兽 boolean[][] monster = new boolean[n][n]; int k = scanner.nextInt(); for (int i = 0; i < k; ++i) { int r = scanner.nextInt(); int c = scanner.nextInt(); monster[r][c] = true; } // 公主位置 int princessR = scanner.nextInt(); int princessC = scanner.nextInt(); // 王子 int knightR = scanner.nextInt(); int knightC = scanner.nextInt(); String[][] carrier = new String[n][n]; scanner.nextLine(); for (int i = 0; i < n; ++i) { String line = scanner.nextLine(); carrier[i] = line.trim().split(" "); } solution3 solution3 = new solution3(); solution3.carrier = carrier; solution3.monster = monster; solution3.princess = new int[]{princessR, princessC}; solution3.dfsSave(knightR, knightC, 0, 1); System.out.println(solution3.minTime); } int minTime = Integer.MAX_VALUE; boolean[][] monster = null; String[][] carrier = null; int[] princess = null; /** * * @param r 当前行 * @param c * @param timestamp 当前时间点 */ public void dfsSave(int r, int c, int timestamp, int wait) { if (timestamp>minTime) { // 超时剪枝 return; } if (r == princess[0] && c == princess[1]) { // 到达目标 minTime = Math.min(timestamp, minTime); return; } int nextCarrier = (timestamp+1)%3; if (r-1 >= 0 && !monster[r-1][c] && carrier[r-1][c].charAt(nextCarrier)=='0') { // 向上走 dfsSave(r-1, c, timestamp+1, 1); } if (r+1 < monster.length && !monster[r+1][c] && carrier[r+1][c].charAt(nextCarrier)=='0') { // 向下走 dfsSave(r+1, c, timestamp+1, 1); } if (c-1 >= 0 && !monster[r][c-1] && carrier[r][c-1].charAt(nextCarrier)=='0') { // 向左走 dfsSave(r, c-1, timestamp+1, 1); } if (c+1 < monster.length && !monster[r][c+1] && carrier[r][c+1].charAt(nextCarrier)=='0') { // 向右走 dfsSave(r, c+1, timestamp+1, 1); } if (carrier[r][c].charAt(nextCarrier)=='0' && wait <= 3) { // 原地不动 dfsSave(r,c, timestamp+1, wait+1); } } }
My-captain/algorithm
src/zliu/elliot/huawei/solution3.java
791
// 向左走
line_comment
zh-cn
package zliu.elliot.huawei; import java.util.Scanner; public class solution3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 地图大小 int n = scanner.nextInt(); // 怪兽 boolean[][] monster = new boolean[n][n]; int k = scanner.nextInt(); for (int i = 0; i < k; ++i) { int r = scanner.nextInt(); int c = scanner.nextInt(); monster[r][c] = true; } // 公主位置 int princessR = scanner.nextInt(); int princessC = scanner.nextInt(); // 王子 int knightR = scanner.nextInt(); int knightC = scanner.nextInt(); String[][] carrier = new String[n][n]; scanner.nextLine(); for (int i = 0; i < n; ++i) { String line = scanner.nextLine(); carrier[i] = line.trim().split(" "); } solution3 solution3 = new solution3(); solution3.carrier = carrier; solution3.monster = monster; solution3.princess = new int[]{princessR, princessC}; solution3.dfsSave(knightR, knightC, 0, 1); System.out.println(solution3.minTime); } int minTime = Integer.MAX_VALUE; boolean[][] monster = null; String[][] carrier = null; int[] princess = null; /** * * @param r 当前行 * @param c * @param timestamp 当前时间点 */ public void dfsSave(int r, int c, int timestamp, int wait) { if (timestamp>minTime) { // 超时剪枝 return; } if (r == princess[0] && c == princess[1]) { // 到达目标 minTime = Math.min(timestamp, minTime); return; } int nextCarrier = (timestamp+1)%3; if (r-1 >= 0 && !monster[r-1][c] && carrier[r-1][c].charAt(nextCarrier)=='0') { // 向上走 dfsSave(r-1, c, timestamp+1, 1); } if (r+1 < monster.length && !monster[r+1][c] && carrier[r+1][c].charAt(nextCarrier)=='0') { // 向下走 dfsSave(r+1, c, timestamp+1, 1); } if (c-1 >= 0 && !monster[r][c-1] && carrier[r][c-1].charAt(nextCarrier)=='0') { // 向左 <SUF> dfsSave(r, c-1, timestamp+1, 1); } if (c+1 < monster.length && !monster[r][c+1] && carrier[r][c+1].charAt(nextCarrier)=='0') { // 向右走 dfsSave(r, c+1, timestamp+1, 1); } if (carrier[r][c].charAt(nextCarrier)=='0' && wait <= 3) { // 原地不动 dfsSave(r,c, timestamp+1, wait+1); } } }
false
52379_0
package io.mycat.net2; import java.io.IOException; /** * NIOHandler是无状态的,多个连接共享一个,用于处理连接的事件,每个方法需要不阻塞,尽快返回结果 * * @author wuzh */ public interface NIOHandler<T extends Connection> { /** * 连接建立成功的通知事件 * * @param con * 当前连接 */ public void onConnected(T con) throws IOException; /** * 连接失败 * * @param con * 失败的连接 * @param e * 连接异常 */ public void onConnectFailed(T con, Throwable e); /** * 连接关闭通知 * @param con * @throws IOException */ public void onClosed(T con,String reason); /** * 收到数据需要处理 * * @param con * 当前连接 * @param data * 收到的数据包 */ void handle(T con, ByteBufferArray nioData); }
MyCATApache/Mycat-NIO
src/main/java/io/mycat/net2/NIOHandler.java
253
/** * NIOHandler是无状态的,多个连接共享一个,用于处理连接的事件,每个方法需要不阻塞,尽快返回结果 * * @author wuzh */
block_comment
zh-cn
package io.mycat.net2; import java.io.IOException; /** * NIO <SUF>*/ public interface NIOHandler<T extends Connection> { /** * 连接建立成功的通知事件 * * @param con * 当前连接 */ public void onConnected(T con) throws IOException; /** * 连接失败 * * @param con * 失败的连接 * @param e * 连接异常 */ public void onConnectFailed(T con, Throwable e); /** * 连接关闭通知 * @param con * @throws IOException */ public void onClosed(T con,String reason); /** * 收到数据需要处理 * * @param con * 当前连接 * @param data * 收到的数据包 */ void handle(T con, ByteBufferArray nioData); }
true
13686_6
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.config; import java.io.IOException; import java.net.StandardSocketOptions; import java.nio.channels.NetworkChannel; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import io.mycat.backend.datasource.PhysicalDBNode; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.config.model.FirewallConfig; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.SystemConfig; import io.mycat.config.model.UserConfig; import io.mycat.net.AbstractConnection; import io.mycat.util.TimeUtil; /** * @author mycat */ public class MycatConfig { private static final int RELOAD = 1; private static final int ROLLBACK = 2; private static final int RELOAD_ALL = 3; private volatile SystemConfig system; private volatile MycatCluster cluster; private volatile MycatCluster _cluster; private volatile FirewallConfig firewall; private volatile FirewallConfig _firewall; private volatile Map<String, UserConfig> users; private volatile Map<String, UserConfig> _users; private volatile Map<String, SchemaConfig> schemas; private volatile Map<String, SchemaConfig> _schemas; private volatile Map<String, PhysicalDBNode> dataNodes; private volatile Map<String, PhysicalDBNode> _dataNodes; private volatile Map<String, PhysicalDBPool> dataHosts; private volatile Map<String, PhysicalDBPool> _dataHosts; private long reloadTime; private long rollbackTime; private int status; private final ReentrantLock lock; public MycatConfig() { //读取schema.xml,rule.xml和server.xml ConfigInitializer confInit = new ConfigInitializer(true); this.system = confInit.getSystem(); this.users = confInit.getUsers(); this.schemas = confInit.getSchemas(); this.dataHosts = confInit.getDataHosts(); this.dataNodes = confInit.getDataNodes(); for (PhysicalDBPool dbPool : dataHosts.values()) { dbPool.setSchemas(getDataNodeSchemasOfDataHost(dbPool.getHostName())); } this.firewall = confInit.getFirewall(); this.cluster = confInit.getCluster(); //初始化重加载配置时间 this.reloadTime = TimeUtil.currentTimeMillis(); this.rollbackTime = -1L; this.status = RELOAD; //配置加载锁 this.lock = new ReentrantLock(); } public SystemConfig getSystem() { return system; } public void setSocketParams(AbstractConnection con, boolean isFrontChannel) throws IOException { int sorcvbuf = 0; int sosndbuf = 0; int soNoDelay = 0; if ( isFrontChannel ) { sorcvbuf = system.getFrontsocketsorcvbuf(); sosndbuf = system.getFrontsocketsosndbuf(); soNoDelay = system.getFrontSocketNoDelay(); } else { sorcvbuf = system.getBacksocketsorcvbuf(); sosndbuf = system.getBacksocketsosndbuf(); soNoDelay = system.getBackSocketNoDelay(); } NetworkChannel channel = con.getChannel(); channel.setOption(StandardSocketOptions.SO_RCVBUF, sorcvbuf); channel.setOption(StandardSocketOptions.SO_SNDBUF, sosndbuf); channel.setOption(StandardSocketOptions.TCP_NODELAY, soNoDelay == 1); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); con.setMaxPacketSize(system.getMaxPacketSize()); con.setPacketHeaderSize(system.getPacketHeaderSize()); con.setIdleTimeout(system.getIdleTimeout()); con.setCharset(system.getCharset()); } public Map<String, UserConfig> getUsers() { return users; } public Map<String, UserConfig> getBackupUsers() { return _users; } public Map<String, SchemaConfig> getSchemas() { return schemas; } public Map<String, SchemaConfig> getBackupSchemas() { return _schemas; } public Map<String, PhysicalDBNode> getDataNodes() { return dataNodes; } public void setDataNodes( Map<String, PhysicalDBNode> map) { this.dataNodes = map; } public String[] getDataNodeSchemasOfDataHost(String dataHost) { ArrayList<String> schemas = new ArrayList<String>(30); for (PhysicalDBNode dn: dataNodes.values()) { if (dn.getDbPool().getHostName().equals(dataHost)) { schemas.add(dn.getDatabase()); } } return schemas.toArray(new String[schemas.size()]); } public Map<String, PhysicalDBNode> getBackupDataNodes() { return _dataNodes; } public Map<String, PhysicalDBPool> getDataHosts() { return dataHosts; } public Map<String, PhysicalDBPool> getBackupDataHosts() { return _dataHosts; } public MycatCluster getCluster() { return cluster; } public MycatCluster getBackupCluster() { return _cluster; } public FirewallConfig getFirewall() { return firewall; } public FirewallConfig getBackupFirewall() { return _firewall; } public ReentrantLock getLock() { return lock; } public long getReloadTime() { return reloadTime; } public long getRollbackTime() { return rollbackTime; } public void reload( Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean reloadAll) { apply(newUsers, newSchemas, newDataNodes, newDataHosts, newCluster, newFirewall, reloadAll); this.reloadTime = TimeUtil.currentTimeMillis(); this.status = reloadAll?RELOAD_ALL:RELOAD; } public boolean canRollback() { if (_users == null || _schemas == null || _dataNodes == null || _dataHosts == null || _cluster == null || _firewall == null || status == ROLLBACK) { return false; } else { return true; } } public void rollback( Map<String, UserConfig> users, Map<String, SchemaConfig> schemas, Map<String, PhysicalDBNode> dataNodes, Map<String, PhysicalDBPool> dataHosts, MycatCluster cluster, FirewallConfig firewall) { apply(users, schemas, dataNodes, dataHosts, cluster, firewall, status==RELOAD_ALL); this.rollbackTime = TimeUtil.currentTimeMillis(); this.status = ROLLBACK; } private void apply(Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean isLoadAll) { final ReentrantLock lock = this.lock; lock.lock(); try { // old 处理 // 1、停止老的数据源心跳 // 2、备份老的数据源配置 //-------------------------------------------- if (isLoadAll) { Map<String, PhysicalDBPool> oldDataHosts = this.dataHosts; if (oldDataHosts != null) { for (PhysicalDBPool oldDbPool : oldDataHosts.values()) { if (oldDbPool != null) { oldDbPool.stopHeartbeat(); } } } this._dataNodes = this.dataNodes; this._dataHosts = this.dataHosts; } this._users = this.users; this._schemas = this.schemas; this._cluster = this.cluster; this._firewall = this.firewall; // new 处理 // 1、启动新的数据源心跳 // 2、执行新的配置 //--------------------------------------------------- if (isLoadAll) { if (newDataHosts != null) { for (PhysicalDBPool newDbPool : newDataHosts.values()) { if ( newDbPool != null) { newDbPool.startHeartbeat(); } } } this.dataNodes = newDataNodes; this.dataHosts = newDataHosts; } this.users = newUsers; this.schemas = newSchemas; this.cluster = newCluster; this.firewall = newFirewall; } finally { lock.unlock(); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/config/MycatConfig.java
2,528
// 1、停止老的数据源心跳
line_comment
zh-cn
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.config; import java.io.IOException; import java.net.StandardSocketOptions; import java.nio.channels.NetworkChannel; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import io.mycat.backend.datasource.PhysicalDBNode; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.config.model.FirewallConfig; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.SystemConfig; import io.mycat.config.model.UserConfig; import io.mycat.net.AbstractConnection; import io.mycat.util.TimeUtil; /** * @author mycat */ public class MycatConfig { private static final int RELOAD = 1; private static final int ROLLBACK = 2; private static final int RELOAD_ALL = 3; private volatile SystemConfig system; private volatile MycatCluster cluster; private volatile MycatCluster _cluster; private volatile FirewallConfig firewall; private volatile FirewallConfig _firewall; private volatile Map<String, UserConfig> users; private volatile Map<String, UserConfig> _users; private volatile Map<String, SchemaConfig> schemas; private volatile Map<String, SchemaConfig> _schemas; private volatile Map<String, PhysicalDBNode> dataNodes; private volatile Map<String, PhysicalDBNode> _dataNodes; private volatile Map<String, PhysicalDBPool> dataHosts; private volatile Map<String, PhysicalDBPool> _dataHosts; private long reloadTime; private long rollbackTime; private int status; private final ReentrantLock lock; public MycatConfig() { //读取schema.xml,rule.xml和server.xml ConfigInitializer confInit = new ConfigInitializer(true); this.system = confInit.getSystem(); this.users = confInit.getUsers(); this.schemas = confInit.getSchemas(); this.dataHosts = confInit.getDataHosts(); this.dataNodes = confInit.getDataNodes(); for (PhysicalDBPool dbPool : dataHosts.values()) { dbPool.setSchemas(getDataNodeSchemasOfDataHost(dbPool.getHostName())); } this.firewall = confInit.getFirewall(); this.cluster = confInit.getCluster(); //初始化重加载配置时间 this.reloadTime = TimeUtil.currentTimeMillis(); this.rollbackTime = -1L; this.status = RELOAD; //配置加载锁 this.lock = new ReentrantLock(); } public SystemConfig getSystem() { return system; } public void setSocketParams(AbstractConnection con, boolean isFrontChannel) throws IOException { int sorcvbuf = 0; int sosndbuf = 0; int soNoDelay = 0; if ( isFrontChannel ) { sorcvbuf = system.getFrontsocketsorcvbuf(); sosndbuf = system.getFrontsocketsosndbuf(); soNoDelay = system.getFrontSocketNoDelay(); } else { sorcvbuf = system.getBacksocketsorcvbuf(); sosndbuf = system.getBacksocketsosndbuf(); soNoDelay = system.getBackSocketNoDelay(); } NetworkChannel channel = con.getChannel(); channel.setOption(StandardSocketOptions.SO_RCVBUF, sorcvbuf); channel.setOption(StandardSocketOptions.SO_SNDBUF, sosndbuf); channel.setOption(StandardSocketOptions.TCP_NODELAY, soNoDelay == 1); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); con.setMaxPacketSize(system.getMaxPacketSize()); con.setPacketHeaderSize(system.getPacketHeaderSize()); con.setIdleTimeout(system.getIdleTimeout()); con.setCharset(system.getCharset()); } public Map<String, UserConfig> getUsers() { return users; } public Map<String, UserConfig> getBackupUsers() { return _users; } public Map<String, SchemaConfig> getSchemas() { return schemas; } public Map<String, SchemaConfig> getBackupSchemas() { return _schemas; } public Map<String, PhysicalDBNode> getDataNodes() { return dataNodes; } public void setDataNodes( Map<String, PhysicalDBNode> map) { this.dataNodes = map; } public String[] getDataNodeSchemasOfDataHost(String dataHost) { ArrayList<String> schemas = new ArrayList<String>(30); for (PhysicalDBNode dn: dataNodes.values()) { if (dn.getDbPool().getHostName().equals(dataHost)) { schemas.add(dn.getDatabase()); } } return schemas.toArray(new String[schemas.size()]); } public Map<String, PhysicalDBNode> getBackupDataNodes() { return _dataNodes; } public Map<String, PhysicalDBPool> getDataHosts() { return dataHosts; } public Map<String, PhysicalDBPool> getBackupDataHosts() { return _dataHosts; } public MycatCluster getCluster() { return cluster; } public MycatCluster getBackupCluster() { return _cluster; } public FirewallConfig getFirewall() { return firewall; } public FirewallConfig getBackupFirewall() { return _firewall; } public ReentrantLock getLock() { return lock; } public long getReloadTime() { return reloadTime; } public long getRollbackTime() { return rollbackTime; } public void reload( Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean reloadAll) { apply(newUsers, newSchemas, newDataNodes, newDataHosts, newCluster, newFirewall, reloadAll); this.reloadTime = TimeUtil.currentTimeMillis(); this.status = reloadAll?RELOAD_ALL:RELOAD; } public boolean canRollback() { if (_users == null || _schemas == null || _dataNodes == null || _dataHosts == null || _cluster == null || _firewall == null || status == ROLLBACK) { return false; } else { return true; } } public void rollback( Map<String, UserConfig> users, Map<String, SchemaConfig> schemas, Map<String, PhysicalDBNode> dataNodes, Map<String, PhysicalDBPool> dataHosts, MycatCluster cluster, FirewallConfig firewall) { apply(users, schemas, dataNodes, dataHosts, cluster, firewall, status==RELOAD_ALL); this.rollbackTime = TimeUtil.currentTimeMillis(); this.status = ROLLBACK; } private void apply(Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean isLoadAll) { final ReentrantLock lock = this.lock; lock.lock(); try { // old 处理 // 1、 <SUF> // 2、备份老的数据源配置 //-------------------------------------------- if (isLoadAll) { Map<String, PhysicalDBPool> oldDataHosts = this.dataHosts; if (oldDataHosts != null) { for (PhysicalDBPool oldDbPool : oldDataHosts.values()) { if (oldDbPool != null) { oldDbPool.stopHeartbeat(); } } } this._dataNodes = this.dataNodes; this._dataHosts = this.dataHosts; } this._users = this.users; this._schemas = this.schemas; this._cluster = this.cluster; this._firewall = this.firewall; // new 处理 // 1、启动新的数据源心跳 // 2、执行新的配置 //--------------------------------------------------- if (isLoadAll) { if (newDataHosts != null) { for (PhysicalDBPool newDbPool : newDataHosts.values()) { if ( newDbPool != null) { newDbPool.startHeartbeat(); } } } this.dataNodes = newDataNodes; this.dataHosts = newDataHosts; } this.users = newUsers; this.schemas = newSchemas; this.cluster = newCluster; this.firewall = newFirewall; } finally { lock.unlock(); } } }
false
13418_81
///* // * Licensed to the Apache Software Foundation (ASF) under one or more // * contributor license agreements. See the NOTICE file distributed with // * this work for additional information regarding copyright ownership. // * The ASF licenses this file to you 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 io.mycat.util; // //import com.alibaba.druid.sql.ast.SQLStatement; //import com.alibaba.druid.sql.ast.statement.SQLInsertInto; //import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; //import io.mycat.Partition; //import io.mycat.MetaClusterCurrent; //import io.mycat.MetadataManager; //import io.mycat.TableHandler; //import io.mycat.calcite.executor.MycatPreparedStatementUtil; //import lombok.AllArgsConstructor; //import lombok.Getter; //import lombok.ToString; //import lombok.extern.slf4j.Slf4j; // //import java.sql.Connection; //import java.sql.PreparedStatement; //import java.sql.ResultSet; //import java.sql.SQLException; //import java.util.Arrays; //import java.util.List; //import java.util.Objects; // //import static java.sql.Statement.NO_GENERATED_KEYS; //import static java.sql.Statement.RETURN_GENERATED_KEYS; // ///** // * 真正要发给后端的sql语句 // * 用于把发送SQL过程中的变量数据内聚到一起, 不需要开发者从各个地方寻找数据。 // * @param <T> // * @author wangzihaogithub 2020-12-29 // */ //@Slf4j //@Getter //@ToString //@AllArgsConstructor //public class SQL<T extends SQLStatement> { // private String parameterizedSql; // private Partition partition; // private T statement; // private List<Object> parameters; // // public String getTarget() { // return partition.getTargetName(); // } // // public static <T extends SQLStatement> SQL<T> of(String parameterizedSql, // Partition partition, T statement, T originStatement, List<Object> parameters){ // SQL sql; // if(statement instanceof SQLUpdateStatement){ // sql = new UpdateSQL<>(parameterizedSql, partition,(SQLUpdateStatement)statement, (SQLUpdateStatement)originStatement,parameters); // }else { // sql = new SQL<>(parameterizedSql, partition,statement,parameters); // } // return sql; // } // // public static <T extends SQLStatement> SQL<T> of(String parameterizedSql, // Partition partition, T statement, List<Object> parameters){ // SQL sql; // sql = new SQL<>(parameterizedSql, partition,statement,parameters); // return sql; // } // // public UpdateResult executeUpdate(Connection connection) throws SQLException { // return executeUpdate(connection,statement instanceof SQLInsertInto); // } // // public UpdateResult executeUpdate(Connection connection,boolean autoGeneratedKeys) throws SQLException { // List<Object> parameters = getParameters(); // if (!parameters.isEmpty()&&parameters.get(0) instanceof List){ // PreparedStatement preparedStatement = connection.prepareStatement(parameterizedSql, autoGeneratedKeys? RETURN_GENERATED_KEYS : NO_GENERATED_KEYS); // for (Object parameter : parameters) { // MycatPreparedStatementUtil.setParams(preparedStatement,(List) parameter); // preparedStatement.addBatch(); // } // int[] affectedRow = preparedStatement.executeBatch(); // Long lastInsertId = autoGeneratedKeys? getInSingleSqlLastInsertId(preparedStatement) : null; // return new UpdateResult(Arrays.stream(affectedRow).sum(),lastInsertId); // }else { // PreparedStatement preparedStatement = connection.prepareStatement(parameterizedSql, autoGeneratedKeys? RETURN_GENERATED_KEYS : NO_GENERATED_KEYS); // MycatPreparedStatementUtil.setParams(preparedStatement, this.parameters); // int affectedRow = preparedStatement.executeUpdate(); // Long lastInsertId = autoGeneratedKeys? getInSingleSqlLastInsertId(preparedStatement) : null; // return new UpdateResult(affectedRow,lastInsertId); // } // // } // // /** // * ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); // * 会生成多个值,其中第一个是真正的值 // * // * @param preparedStatement // * @return // * @throws SQLException // */ // public static Long getInSingleSqlLastInsertId(java.sql.Statement preparedStatement) throws SQLException { // Long lastInsertId = null; // ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); // if (generatedKeys != null) { // if (generatedKeys.next()) { // long generatedKeysLong = generatedKeys.getBigDecimal(1).longValue(); // if (log.isDebugEnabled()) { // log.debug("preparedStatement:{} insertId:{}", preparedStatement, generatedKeysLong); // } // lastInsertId = Math.max(generatedKeysLong,0); // } // } // return lastInsertId; // } // // // @Getter // @AllArgsConstructor // public static class UpdateResult{ // private int affectedRow; // private Long lastInsertId; // } // // public TableHandler getTable(){ // TableHandler table = getMetadataManager().getTable(partition.getSchema(), partition.getTable()); // return table; // } // // public MetadataManager getMetadataManager(){ // MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class); // return metadataManager; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SQL that = (SQL) o; // return Objects.equals(that.getTarget(),getTarget()) // && Objects.equals(that.parameterizedSql,this.parameterizedSql); // } // // @Override // public int hashCode() { // return Objects.hash(this.parameterizedSql,getTarget()); // } //}
MyCATApache/Mycat2
hbt/src/main/java/io/mycat/util/SQL.java
1,671
// * 会生成多个值,其中第一个是真正的值
line_comment
zh-cn
///* // * Licensed to the Apache Software Foundation (ASF) under one or more // * contributor license agreements. See the NOTICE file distributed with // * this work for additional information regarding copyright ownership. // * The ASF licenses this file to you 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 io.mycat.util; // //import com.alibaba.druid.sql.ast.SQLStatement; //import com.alibaba.druid.sql.ast.statement.SQLInsertInto; //import com.alibaba.druid.sql.ast.statement.SQLUpdateStatement; //import io.mycat.Partition; //import io.mycat.MetaClusterCurrent; //import io.mycat.MetadataManager; //import io.mycat.TableHandler; //import io.mycat.calcite.executor.MycatPreparedStatementUtil; //import lombok.AllArgsConstructor; //import lombok.Getter; //import lombok.ToString; //import lombok.extern.slf4j.Slf4j; // //import java.sql.Connection; //import java.sql.PreparedStatement; //import java.sql.ResultSet; //import java.sql.SQLException; //import java.util.Arrays; //import java.util.List; //import java.util.Objects; // //import static java.sql.Statement.NO_GENERATED_KEYS; //import static java.sql.Statement.RETURN_GENERATED_KEYS; // ///** // * 真正要发给后端的sql语句 // * 用于把发送SQL过程中的变量数据内聚到一起, 不需要开发者从各个地方寻找数据。 // * @param <T> // * @author wangzihaogithub 2020-12-29 // */ //@Slf4j //@Getter //@ToString //@AllArgsConstructor //public class SQL<T extends SQLStatement> { // private String parameterizedSql; // private Partition partition; // private T statement; // private List<Object> parameters; // // public String getTarget() { // return partition.getTargetName(); // } // // public static <T extends SQLStatement> SQL<T> of(String parameterizedSql, // Partition partition, T statement, T originStatement, List<Object> parameters){ // SQL sql; // if(statement instanceof SQLUpdateStatement){ // sql = new UpdateSQL<>(parameterizedSql, partition,(SQLUpdateStatement)statement, (SQLUpdateStatement)originStatement,parameters); // }else { // sql = new SQL<>(parameterizedSql, partition,statement,parameters); // } // return sql; // } // // public static <T extends SQLStatement> SQL<T> of(String parameterizedSql, // Partition partition, T statement, List<Object> parameters){ // SQL sql; // sql = new SQL<>(parameterizedSql, partition,statement,parameters); // return sql; // } // // public UpdateResult executeUpdate(Connection connection) throws SQLException { // return executeUpdate(connection,statement instanceof SQLInsertInto); // } // // public UpdateResult executeUpdate(Connection connection,boolean autoGeneratedKeys) throws SQLException { // List<Object> parameters = getParameters(); // if (!parameters.isEmpty()&&parameters.get(0) instanceof List){ // PreparedStatement preparedStatement = connection.prepareStatement(parameterizedSql, autoGeneratedKeys? RETURN_GENERATED_KEYS : NO_GENERATED_KEYS); // for (Object parameter : parameters) { // MycatPreparedStatementUtil.setParams(preparedStatement,(List) parameter); // preparedStatement.addBatch(); // } // int[] affectedRow = preparedStatement.executeBatch(); // Long lastInsertId = autoGeneratedKeys? getInSingleSqlLastInsertId(preparedStatement) : null; // return new UpdateResult(Arrays.stream(affectedRow).sum(),lastInsertId); // }else { // PreparedStatement preparedStatement = connection.prepareStatement(parameterizedSql, autoGeneratedKeys? RETURN_GENERATED_KEYS : NO_GENERATED_KEYS); // MycatPreparedStatementUtil.setParams(preparedStatement, this.parameters); // int affectedRow = preparedStatement.executeUpdate(); // Long lastInsertId = autoGeneratedKeys? getInSingleSqlLastInsertId(preparedStatement) : null; // return new UpdateResult(affectedRow,lastInsertId); // } // // } // // /** // * ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); // * 会生 <SUF> // * // * @param preparedStatement // * @return // * @throws SQLException // */ // public static Long getInSingleSqlLastInsertId(java.sql.Statement preparedStatement) throws SQLException { // Long lastInsertId = null; // ResultSet generatedKeys = preparedStatement.getGeneratedKeys(); // if (generatedKeys != null) { // if (generatedKeys.next()) { // long generatedKeysLong = generatedKeys.getBigDecimal(1).longValue(); // if (log.isDebugEnabled()) { // log.debug("preparedStatement:{} insertId:{}", preparedStatement, generatedKeysLong); // } // lastInsertId = Math.max(generatedKeysLong,0); // } // } // return lastInsertId; // } // // // @Getter // @AllArgsConstructor // public static class UpdateResult{ // private int affectedRow; // private Long lastInsertId; // } // // public TableHandler getTable(){ // TableHandler table = getMetadataManager().getTable(partition.getSchema(), partition.getTable()); // return table; // } // // public MetadataManager getMetadataManager(){ // MetadataManager metadataManager = MetaClusterCurrent.wrapper(MetadataManager.class); // return metadataManager; // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SQL that = (SQL) o; // return Objects.equals(that.getTarget(),getTarget()) // && Objects.equals(that.parameterizedSql,this.parameterizedSql); // } // // @Override // public int hashCode() { // return Objects.hash(this.parameterizedSql,getTarget()); // } //}
true
9755_3
package io.mycat.fabric.phdc.entity; import java.util.Date; import javax.persistence.*; @Table(name = "tb_result") public class Result { /** * ID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 预约ID */ @Column(name = "reserve_id") private Integer reserveId; /** * 预约人ID */ @Column(name = "member_id") private Integer memberId; /** * 检查项ID */ @Column(name = "exam_dict_id") private Integer examDictId; /** * 科室医生 */ @Column(name = "depart_doctor") private String departDoctor; /** * 医生 */ @Column(name = "check_doctor") private String checkDoctor; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 结果状态 1)未出结果 2)已出结果 */ private Byte status; /** * 检查结果 */ private String result; /** * 结论 */ private String summary; /** * 获取ID * * @return id - ID */ public Integer getId() { return id; } /** * 设置ID * * @param id ID */ public void setId(Integer id) { this.id = id; } /** * 获取预约ID * * @return reserve_id - 预约ID */ public Integer getReserveId() { return reserveId; } /** * 设置预约ID * * @param reserveId 预约ID */ public void setReserveId(Integer reserveId) { this.reserveId = reserveId; } /** * 获取预约人ID * * @return member_id - 预约人ID */ public Integer getMemberId() { return memberId; } /** * 设置预约人ID * * @param memberId 预约人ID */ public void setMemberId(Integer memberId) { this.memberId = memberId; } /** * 获取检查项ID * * @return exam_dict_id - 检查项ID */ public Integer getExamDictId() { return examDictId; } /** * 设置检查项ID * * @param examDictId 检查项ID */ public void setExamDictId(Integer examDictId) { this.examDictId = examDictId; } /** * 获取科室医生 * * @return depart_doctor - 科室医生 */ public String getDepartDoctor() { return departDoctor; } /** * 设置科室医生 * * @param departDoctor 科室医生 */ public void setDepartDoctor(String departDoctor) { this.departDoctor = departDoctor == null ? null : departDoctor.trim(); } /** * 获取医生 * * @return check_doctor - 医生 */ public String getCheckDoctor() { return checkDoctor; } /** * 设置医生 * * @param checkDoctor 医生 */ public void setCheckDoctor(String checkDoctor) { this.checkDoctor = checkDoctor == null ? null : checkDoctor.trim(); } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取结果状态 1)未出结果 2)已出结果 * * @return status - 结果状态 1)未出结果 2)已出结果 */ public Byte getStatus() { return status; } /** * 设置结果状态 1)未出结果 2)已出结果 * * @param status 结果状态 1)未出结果 2)已出结果 */ public void setStatus(Byte status) { this.status = status; } /** * 获取检查结果 * * @return result - 检查结果 */ public String getResult() { return result; } /** * 设置检查结果 * * @param result 检查结果 */ public void setResult(String result) { this.result = result == null ? null : result.trim(); } /** * 获取结论 * * @return summary - 结论 */ public String getSummary() { return summary; } /** * 设置结论 * * @param summary 结论 */ public void setSummary(String summary) { this.summary = summary == null ? null : summary.trim(); } }
MyCATApache/SuperLedger
PHDC/java/src/main/java/io/mycat/fabric/phdc/entity/Result.java
1,151
/** * 检查项ID */
block_comment
zh-cn
package io.mycat.fabric.phdc.entity; import java.util.Date; import javax.persistence.*; @Table(name = "tb_result") public class Result { /** * ID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 预约ID */ @Column(name = "reserve_id") private Integer reserveId; /** * 预约人ID */ @Column(name = "member_id") private Integer memberId; /** * 检查项 <SUF>*/ @Column(name = "exam_dict_id") private Integer examDictId; /** * 科室医生 */ @Column(name = "depart_doctor") private String departDoctor; /** * 医生 */ @Column(name = "check_doctor") private String checkDoctor; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 结果状态 1)未出结果 2)已出结果 */ private Byte status; /** * 检查结果 */ private String result; /** * 结论 */ private String summary; /** * 获取ID * * @return id - ID */ public Integer getId() { return id; } /** * 设置ID * * @param id ID */ public void setId(Integer id) { this.id = id; } /** * 获取预约ID * * @return reserve_id - 预约ID */ public Integer getReserveId() { return reserveId; } /** * 设置预约ID * * @param reserveId 预约ID */ public void setReserveId(Integer reserveId) { this.reserveId = reserveId; } /** * 获取预约人ID * * @return member_id - 预约人ID */ public Integer getMemberId() { return memberId; } /** * 设置预约人ID * * @param memberId 预约人ID */ public void setMemberId(Integer memberId) { this.memberId = memberId; } /** * 获取检查项ID * * @return exam_dict_id - 检查项ID */ public Integer getExamDictId() { return examDictId; } /** * 设置检查项ID * * @param examDictId 检查项ID */ public void setExamDictId(Integer examDictId) { this.examDictId = examDictId; } /** * 获取科室医生 * * @return depart_doctor - 科室医生 */ public String getDepartDoctor() { return departDoctor; } /** * 设置科室医生 * * @param departDoctor 科室医生 */ public void setDepartDoctor(String departDoctor) { this.departDoctor = departDoctor == null ? null : departDoctor.trim(); } /** * 获取医生 * * @return check_doctor - 医生 */ public String getCheckDoctor() { return checkDoctor; } /** * 设置医生 * * @param checkDoctor 医生 */ public void setCheckDoctor(String checkDoctor) { this.checkDoctor = checkDoctor == null ? null : checkDoctor.trim(); } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取结果状态 1)未出结果 2)已出结果 * * @return status - 结果状态 1)未出结果 2)已出结果 */ public Byte getStatus() { return status; } /** * 设置结果状态 1)未出结果 2)已出结果 * * @param status 结果状态 1)未出结果 2)已出结果 */ public void setStatus(Byte status) { this.status = status; } /** * 获取检查结果 * * @return result - 检查结果 */ public String getResult() { return result; } /** * 设置检查结果 * * @param result 检查结果 */ public void setResult(String result) { this.result = result == null ? null : result.trim(); } /** * 获取结论 * * @return summary - 结论 */ public String getSummary() { return summary; } /** * 设置结论 * * @param summary 结论 */ public void setSummary(String summary) { this.summary = summary == null ? null : summary.trim(); } }
false
21298_4
/* * Copyright (c) 2016, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.front; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.ArrayList; import io.mycat.SQLEngineCtx; import io.mycat.backend.MySQLBackendConnection; import io.mycat.beans.SchemaBean; import io.mycat.engine.NoneBlockTask; import io.mycat.engine.UserSession; import io.mycat.mysql.MySQLConnection; import io.mycat.mysql.state.frontend.FrontendInitialState; /** * front mysql connection * * @author wuzhihui */ public class MySQLFrontConnection extends MySQLConnection { private final UserSession session; private SchemaBean mycatSchema; private MySQLBackendConnection backendConnection; private final ArrayList<NoneBlockTask> todoTasks = new ArrayList<NoneBlockTask>(2); public MySQLFrontConnection(SocketChannel channel) { super(channel, FrontendInitialState.INSTANCE); session = new UserSession(); } @Override public boolean init() throws IOException { setProcessKey(channel.register(getSelector(), SelectionKey.OP_CONNECT, this)); this.getProtocolStateMachine().driveState(); return true; } /** * 客戶端連接或者設置Schema的時候,需要調用此方法,確定是連接到了普通的Schema還是分片Schema * * @param schema * @throws IOException */ public boolean setFrontSchema(String schema) throws IOException { //TODO 此处应该重新实现 SchemaBean mycatSchema = null; if (schema != null) { mycatSchema = SQLEngineCtx.INSTANCE().getMycatSchema(schema); if (mycatSchema == null) { return false; } this.mycatSchema = mycatSchema; if (!mycatSchema.isNormalSchema()) { this.session.changeCmdHandler(SQLEngineCtx.INSTANCE().getPartionSchemaSQLCmdHandler()); } else { session.changeCmdHandler(SQLEngineCtx.INSTANCE().getNomalSchemaSQLCmdHandler()); } return true; } else { // 默认设置为不分片的SQL处理器 session.changeCmdHandler(SQLEngineCtx.INSTANCE().getNomalSchemaSQLCmdHandler()); return true; } } public void executePendingTask() { if (todoTasks.isEmpty()) { return; } NoneBlockTask task = todoTasks.remove(0); try { task.execute(); } catch (Exception e) { } } public void addTodoTask(NoneBlockTask task) { todoTasks.add(task); } public UserSession getSession() { return this.session; } public SchemaBean getMycatSchema() { return mycatSchema; } public void setMycatSchema(SchemaBean mycatSchema) { this.mycatSchema = mycatSchema; } public MySQLBackendConnection getBackendConnection() { return backendConnection; } public void setBackendConnection(MySQLBackendConnection backendConnection) { this.backendConnection = backendConnection; } }
MyCATApache/abandomed
Mycat-Core/src/main/java/io/mycat/front/MySQLFrontConnection.java
1,015
// 默认设置为不分片的SQL处理器
line_comment
zh-cn
/* * Copyright (c) 2016, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, as published by the * Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.front; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.SocketChannel; import java.util.ArrayList; import io.mycat.SQLEngineCtx; import io.mycat.backend.MySQLBackendConnection; import io.mycat.beans.SchemaBean; import io.mycat.engine.NoneBlockTask; import io.mycat.engine.UserSession; import io.mycat.mysql.MySQLConnection; import io.mycat.mysql.state.frontend.FrontendInitialState; /** * front mysql connection * * @author wuzhihui */ public class MySQLFrontConnection extends MySQLConnection { private final UserSession session; private SchemaBean mycatSchema; private MySQLBackendConnection backendConnection; private final ArrayList<NoneBlockTask> todoTasks = new ArrayList<NoneBlockTask>(2); public MySQLFrontConnection(SocketChannel channel) { super(channel, FrontendInitialState.INSTANCE); session = new UserSession(); } @Override public boolean init() throws IOException { setProcessKey(channel.register(getSelector(), SelectionKey.OP_CONNECT, this)); this.getProtocolStateMachine().driveState(); return true; } /** * 客戶端連接或者設置Schema的時候,需要調用此方法,確定是連接到了普通的Schema還是分片Schema * * @param schema * @throws IOException */ public boolean setFrontSchema(String schema) throws IOException { //TODO 此处应该重新实现 SchemaBean mycatSchema = null; if (schema != null) { mycatSchema = SQLEngineCtx.INSTANCE().getMycatSchema(schema); if (mycatSchema == null) { return false; } this.mycatSchema = mycatSchema; if (!mycatSchema.isNormalSchema()) { this.session.changeCmdHandler(SQLEngineCtx.INSTANCE().getPartionSchemaSQLCmdHandler()); } else { session.changeCmdHandler(SQLEngineCtx.INSTANCE().getNomalSchemaSQLCmdHandler()); } return true; } else { // 默认 <SUF> session.changeCmdHandler(SQLEngineCtx.INSTANCE().getNomalSchemaSQLCmdHandler()); return true; } } public void executePendingTask() { if (todoTasks.isEmpty()) { return; } NoneBlockTask task = todoTasks.remove(0); try { task.execute(); } catch (Exception e) { } } public void addTodoTask(NoneBlockTask task) { todoTasks.add(task); } public UserSession getSession() { return this.session; } public SchemaBean getMycatSchema() { return mycatSchema; } public void setMycatSchema(SchemaBean mycatSchema) { this.mycatSchema = mycatSchema; } public MySQLBackendConnection getBackendConnection() { return backendConnection; } public void setBackendConnection(MySQLBackendConnection backendConnection) { this.backendConnection = backendConnection; } }
true
871_1
package com.xu.drools.rule.complexProblem; import com.xu.drools.bean.Golfer; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * 使用kmodule的方式调用drools * /resources/META-INF/kmodule.xml * 高尔夫球员站位问题 */ public class GolferProblem { /** * 已知有四个高尔夫球员,他们的名字是Fred,Joe,Bob,Tom; * 今天他们分别穿着红色,蓝色,橙色,以及格子衣服,并且他们按照从左往右的顺序站成一排。 * 我们将最左边的位置定为1,最右边的位置定为4,中间依次是2,3位置。 * 现在我们了解的情况是: * 1.高尔夫球员Fred,目前不知道他的位置和衣服颜色 * 2.Fred右边紧挨着的球员穿蓝色衣服 * 3.Joe排在第2个位置 * 4.Bob穿着格子短裤 * 5.Tom没有排在第1位或第4位,也没有穿橙色衣服 * 请问,这四名球员的位置和衣服颜色。 */ public static void main(final String[] args) { KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); System.out.println(kc.verify().getMessages().toString()); execute(kc); } private static void execute(KieContainer kc) { KieSession ksession = kc.newKieSession("mingKS"); String[] names = new String[]{"Fred", "Joe", "Bob", "Tom"}; String[] colors = new String[]{"red", "blue", "plaid", "orange"}; int[] positions = new int[]{1, 2, 3, 4}; for (String name : names) { for (String color : colors) { for (int position : positions) { ksession.insert(new Golfer(name, color, position)); } } } ksession.fireAllRules(); ksession.dispose(); } }
MyHerux/drools-springboot
src/main/java/com/xu/drools/rule/complexProblem/GolferProblem.java
566
/** * 已知有四个高尔夫球员,他们的名字是Fred,Joe,Bob,Tom; * 今天他们分别穿着红色,蓝色,橙色,以及格子衣服,并且他们按照从左往右的顺序站成一排。 * 我们将最左边的位置定为1,最右边的位置定为4,中间依次是2,3位置。 * 现在我们了解的情况是: * 1.高尔夫球员Fred,目前不知道他的位置和衣服颜色 * 2.Fred右边紧挨着的球员穿蓝色衣服 * 3.Joe排在第2个位置 * 4.Bob穿着格子短裤 * 5.Tom没有排在第1位或第4位,也没有穿橙色衣服 * 请问,这四名球员的位置和衣服颜色。 */
block_comment
zh-cn
package com.xu.drools.rule.complexProblem; import com.xu.drools.bean.Golfer; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * 使用kmodule的方式调用drools * /resources/META-INF/kmodule.xml * 高尔夫球员站位问题 */ public class GolferProblem { /** * 已知有 <SUF>*/ public static void main(final String[] args) { KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); System.out.println(kc.verify().getMessages().toString()); execute(kc); } private static void execute(KieContainer kc) { KieSession ksession = kc.newKieSession("mingKS"); String[] names = new String[]{"Fred", "Joe", "Bob", "Tom"}; String[] colors = new String[]{"red", "blue", "plaid", "orange"}; int[] positions = new int[]{1, 2, 3, 4}; for (String name : names) { for (String color : colors) { for (int position : positions) { ksession.insert(new Golfer(name, color, position)); } } } ksession.fireAllRules(); ksession.dispose(); } }
false
32044_4
package v1; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.mllib.classification.LogisticRegressionModel; import org.apache.spark.mllib.classification.LogisticRegressionWithSGD; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.sql.SparkSession; import org.apache.spark.mllib.feature.HashingTF; import java.util.Arrays; import java.util.regex.Pattern; /** * Created by 張燿峰 * 机器学习入门案例 * 过滤垃圾邮件 * 这 个 程 序 使 用 了 MLlib 中 的 两 个 函 数:HashingTF 与 * LogisticRegressionWithSGD,前者从文本数据构建词频(term frequency)特征向量,后者 * 使用随机梯度下降法(Stochastic Gradient Descent,简称 SGD)实现逻辑回归。假设我们 * 从两个文件 spam.txt 与 normal.txt 开始,两个文件分别包含垃圾邮件和非垃圾邮件的例子, * 每行一个。接下来我们就根据词频把每个文件中的文本转化为特征向量,然后训练出一个 可以把两类消息分开的逻辑回归模型 * @author 孤 * @date 2019/5/7 * @Varsion 1.0 */ public class SpamEmail { private static final Pattern SPACE = Pattern.compile(" "); public static void main(String[] args) { SparkSession sparkSession = SparkSession.builder().appName("spam-email").master("local[2]").getOrCreate(); JavaSparkContext javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); //垃圾邮件数据 JavaRDD<String> spamEmail = javaSparkContext.textFile("spam.json"); //优质邮件数据 JavaRDD<String> normalEmail = javaSparkContext.textFile("normal.json"); //创建hashingTF实例把邮件文本映射为包含10000个特征的向量 final HashingTF hashingTF = new HashingTF(10000); JavaRDD<LabeledPoint> spamExamples = spamEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(0, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); JavaRDD<LabeledPoint> normaExamples = normalEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(1, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); //训练数据 JavaRDD<LabeledPoint> trainData = spamExamples.union(normaExamples); trainData.cache(); //逻辑回归需要迭代,先缓存 //随机梯度下降法 SGD 逻辑回归 LogisticRegressionModel model = new LogisticRegressionWithSGD().run(trainData.rdd()); Vector spamModel = hashingTF.transform(Arrays.asList(SPACE.split("垃 圾 钱 恶 心 色 情 赌 博 毒 品 败 类 犯罪"))); Vector normaModel = hashingTF.transform(Arrays.asList(SPACE.split("work 工作 你好 我们 请问 时间 领导"))); System.out.println("预测负面的例子: " + model.predict(spamModel)); System.out.println("预测积极的例子: " + model.predict(normaModel)); } }
Mydreamandreality/sparkResearch
chapter23/src/main/java/v1/SpamEmail.java
934
//训练数据
line_comment
zh-cn
package v1; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.mllib.classification.LogisticRegressionModel; import org.apache.spark.mllib.classification.LogisticRegressionWithSGD; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.sql.SparkSession; import org.apache.spark.mllib.feature.HashingTF; import java.util.Arrays; import java.util.regex.Pattern; /** * Created by 張燿峰 * 机器学习入门案例 * 过滤垃圾邮件 * 这 个 程 序 使 用 了 MLlib 中 的 两 个 函 数:HashingTF 与 * LogisticRegressionWithSGD,前者从文本数据构建词频(term frequency)特征向量,后者 * 使用随机梯度下降法(Stochastic Gradient Descent,简称 SGD)实现逻辑回归。假设我们 * 从两个文件 spam.txt 与 normal.txt 开始,两个文件分别包含垃圾邮件和非垃圾邮件的例子, * 每行一个。接下来我们就根据词频把每个文件中的文本转化为特征向量,然后训练出一个 可以把两类消息分开的逻辑回归模型 * @author 孤 * @date 2019/5/7 * @Varsion 1.0 */ public class SpamEmail { private static final Pattern SPACE = Pattern.compile(" "); public static void main(String[] args) { SparkSession sparkSession = SparkSession.builder().appName("spam-email").master("local[2]").getOrCreate(); JavaSparkContext javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); //垃圾邮件数据 JavaRDD<String> spamEmail = javaSparkContext.textFile("spam.json"); //优质邮件数据 JavaRDD<String> normalEmail = javaSparkContext.textFile("normal.json"); //创建hashingTF实例把邮件文本映射为包含10000个特征的向量 final HashingTF hashingTF = new HashingTF(10000); JavaRDD<LabeledPoint> spamExamples = spamEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(0, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); JavaRDD<LabeledPoint> normaExamples = normalEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(1, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); //训练 <SUF> JavaRDD<LabeledPoint> trainData = spamExamples.union(normaExamples); trainData.cache(); //逻辑回归需要迭代,先缓存 //随机梯度下降法 SGD 逻辑回归 LogisticRegressionModel model = new LogisticRegressionWithSGD().run(trainData.rdd()); Vector spamModel = hashingTF.transform(Arrays.asList(SPACE.split("垃 圾 钱 恶 心 色 情 赌 博 毒 品 败 类 犯罪"))); Vector normaModel = hashingTF.transform(Arrays.asList(SPACE.split("work 工作 你好 我们 请问 时间 领导"))); System.out.println("预测负面的例子: " + model.predict(spamModel)); System.out.println("预测积极的例子: " + model.predict(normaModel)); } }
false
61351_19
package mail.demo; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.springframework.core.io.support.PropertiesLoaderUtils; import com.sun.mail.util.MailSSLSocketFactory; public class SendEmailUtil { private static String account; //登录用户名 private static String pass; //登录密码 private static String host; //服务器地址(邮件服务器) private static String port; //端口 private static String protocol; //协议 static{ Properties prop = new Properties(); // InputStream instream = ClassLoader.getSystemResourceAsStream("email.properties");//测试环境 try { // prop.load(instream);//测试环境 prop = PropertiesLoaderUtils.loadAllProperties("email.properties");//生产环境 } catch (IOException e) { System.out.println("加载属性文件失败"); } account = prop.getProperty("e.account"); pass = prop.getProperty("e.pass"); host = prop.getProperty("e.host"); port = prop.getProperty("e.port"); protocol = prop.getProperty("e.protocol"); } static class MyAuthenricator extends Authenticator{ String u = null; String p = null; public MyAuthenricator(String u,String p){ this.u=u; this.p=p; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(u,p); } } private String to; //收件人 private String subject; //主题 private String content; //内容 private String fileStr; //附件路径 public SendEmailUtil(String to, String subject, String content, String fileStr) { this.to = to; this.subject = subject; this.content = content; this.fileStr = fileStr; } public void send(){ Properties prop = new Properties(); //协议 prop.setProperty("mail.transport.protocol", protocol); //服务器 prop.setProperty("mail.smtp.host", host); //端口 prop.setProperty("mail.smtp.port", port); //使用smtp身份验证 prop.setProperty("mail.smtp.auth", "true"); //使用SSL,企业邮箱必需! //开启安全协议 MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); } catch (GeneralSecurityException e1) { e1.printStackTrace(); } prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass)); session.setDebug(true); MimeMessage mimeMessage = new MimeMessage(session); try { //发件人 mimeMessage.setFrom(new InternetAddress(account,"XXX")); //可以设置发件人的别名 //mimeMessage.setFrom(new InternetAddress(account)); //如果不需要就省略 //收件人 mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //主题 mimeMessage.setSubject(subject); //时间 mimeMessage.setSentDate(new Date()); //容器类,可以包含多个MimeBodyPart对象 Multipart mp = new MimeMultipart(); //MimeBodyPart可以包装文本,图片,附件 MimeBodyPart body = new MimeBodyPart(); //HTML正文 body.setContent(content, "text/html; charset=UTF-8"); mp.addBodyPart(body); //添加图片&附件 body = new MimeBodyPart(); body.attachFile(fileStr); mp.addBodyPart(body); //设置邮件内容 mimeMessage.setContent(mp); //仅仅发送文本 //mimeMessage.setText(content); mimeMessage.saveChanges(); Transport.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Mysakura/Javamail-demo
src/mail/demo/SendEmailUtil.java
1,177
//添加图片&附件
line_comment
zh-cn
package mail.demo; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.springframework.core.io.support.PropertiesLoaderUtils; import com.sun.mail.util.MailSSLSocketFactory; public class SendEmailUtil { private static String account; //登录用户名 private static String pass; //登录密码 private static String host; //服务器地址(邮件服务器) private static String port; //端口 private static String protocol; //协议 static{ Properties prop = new Properties(); // InputStream instream = ClassLoader.getSystemResourceAsStream("email.properties");//测试环境 try { // prop.load(instream);//测试环境 prop = PropertiesLoaderUtils.loadAllProperties("email.properties");//生产环境 } catch (IOException e) { System.out.println("加载属性文件失败"); } account = prop.getProperty("e.account"); pass = prop.getProperty("e.pass"); host = prop.getProperty("e.host"); port = prop.getProperty("e.port"); protocol = prop.getProperty("e.protocol"); } static class MyAuthenricator extends Authenticator{ String u = null; String p = null; public MyAuthenricator(String u,String p){ this.u=u; this.p=p; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(u,p); } } private String to; //收件人 private String subject; //主题 private String content; //内容 private String fileStr; //附件路径 public SendEmailUtil(String to, String subject, String content, String fileStr) { this.to = to; this.subject = subject; this.content = content; this.fileStr = fileStr; } public void send(){ Properties prop = new Properties(); //协议 prop.setProperty("mail.transport.protocol", protocol); //服务器 prop.setProperty("mail.smtp.host", host); //端口 prop.setProperty("mail.smtp.port", port); //使用smtp身份验证 prop.setProperty("mail.smtp.auth", "true"); //使用SSL,企业邮箱必需! //开启安全协议 MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); } catch (GeneralSecurityException e1) { e1.printStackTrace(); } prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass)); session.setDebug(true); MimeMessage mimeMessage = new MimeMessage(session); try { //发件人 mimeMessage.setFrom(new InternetAddress(account,"XXX")); //可以设置发件人的别名 //mimeMessage.setFrom(new InternetAddress(account)); //如果不需要就省略 //收件人 mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //主题 mimeMessage.setSubject(subject); //时间 mimeMessage.setSentDate(new Date()); //容器类,可以包含多个MimeBodyPart对象 Multipart mp = new MimeMultipart(); //MimeBodyPart可以包装文本,图片,附件 MimeBodyPart body = new MimeBodyPart(); //HTML正文 body.setContent(content, "text/html; charset=UTF-8"); mp.addBodyPart(body); //添加 <SUF> body = new MimeBodyPart(); body.attachFile(fileStr); mp.addBodyPart(body); //设置邮件内容 mimeMessage.setContent(mp); //仅仅发送文本 //mimeMessage.setText(content); mimeMessage.saveChanges(); Transport.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
false
59901_0
package dao; //测试 import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import model.Admin; /** * 管理员数据处理类 * */ public class AdminDao { /**管理员登录 * @param con * @param admin * @return * @throws Exception */ public Admin login(Connection con, Admin admin) throws Exception {// 登录查找信息 Admin resultUser = null; String sql = "select * from admin where admin_name=? and admin_password=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, admin.getAdmin_name());// 将指定参数设置为给定 Java String 值 pstmt.setString(2, admin.getAdmin_password()); ResultSet rs = pstmt.executeQuery();// 在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。 if (rs.next()) { resultUser = new Admin(); resultUser.setAdmin_id(rs.getInt("admin_id")); resultUser.setAdmin_name(rs.getString("admin_name")); resultUser.setAdmin_phone(rs.getString("admin_phone")); resultUser.setAdmin_password(rs.getString("admin_password")); } return resultUser; } }
Mzmba/Book-sales-management-system
src/dao/AdminDao.java
318
/** * 管理员数据处理类 * */
block_comment
zh-cn
package dao; //测试 import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import model.Admin; /** * 管理员 <SUF>*/ public class AdminDao { /**管理员登录 * @param con * @param admin * @return * @throws Exception */ public Admin login(Connection con, Admin admin) throws Exception {// 登录查找信息 Admin resultUser = null; String sql = "select * from admin where admin_name=? and admin_password=?"; PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, admin.getAdmin_name());// 将指定参数设置为给定 Java String 值 pstmt.setString(2, admin.getAdmin_password()); ResultSet rs = pstmt.executeQuery();// 在此 PreparedStatement 对象中执行 SQL 查询,并返回该查询生成的 ResultSet 对象。 if (rs.next()) { resultUser = new Admin(); resultUser.setAdmin_id(rs.getInt("admin_id")); resultUser.setAdmin_name(rs.getString("admin_name")); resultUser.setAdmin_phone(rs.getString("admin_phone")); resultUser.setAdmin_password(rs.getString("admin_password")); } return resultUser; } }
true
57805_10
package com.bg7yoz.ft8cn.log; import com.bg7yoz.ft8cn.Ft8Message; import com.bg7yoz.ft8cn.GeneralVariables; import com.bg7yoz.ft8cn.timer.UtcTimer; import java.util.ArrayList; /** * 用于计算和处理SWL消息中的QSO记录。 * QSO的计算方法:把FT8通联的6个阶段分成3部分: * 1.CQ C1 grid * 2.C1 C2 grid * ---------第一部分--- * 3.C2 C1 report * 4.C1 C2 r-report * --------第二部分---- * 5.C2 C1 RR73(RRR) * 6.C1 C2 73 * --------第三部分---- * <p> * 一个基本的QSO,必须有自己的结束点(第三部分),双方的信号报告(在第二部分判断),网格报告可有可无(第一部分) * 以RR73、RRR、73为检查点,符合以上第一、二部分 * swlQsoList是个双key的HashMap,用于防止重复记录QSO。 * C1与C2顺序不同,代表不同的呼叫方。体现在station_callsign和call字段上 * * @author BG7YOZ * @date 2023-03-07 */ public class SWLQsoList { private static final String TAG = "SWLQsoList"; //通联成功的列表,防止重复,两个KEY顺序分别是:station_callsign和call,Boolean=true,已经QSO private final HashTable qsoList =new HashTable(); public SWLQsoList() { } /** * 检查有没有QSO消息 * * @param newMessages 新的FT8消息 * @param allMessages 全部的FT8消息 * @param onFoundSwlQso 当有发现的回调 */ public void findSwlQso(ArrayList<Ft8Message> newMessages, ArrayList<Ft8Message> allMessages , OnFoundSwlQso onFoundSwlQso) { for (int i = 0; i < newMessages.size(); i++) { Ft8Message msg = newMessages.get(i); if (msg.inMyCall()) continue;//对包含我自己的消息不处理 if (GeneralVariables.checkFun4_5(msg.extraInfo)//结束标识RRR、RR73、73 && !qsoList.contains(msg.callsignFrom, msg.callsignTo)) {//没有QSO记录 QSLRecord qslRecord = new QSLRecord(msg); if (checkPart2(allMessages, qslRecord)) {//找双方的信号报告,一个基本的QSO,必须有双方的信号报告 checkPart1(allMessages, qslRecord);//找双方的网格报告,顺便更新time_on的时间 if (onFoundSwlQso != null) {//触发回调,用于记录到数据库 qsoList.put(msg.callsignFrom, msg.callsignTo, true);//把QSO记录保存下来 onFoundSwlQso.doFound(qslRecord);//触发找到QSO的动作 } } } } } /** * 查第2部分是否存在,顺便把信号报告保存到QSLRecord中 * * @param allMessages 消息列表 * @param record QSLRecord * @return 返回值 没有发现:0,存在:2 */ private boolean checkPart2(ArrayList<Ft8Message> allMessages, QSLRecord record) { boolean foundFromReport = false; boolean foundToReport = false; long time_on = System.currentTimeMillis();//先把当前的时间作为最早时间 for (int i = allMessages.size() - 1; i >= 0; i--) { Ft8Message msg = allMessages.get(i); //if (msg.callsignFrom.equals(record.getMyCallsign()) if (GeneralVariables.checkIsMyCallsign(msg.callsignFrom) && msg.callsignTo.equals(record.getToCallsign()) && !foundFromReport) {//callsignFrom发出的信号报告 int report = GeneralVariables.checkFun2_3(msg.extraInfo); if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 if (report != -100) { record.setSendReport(report); foundFromReport = true; } } if (msg.callsignFrom.equals(record.getToCallsign()) //&& msg.callsignTo.equals(record.getMyCallsign()) && GeneralVariables.checkIsMyCallsign(msg.callsignTo) && !foundToReport) {//callsignTo发出的信号报告 int report = GeneralVariables.checkFun2_3(msg.extraInfo); if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 if (report != -100) { record.setReceivedReport(report); foundToReport = true; } } if (foundToReport && foundFromReport) {//如果双方的信号报告都找到了,就退出循环 record.setQso_date(UtcTimer.getYYYYMMDD(time_on)); record.setTime_on(UtcTimer.getTimeHHMMSS(time_on)); break; } } return foundToReport && foundFromReport;//双方的信号报告都有,才算一个QSO } /** * 查第2部分是否存在,顺便把网格报告保存到QSLRecord中 * * @param allMessages 消息列表 * @param record QSLRecord */ private void checkPart1(ArrayList<Ft8Message> allMessages, QSLRecord record) { boolean foundFromGrid = false; boolean foundToGrid = false; long time_on = System.currentTimeMillis();//先把当前的时间作为最早时间 for (int i = allMessages.size() - 1; i >= 0; i--) { Ft8Message msg = allMessages.get(i); if (!foundFromGrid //&& msg.callsignFrom.equals(record.getMyCallsign()) && GeneralVariables.checkIsMyCallsign(msg.callsignFrom) && (msg.callsignTo.equals(record.getToCallsign()) || msg.checkIsCQ())) {//callsignFrom的网格报告 if (GeneralVariables.checkFun1_6(msg.extraInfo)) { record.setMyMaidenGrid(msg.extraInfo.trim()); foundFromGrid = true; } if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 } if (!foundToGrid && msg.callsignFrom.equals(record.getToCallsign()) //&& (msg.callsignTo.equals(record.getMyCallsign()) && (GeneralVariables.checkIsMyCallsign(msg.callsignTo) || msg.checkIsCQ())) {//callsignTo发出的信号报告 if (GeneralVariables.checkFun1_6(msg.extraInfo)) { record.setToMaidenGrid(msg.extraInfo.trim()); foundToGrid = true; } if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 } if (foundToGrid && foundFromGrid) {//如果双方的信号报告都找到了,就退出循环 break; } } if (foundFromGrid || foundToGrid) {//发现网格报告,至少一个方向的 record.setQso_date(UtcTimer.getYYYYMMDD(time_on)); record.setTime_on(UtcTimer.getTimeHHMMSS(time_on)); } } public interface OnFoundSwlQso { void doFound(QSLRecord record); } }
N0BOY/FT8CN
ft8cn/app/src/main/java/com/bg7yoz/ft8cn/log/SWLQsoList.java
1,890
//触发找到QSO的动作
line_comment
zh-cn
package com.bg7yoz.ft8cn.log; import com.bg7yoz.ft8cn.Ft8Message; import com.bg7yoz.ft8cn.GeneralVariables; import com.bg7yoz.ft8cn.timer.UtcTimer; import java.util.ArrayList; /** * 用于计算和处理SWL消息中的QSO记录。 * QSO的计算方法:把FT8通联的6个阶段分成3部分: * 1.CQ C1 grid * 2.C1 C2 grid * ---------第一部分--- * 3.C2 C1 report * 4.C1 C2 r-report * --------第二部分---- * 5.C2 C1 RR73(RRR) * 6.C1 C2 73 * --------第三部分---- * <p> * 一个基本的QSO,必须有自己的结束点(第三部分),双方的信号报告(在第二部分判断),网格报告可有可无(第一部分) * 以RR73、RRR、73为检查点,符合以上第一、二部分 * swlQsoList是个双key的HashMap,用于防止重复记录QSO。 * C1与C2顺序不同,代表不同的呼叫方。体现在station_callsign和call字段上 * * @author BG7YOZ * @date 2023-03-07 */ public class SWLQsoList { private static final String TAG = "SWLQsoList"; //通联成功的列表,防止重复,两个KEY顺序分别是:station_callsign和call,Boolean=true,已经QSO private final HashTable qsoList =new HashTable(); public SWLQsoList() { } /** * 检查有没有QSO消息 * * @param newMessages 新的FT8消息 * @param allMessages 全部的FT8消息 * @param onFoundSwlQso 当有发现的回调 */ public void findSwlQso(ArrayList<Ft8Message> newMessages, ArrayList<Ft8Message> allMessages , OnFoundSwlQso onFoundSwlQso) { for (int i = 0; i < newMessages.size(); i++) { Ft8Message msg = newMessages.get(i); if (msg.inMyCall()) continue;//对包含我自己的消息不处理 if (GeneralVariables.checkFun4_5(msg.extraInfo)//结束标识RRR、RR73、73 && !qsoList.contains(msg.callsignFrom, msg.callsignTo)) {//没有QSO记录 QSLRecord qslRecord = new QSLRecord(msg); if (checkPart2(allMessages, qslRecord)) {//找双方的信号报告,一个基本的QSO,必须有双方的信号报告 checkPart1(allMessages, qslRecord);//找双方的网格报告,顺便更新time_on的时间 if (onFoundSwlQso != null) {//触发回调,用于记录到数据库 qsoList.put(msg.callsignFrom, msg.callsignTo, true);//把QSO记录保存下来 onFoundSwlQso.doFound(qslRecord);//触发 <SUF> } } } } } /** * 查第2部分是否存在,顺便把信号报告保存到QSLRecord中 * * @param allMessages 消息列表 * @param record QSLRecord * @return 返回值 没有发现:0,存在:2 */ private boolean checkPart2(ArrayList<Ft8Message> allMessages, QSLRecord record) { boolean foundFromReport = false; boolean foundToReport = false; long time_on = System.currentTimeMillis();//先把当前的时间作为最早时间 for (int i = allMessages.size() - 1; i >= 0; i--) { Ft8Message msg = allMessages.get(i); //if (msg.callsignFrom.equals(record.getMyCallsign()) if (GeneralVariables.checkIsMyCallsign(msg.callsignFrom) && msg.callsignTo.equals(record.getToCallsign()) && !foundFromReport) {//callsignFrom发出的信号报告 int report = GeneralVariables.checkFun2_3(msg.extraInfo); if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 if (report != -100) { record.setSendReport(report); foundFromReport = true; } } if (msg.callsignFrom.equals(record.getToCallsign()) //&& msg.callsignTo.equals(record.getMyCallsign()) && GeneralVariables.checkIsMyCallsign(msg.callsignTo) && !foundToReport) {//callsignTo发出的信号报告 int report = GeneralVariables.checkFun2_3(msg.extraInfo); if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 if (report != -100) { record.setReceivedReport(report); foundToReport = true; } } if (foundToReport && foundFromReport) {//如果双方的信号报告都找到了,就退出循环 record.setQso_date(UtcTimer.getYYYYMMDD(time_on)); record.setTime_on(UtcTimer.getTimeHHMMSS(time_on)); break; } } return foundToReport && foundFromReport;//双方的信号报告都有,才算一个QSO } /** * 查第2部分是否存在,顺便把网格报告保存到QSLRecord中 * * @param allMessages 消息列表 * @param record QSLRecord */ private void checkPart1(ArrayList<Ft8Message> allMessages, QSLRecord record) { boolean foundFromGrid = false; boolean foundToGrid = false; long time_on = System.currentTimeMillis();//先把当前的时间作为最早时间 for (int i = allMessages.size() - 1; i >= 0; i--) { Ft8Message msg = allMessages.get(i); if (!foundFromGrid //&& msg.callsignFrom.equals(record.getMyCallsign()) && GeneralVariables.checkIsMyCallsign(msg.callsignFrom) && (msg.callsignTo.equals(record.getToCallsign()) || msg.checkIsCQ())) {//callsignFrom的网格报告 if (GeneralVariables.checkFun1_6(msg.extraInfo)) { record.setMyMaidenGrid(msg.extraInfo.trim()); foundFromGrid = true; } if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 } if (!foundToGrid && msg.callsignFrom.equals(record.getToCallsign()) //&& (msg.callsignTo.equals(record.getMyCallsign()) && (GeneralVariables.checkIsMyCallsign(msg.callsignTo) || msg.checkIsCQ())) {//callsignTo发出的信号报告 if (GeneralVariables.checkFun1_6(msg.extraInfo)) { record.setToMaidenGrid(msg.extraInfo.trim()); foundToGrid = true; } if (time_on > msg.utcTime) time_on = msg.utcTime;//取最早的时间 } if (foundToGrid && foundFromGrid) {//如果双方的信号报告都找到了,就退出循环 break; } } if (foundFromGrid || foundToGrid) {//发现网格报告,至少一个方向的 record.setQso_date(UtcTimer.getYYYYMMDD(time_on)); record.setTime_on(UtcTimer.getTimeHHMMSS(time_on)); } } public interface OnFoundSwlQso { void doFound(QSLRecord record); } }
true
38946_0
package solutions._674; class Solution { public int findLengthOfLCIS(int[] nums) { if (nums.length == 0) { return 0; } int[] dp = new int[nums.length]; int result = 1; dp[0] = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { dp[i] = dp[i - 1] + 1; if (dp[i] > result) { result = dp[i]; } } else { dp[i] = 1; } } return result; } public static void main(String[] args) { System.out.println(new Solution().findLengthOfLCIS(new int[]{1, 3, 5, 4, 7})); System.out.println(new Solution().findLengthOfLCIS(new int[]{2, 2, 2, 2, 2})); } } /* 给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。 示例 1: 输入:nums = [1,3,5,4,7] 输出:3 解释:最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 示例 2: 输入:nums = [2,2,2,2,2] 输出:1 解释:最长连续递增序列是 [2], 长度为1。 提示: 0 <= nums.length <= 104 -109 <= nums[i] <= 109 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */
N3verL4nd/leetcode
src/main/java/solutions/_674/Solution.java
599
/* 给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。 示例 1: 输入:nums = [1,3,5,4,7] 输出:3 解释:最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 示例 2: 输入:nums = [2,2,2,2,2] 输出:1 解释:最长连续递增序列是 [2], 长度为1。 提示: 0 <= nums.length <= 104 -109 <= nums[i] <= 109 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */
block_comment
zh-cn
package solutions._674; class Solution { public int findLengthOfLCIS(int[] nums) { if (nums.length == 0) { return 0; } int[] dp = new int[nums.length]; int result = 1; dp[0] = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { dp[i] = dp[i - 1] + 1; if (dp[i] > result) { result = dp[i]; } } else { dp[i] = 1; } } return result; } public static void main(String[] args) { System.out.println(new Solution().findLengthOfLCIS(new int[]{1, 3, 5, 4, 7})); System.out.println(new Solution().findLengthOfLCIS(new int[]{2, 2, 2, 2, 2})); } } /* 给定一 <SUF>*/
false
46314_2
package org.apache.struts.actions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 同一个后端控制器类,对应多个<action>,也就是说,同一个后端控制器可以有多个控制函数, * 例如,CalcAction类,有add,subtract,multiply,divide函数,DispatchAction类的execute函数完成dispatch * 那么如何dispatch呢?execute函数如何转发调用到add,subtract,multipy,divide函数呢? * MappingDispatchAction函数改写(覆盖,override)了getMethodName函数,该函数返回的控制函数名称来自 * <action>元素的parameter属性的值。这样,可以把有一定相关性,聚合性的函数封装在一个后端控制器中。 * 然后为这个后端控制器定义多个path。例如: * * <action path="/add" type="action.CalcAction" parameter="add"/> * <action path="/subtract" type="action.CalcAction" parameter="subtract"/> * <action path="/multiply" type="action.CalcAction" parameter="multiply"/> * <action path="/divide" type="action.CalcAction" parameter="divide"/> * * 只要action.CalcAction类继承MappingDispatchAction类就可以了。 * parameter直接定义控制函数名称。 */ public class MappingDispatchAction extends DispatchAction { // 这个函数没有存在的必要,直接继承DispatchAction类就可以了。 // 毫无意义的覆盖。 protected String getParameter(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.getParameter(); } // MappingDispatchAction唯一有意义的函数,覆盖了DispatchAction类的getMethodName函数。 protected String getMethodName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String parameter) throws Exception { // 派发的控制函数的函数名称就是在<action>元素中parameter属性的值。 return parameter; } }
NAOSI-DLUT/DLUT_SE_Courses
大三上/JavaEE/exam_22_代码大题/MappingDispatchAction.java
534
// 毫无意义的覆盖。
line_comment
zh-cn
package org.apache.struts.actions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 同一个后端控制器类,对应多个<action>,也就是说,同一个后端控制器可以有多个控制函数, * 例如,CalcAction类,有add,subtract,multiply,divide函数,DispatchAction类的execute函数完成dispatch * 那么如何dispatch呢?execute函数如何转发调用到add,subtract,multipy,divide函数呢? * MappingDispatchAction函数改写(覆盖,override)了getMethodName函数,该函数返回的控制函数名称来自 * <action>元素的parameter属性的值。这样,可以把有一定相关性,聚合性的函数封装在一个后端控制器中。 * 然后为这个后端控制器定义多个path。例如: * * <action path="/add" type="action.CalcAction" parameter="add"/> * <action path="/subtract" type="action.CalcAction" parameter="subtract"/> * <action path="/multiply" type="action.CalcAction" parameter="multiply"/> * <action path="/divide" type="action.CalcAction" parameter="divide"/> * * 只要action.CalcAction类继承MappingDispatchAction类就可以了。 * parameter直接定义控制函数名称。 */ public class MappingDispatchAction extends DispatchAction { // 这个函数没有存在的必要,直接继承DispatchAction类就可以了。 // 毫无 <SUF> protected String getParameter(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.getParameter(); } // MappingDispatchAction唯一有意义的函数,覆盖了DispatchAction类的getMethodName函数。 protected String getMethodName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String parameter) throws Exception { // 派发的控制函数的函数名称就是在<action>元素中parameter属性的值。 return parameter; } }
false
58381_8
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.eron.solarsystem; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.app.scene.Camera3D; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.SpawnData; import com.almasb.fxgl.entity.components.TransformComponent; import com.almasb.fxgl.scene3d.SkyboxBuilder; import com.almasb.fxgl.texture.ColoredTexture; import com.almasb.fxgl.texture.ImagesKt; import javafx.geometry.Point2D; import javafx.scene.PointLight; import javafx.scene.image.WritableImage; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import javafx.util.Duration; import java.util.ArrayList; import java.util.stream.Collectors; import static com.almasb.fxgl.dsl.FXGL.*; /** * @author Almas Baimagambetov ([email protected]) */ public class SolarSystemApp extends GameApplication { private TransformComponent transform; private Camera3D camera3D; @Override protected void initSettings(GameSettings settings) { settings.setWidth(1280); settings.setHeight(720); settings.set3D(true); } @Override protected void initInput() { onKey(KeyCode.W, () -> { camera3D.moveForward(); }); onKey(KeyCode.S, () -> { camera3D.moveBack(); }); onKey(KeyCode.A, () -> { camera3D.moveLeft(); }); onKey(KeyCode.D, () -> { camera3D.moveRight(); }); onKey(KeyCode.L, () -> { getGameController().exit(); }); } @Override protected void initGame() { camera3D = getGameScene().getCamera3D(); camera3D.setMoveSpeed(40); // 设置camera 移动速度 camera3D.getPerspectiveCamera().setFarClip(500000); transform = getGameScene().getCamera3D().getTransform(); // 移动变换 transform.translateZ(-10); getGameWorld().addEntityFactory(new SolarSystemFactory()); // 设置entity 工厂 initLight(); // 灯光 initSkybox(); // 外景 包括幕布 其他星球的闪烁影像 initBodies(); // 星球 getGameScene().setFPSCamera(true); getGameScene().setCursorInvisible(); // 设置鼠标指针不可见 } private void initLight() { entityBuilder() .at(-5, 0, 0) // 灯光位置 不设置时为 0 .view(new PointLight()) .buildAndAttach(); } private void initSkybox() { var pixels = new ColoredTexture(1024, 1024, Color.RED) .pixels() .stream() .map(p -> p.copy(FXGLMath.randomBoolean(0.02) ? Color.color(1, 1, 1, random(0.0, 1.0)) : Color.BLACK)) // 很小的几率生成其他颜色 大部分成为黑色 .collect(Collectors.toList()); WritableImage image = (WritableImage) ImagesKt.fromPixels(1024, 1024, pixels); var skybox = new SkyboxBuilder(1024) // 一般游戏中需要一个全局的天空 正方形box .front(image) .back(image) .left(image) .right(image) .top(image) .bot(image) .buildImageSkybox(); entityBuilder() .view(skybox) .buildAndAttach(); var points = new ArrayList<Point2D>(); for (int i = 0; i < 2000; i++) { var x = random(5, 1020); var y = random(5, 1020); points.add(new Point2D(x, y)); } run(() -> { // 固定间隔时间运行一次 points.forEach(p -> { var t = getGameTimer().getNow(); var noise = FXGLMath.noise1D(t * ((p.getX()+p.getY()) / 1024) * 1); var c = Color.color(0.67, noise, noise); // 生成噪点 颜色 // image 是 3D box, 修改其中的像素点 image.getPixelWriter().setColor((int)p.getX(), (int)p.getY(), c); image.getPixelWriter().setColor((int)p.getX()-1, (int)p.getY(), c); image.getPixelWriter().setColor((int)p.getX()+2, (int)p.getY(), c); image.getPixelWriter().setColor((int)p.getX(), (int)p.getY()-1, c); image.getPixelWriter().setColor((int)p.getX(), (int)p.getY()+1, c); image.getPixelWriter().setColor((int)p.getX()+1, (int)p.getY()+1, c); image.getPixelWriter().setColor((int)p.getX()-1, (int)p.getY()-2, c); image.getPixelWriter().setColor((int)p.getX()-2, (int)p.getY()+1, c); }); }, Duration.seconds(0.25)); } private void initBodies() { for (CelestialBody body : CelestialBody.values()) { spawn( "body", new SpawnData().put("data", body) // 在factory 中根据data 设置entity的属性 ); } } public static void main(String[] args) { launch(args); } }
NAVERON/ArbitraryCoding
src/main/java/com/eron/solarsystem/SolarSystemApp.java
1,495
// 设置鼠标指针不可见
line_comment
zh-cn
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.eron.solarsystem; import com.almasb.fxgl.app.GameApplication; import com.almasb.fxgl.app.GameSettings; import com.almasb.fxgl.app.scene.Camera3D; import com.almasb.fxgl.core.math.FXGLMath; import com.almasb.fxgl.entity.SpawnData; import com.almasb.fxgl.entity.components.TransformComponent; import com.almasb.fxgl.scene3d.SkyboxBuilder; import com.almasb.fxgl.texture.ColoredTexture; import com.almasb.fxgl.texture.ImagesKt; import javafx.geometry.Point2D; import javafx.scene.PointLight; import javafx.scene.image.WritableImage; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import javafx.util.Duration; import java.util.ArrayList; import java.util.stream.Collectors; import static com.almasb.fxgl.dsl.FXGL.*; /** * @author Almas Baimagambetov ([email protected]) */ public class SolarSystemApp extends GameApplication { private TransformComponent transform; private Camera3D camera3D; @Override protected void initSettings(GameSettings settings) { settings.setWidth(1280); settings.setHeight(720); settings.set3D(true); } @Override protected void initInput() { onKey(KeyCode.W, () -> { camera3D.moveForward(); }); onKey(KeyCode.S, () -> { camera3D.moveBack(); }); onKey(KeyCode.A, () -> { camera3D.moveLeft(); }); onKey(KeyCode.D, () -> { camera3D.moveRight(); }); onKey(KeyCode.L, () -> { getGameController().exit(); }); } @Override protected void initGame() { camera3D = getGameScene().getCamera3D(); camera3D.setMoveSpeed(40); // 设置camera 移动速度 camera3D.getPerspectiveCamera().setFarClip(500000); transform = getGameScene().getCamera3D().getTransform(); // 移动变换 transform.translateZ(-10); getGameWorld().addEntityFactory(new SolarSystemFactory()); // 设置entity 工厂 initLight(); // 灯光 initSkybox(); // 外景 包括幕布 其他星球的闪烁影像 initBodies(); // 星球 getGameScene().setFPSCamera(true); getGameScene().setCursorInvisible(); // 设置 <SUF> } private void initLight() { entityBuilder() .at(-5, 0, 0) // 灯光位置 不设置时为 0 .view(new PointLight()) .buildAndAttach(); } private void initSkybox() { var pixels = new ColoredTexture(1024, 1024, Color.RED) .pixels() .stream() .map(p -> p.copy(FXGLMath.randomBoolean(0.02) ? Color.color(1, 1, 1, random(0.0, 1.0)) : Color.BLACK)) // 很小的几率生成其他颜色 大部分成为黑色 .collect(Collectors.toList()); WritableImage image = (WritableImage) ImagesKt.fromPixels(1024, 1024, pixels); var skybox = new SkyboxBuilder(1024) // 一般游戏中需要一个全局的天空 正方形box .front(image) .back(image) .left(image) .right(image) .top(image) .bot(image) .buildImageSkybox(); entityBuilder() .view(skybox) .buildAndAttach(); var points = new ArrayList<Point2D>(); for (int i = 0; i < 2000; i++) { var x = random(5, 1020); var y = random(5, 1020); points.add(new Point2D(x, y)); } run(() -> { // 固定间隔时间运行一次 points.forEach(p -> { var t = getGameTimer().getNow(); var noise = FXGLMath.noise1D(t * ((p.getX()+p.getY()) / 1024) * 1); var c = Color.color(0.67, noise, noise); // 生成噪点 颜色 // image 是 3D box, 修改其中的像素点 image.getPixelWriter().setColor((int)p.getX(), (int)p.getY(), c); image.getPixelWriter().setColor((int)p.getX()-1, (int)p.getY(), c); image.getPixelWriter().setColor((int)p.getX()+2, (int)p.getY(), c); image.getPixelWriter().setColor((int)p.getX(), (int)p.getY()-1, c); image.getPixelWriter().setColor((int)p.getX(), (int)p.getY()+1, c); image.getPixelWriter().setColor((int)p.getX()+1, (int)p.getY()+1, c); image.getPixelWriter().setColor((int)p.getX()-1, (int)p.getY()-2, c); image.getPixelWriter().setColor((int)p.getX()-2, (int)p.getY()+1, c); }); }, Duration.seconds(0.25)); } private void initBodies() { for (CelestialBody body : CelestialBody.values()) { spawn( "body", new SpawnData().put("data", body) // 在factory 中根据data 设置entity的属性 ); } } public static void main(String[] args) { launch(args); } }
true
58991_17
package com.eron.practice.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; @Entity @Table(name = "ship") public class Ship implements Cloneable { private static final Logger log = LoggerFactory.getLogger(Ship.class); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; // 自动生成的id @Column(name = "user_id") @NonNull private Long userId; // 用户ID @See User **必须赋值** @Column(name = "name") private String name; // 船舶名称 **必须赋值** @Column(name = "mmsi") private String mmsi; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 @Column(name = "imo_number") private String imoNumber; // IMO ship identification number @Column(name = "call_number") private String callNumber; // CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用 @Column(name = "type") private Integer type; // 船舶类型 @Column(name = "electronic_type") private Integer electronicType; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 @Column(name = "draft") private Float draft; // 船舶吃水 m/dt @Column(name = "create_time", insertable = false, updatable = false) private LocalDateTime createTime; // 船舶创建时间 @Column(name = "update_time", insertable = false, updatable = false) private LocalDateTime updateTime; // 船舶属性修改时间 @Deprecated public Ship() { // 禁用 this.userId = 0L; this.name = "NULL"; } public Ship(Long userId, String name) { this.userId = userId; this.name = name; } public Ship(Builder builder) { this.userId = builder.userId; this.name = builder.name; this.mmsi = builder.mmsi; this.imoNumber = builder.imoNumber; this.callNumber = builder.callNumber; this.type = builder.type; this.electronicType = builder.electronicType; this.draft = builder.draft; } /** * 使用 Ship.createBuilder().build(); * @return Builder obj */ public static Builder createBuilder() { return new Builder(); } public static class Builder { //private Long id; // 自动生成的id private Long userId; // 用户ID @See User **必须赋值** private String name = "NULL"; // 船舶名称 **必须赋值** private String mmsi = "NULL"; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 private String imoNumber = "NULL"; // IMO ship identification number private String callNumber = "NULL"; // CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用 private Integer type = 0; // 船舶类型 private Integer electronicType = 0; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 private Float draft = 0F; // 船舶吃水 m/dt //private LocalDateTime createTime; // 船舶创建时间 //private LocalDateTime updateTime; // 船舶属性修改时间 public Builder() {} public Builder userId(Long userId) { this.userId = userId; return this; } public Builder name(String name) { this.name = name; return this; } public Builder mmsi(String mmsi) { this.mmsi = mmsi; return this; } public Builder imoNumber(String imoNumber) { this.imoNumber = imoNumber; return this; } public Builder callNumber(String callNumber) { this.callNumber = callNumber; return this; } public Builder type(Integer type) { this.type = type; return this; } public Builder electronicType(Integer electronicType) { this.electronicType = electronicType; return this; } public Builder draft(Float draft) { this.draft = draft; return this; } public Ship build() { // 检查参数合法化 if (this.userId == null) { throw new IllegalArgumentException("userId of Ship is Required !"); } return new Ship(this); } } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // id 和 updatetime不覆盖 public void overrideAttributes(Ship another) { if (another == null) { log.error("another User is null !!!"); return; } this.userId = another.userId; this.name = another.name; this.mmsi = another.mmsi; this.imoNumber = another.imoNumber; this.callNumber = another.callNumber; this.type = another.type; this.electronicType = another.electronicType; this.draft = another.draft; this.createTime = another.createTime; } /** * pojo 通用 getter 和 setter * @return */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMmsi() { return mmsi; } public void setMmsi(String mmsi) { this.mmsi = mmsi; } public String getImoNumber() { return imoNumber; } public void setImoNumber(String imoNumber) { this.imoNumber = imoNumber; } public String getCallNumber() { return callNumber; } public void setCallNumber(String callNumber) { this.callNumber = callNumber; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getElectronicType() { return electronicType; } public void setElectronicType(Integer electronicType) { this.electronicType = electronicType; } public Float getDraft() { return draft; } public void setDraft(Float draft) { this.draft = draft; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "Ship [id=" + id + ", userId=" + userId + ", name=" + name + ", mmsi=" + mmsi + ", imoNumber=" + imoNumber + ", callNumber=" + callNumber + ", type=" + type + ", electronicType=" + electronicType + ", draft=" + draft + ", createTime=" + createTime + ", updateTime=" + updateTime + "]"; } }
NAVERON/PracticeSpringboot
src/main/java/com/eron/practice/model/Ship.java
2,069
// CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用
line_comment
zh-cn
package com.eron.practice.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; @Entity @Table(name = "ship") public class Ship implements Cloneable { private static final Logger log = LoggerFactory.getLogger(Ship.class); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; // 自动生成的id @Column(name = "user_id") @NonNull private Long userId; // 用户ID @See User **必须赋值** @Column(name = "name") private String name; // 船舶名称 **必须赋值** @Column(name = "mmsi") private String mmsi; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 @Column(name = "imo_number") private String imoNumber; // IMO ship identification number @Column(name = "call_number") private String callNumber; // CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用 @Column(name = "type") private Integer type; // 船舶类型 @Column(name = "electronic_type") private Integer electronicType; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 @Column(name = "draft") private Float draft; // 船舶吃水 m/dt @Column(name = "create_time", insertable = false, updatable = false) private LocalDateTime createTime; // 船舶创建时间 @Column(name = "update_time", insertable = false, updatable = false) private LocalDateTime updateTime; // 船舶属性修改时间 @Deprecated public Ship() { // 禁用 this.userId = 0L; this.name = "NULL"; } public Ship(Long userId, String name) { this.userId = userId; this.name = name; } public Ship(Builder builder) { this.userId = builder.userId; this.name = builder.name; this.mmsi = builder.mmsi; this.imoNumber = builder.imoNumber; this.callNumber = builder.callNumber; this.type = builder.type; this.electronicType = builder.electronicType; this.draft = builder.draft; } /** * 使用 Ship.createBuilder().build(); * @return Builder obj */ public static Builder createBuilder() { return new Builder(); } public static class Builder { //private Long id; // 自动生成的id private Long userId; // 用户ID @See User **必须赋值** private String name = "NULL"; // 船舶名称 **必须赋值** private String mmsi = "NULL"; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 private String imoNumber = "NULL"; // IMO ship identification number private String callNumber = "NULL"; // CA <SUF> private Integer type = 0; // 船舶类型 private Integer electronicType = 0; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 private Float draft = 0F; // 船舶吃水 m/dt //private LocalDateTime createTime; // 船舶创建时间 //private LocalDateTime updateTime; // 船舶属性修改时间 public Builder() {} public Builder userId(Long userId) { this.userId = userId; return this; } public Builder name(String name) { this.name = name; return this; } public Builder mmsi(String mmsi) { this.mmsi = mmsi; return this; } public Builder imoNumber(String imoNumber) { this.imoNumber = imoNumber; return this; } public Builder callNumber(String callNumber) { this.callNumber = callNumber; return this; } public Builder type(Integer type) { this.type = type; return this; } public Builder electronicType(Integer electronicType) { this.electronicType = electronicType; return this; } public Builder draft(Float draft) { this.draft = draft; return this; } public Ship build() { // 检查参数合法化 if (this.userId == null) { throw new IllegalArgumentException("userId of Ship is Required !"); } return new Ship(this); } } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // id 和 updatetime不覆盖 public void overrideAttributes(Ship another) { if (another == null) { log.error("another User is null !!!"); return; } this.userId = another.userId; this.name = another.name; this.mmsi = another.mmsi; this.imoNumber = another.imoNumber; this.callNumber = another.callNumber; this.type = another.type; this.electronicType = another.electronicType; this.draft = another.draft; this.createTime = another.createTime; } /** * pojo 通用 getter 和 setter * @return */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMmsi() { return mmsi; } public void setMmsi(String mmsi) { this.mmsi = mmsi; } public String getImoNumber() { return imoNumber; } public void setImoNumber(String imoNumber) { this.imoNumber = imoNumber; } public String getCallNumber() { return callNumber; } public void setCallNumber(String callNumber) { this.callNumber = callNumber; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getElectronicType() { return electronicType; } public void setElectronicType(Integer electronicType) { this.electronicType = electronicType; } public Float getDraft() { return draft; } public void setDraft(Float draft) { this.draft = draft; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "Ship [id=" + id + ", userId=" + userId + ", name=" + name + ", mmsi=" + mmsi + ", imoNumber=" + imoNumber + ", callNumber=" + callNumber + ", type=" + type + ", electronicType=" + electronicType + ", draft=" + draft + ", createTime=" + createTime + ", updateTime=" + updateTime + "]"; } }
false
7680_17
import java.util.Scanner; public class World { // 這世界能裝一千人 private static Human[] people = new Human[1000]; // 紀錄現在裝了幾人 public static int count; public static void main(String[] args) { Scanner input = new Scanner(System.in); // 世界一開始有兩個天降人(沒父母) people[0] = new Human("憲一", null, null); people[1] = new Human("展瑩", null, null); count += 2; // 運作吧,世界! while (true) { // 列出世界上每個人的資訊 for (int i = 0; i < count; i++) { // 先取得這人的雙親 Human[] parents = people[i].getParents(); // 顯示姓名 System.out.print("[" + people[i].getName() + "] "); // 若有父母,顯示父母 if (parents[0] != null && parents[1] != null) { System.out.print("父母: " + parents[0].getName() + " & " + parents[1].getName() + " "); } // 若有伴侶,顯示伴侶 if (people[i].getCompanion() != null) { System.out.print("伴侶: " + people[i].getCompanion().getName()); } System.out.println(); } System.out.println(); // 取得指令 String cmd = input.next(); // 找尋既存於世界之二人 // 預設找不到 Human a = null; Human b = null; // 輸入到找到為止 while (a == null) { String name = input.next(); a = search(name); } while (b == null) { String name = input.next(); b = search(name); } // 執行指令 if (cmd.equals("marry")) { // 互結連理 a.setCompanion(b); b.setCompanion(a); } else if (cmd.equals("deliver")) { // 若互為伴侶,才可生小孩 if (couldDeliver(a, b)) { System.out.print("請取個名字: "); people[count++] = new Human(input.next(), a, b); } else { System.out.println("互為伴侶才能生喔~"); } } System.out.println(); } } // 判斷這兩人是否能孩子 private static boolean couldDeliver(Human a, Human b) { return a.getCompanion() == b && b.getCompanion() == a; } // 找尋叫這名字的人 private static Human search(String name) { for (int i = 0; i < count; i++) { if (name.equals(people[i].getName())) { return people[i]; } } return null; } }
NCNU-OpenSource/programming-course
1042/judge4-2/World.java
744
// 找尋叫這名字的人
line_comment
zh-cn
import java.util.Scanner; public class World { // 這世界能裝一千人 private static Human[] people = new Human[1000]; // 紀錄現在裝了幾人 public static int count; public static void main(String[] args) { Scanner input = new Scanner(System.in); // 世界一開始有兩個天降人(沒父母) people[0] = new Human("憲一", null, null); people[1] = new Human("展瑩", null, null); count += 2; // 運作吧,世界! while (true) { // 列出世界上每個人的資訊 for (int i = 0; i < count; i++) { // 先取得這人的雙親 Human[] parents = people[i].getParents(); // 顯示姓名 System.out.print("[" + people[i].getName() + "] "); // 若有父母,顯示父母 if (parents[0] != null && parents[1] != null) { System.out.print("父母: " + parents[0].getName() + " & " + parents[1].getName() + " "); } // 若有伴侶,顯示伴侶 if (people[i].getCompanion() != null) { System.out.print("伴侶: " + people[i].getCompanion().getName()); } System.out.println(); } System.out.println(); // 取得指令 String cmd = input.next(); // 找尋既存於世界之二人 // 預設找不到 Human a = null; Human b = null; // 輸入到找到為止 while (a == null) { String name = input.next(); a = search(name); } while (b == null) { String name = input.next(); b = search(name); } // 執行指令 if (cmd.equals("marry")) { // 互結連理 a.setCompanion(b); b.setCompanion(a); } else if (cmd.equals("deliver")) { // 若互為伴侶,才可生小孩 if (couldDeliver(a, b)) { System.out.print("請取個名字: "); people[count++] = new Human(input.next(), a, b); } else { System.out.println("互為伴侶才能生喔~"); } } System.out.println(); } } // 判斷這兩人是否能孩子 private static boolean couldDeliver(Human a, Human b) { return a.getCompanion() == b && b.getCompanion() == a; } // 找尋 <SUF> private static Human search(String name) { for (int i = 0; i < count; i++) { if (name.equals(people[i].getName())) { return people[i]; } } return null; } }
false
44008_7
package CRC; import java.math.BigInteger; import java.util.Scanner; /* * @overview:按提示输入所需数据,最终得到检验结果 * @input:二进制形式的整数,如要发送整数5,则输入101 * @output:1.输入提示 * 2.验证结果(true or false) * @author:张羽白 * @warning:1.输入二进制数不要超过16位 * 2.要求bit转换位置不要超过32 */ public class CRC16 { private static int Poly; //生成多项式16位(使用CRC16,简记码0x8005) //(实际位数为16位,这里使用int是要模拟无符号位的short整形) private static int Send; //发送方输入的原数据 16位 //(实际位数为16位,这里使用int是要模拟无符号位的short整形) private static int CRCr; //生成校验码时的余数(最后一次运算余数为校验码) //(实际位数为16位,这里使用int是要模拟无符号位的short整形) private static long CRC; //带校验码的数据 32位(由Send数据16位,校验码16位组成) //(实际位数为32位,使用long模拟无符号位int整形) private static long Rev; //接收到的带验证码的数据 32位 //(实际位数为32位,使用long模拟无符号位int整形) public static void main(String arg[]){ Scanner sc = new Scanner(System.in); //提示输入二进制形式整数 System.out.println("Please input the num you want to send"); String SendStr = sc.next(); //初始化Send和Poly Send = new BigInteger(SendStr, 2).intValue(); Poly = 0x8005; //CRCr为余数,初始值等于Send CRCr = Send; //getCRC()初始化CRC值,得到32位(由Send数据16位,校验码16位组成) getCRC(); //初始化接收方数据(初始化与CRC相等) Rev = CRC; getInfo(); //提示输入是否要反转bit模拟数据出错情况(输入限制0-32,其中0为正确传输,不改变数据) System.out.println("Do you need to invert a bit?" + "\n" + "If no input 0,Else input the position number" + "\n" + "(Number start from 1 and Position is from right to left)"); int Position = sc.nextInt(); if(Position == 0){ getInfo(); System.out.println("Result :" + verify()); } else{ invert(Position); getInfo(); System.out.println("Result :" + verify()); } } /* * @intent:反转特定位置bit值 * @param:反转bit的位置(顺序为右到左) * @return:无 */ private static void invert(int position) { StringBuilder sb = new StringBuilder(); for(int i = 1;i <= 32; i++) if(position == 32 - i + 1) sb.append("1"); else sb.append("0"); int xor = new BigInteger(sb.toString(), 2).intValue(); //修改Rev值,得到bit反转后的32位损坏数据 Rev = Rev ^ xor; } /* * @intent:检验数据是否正确 * @param:反转bit位置(顺序为右到左) * @return:true for right * false for bad */ private static Boolean verify() { for(int i = 0; i < 32; i++){ //最高位32位是否为1,若为1则做位异或(位除法),否则左移一位至最高位为1 if((Rev & 0x80000000) != 0 /*&& Rev < */){ Rev = (long) (Rev << 1); //poly左移16位对Rev高16位做位异或(位除法) Rev = Rev ^ ((long)Poly << 16); } else Rev = (long) (Rev << 1); //使Rev高32位为0 Rev = Rev & 0xffffffffl; } if(Rev == 0) return true; else return false; } /* * @intent:得到32位CRC码 * @param:无 * @return:无 */ private static void getCRC() { //Send的16位移至高16位,低位补0 CRC = (long)Send << 16; for(int i = 0; i < 16; i++){ //if判断CRCr中最高位(16位)是否为1,是则做除法,否则左移一位直到最高位为1 if((CRCr & 0x8000) != 0){ CRCr = (int) (CRCr << 1); //位异或运算得到位除法余数CRCr(CRCr为最后一次余数时即为校验码) CRCr = (int) (CRCr ^ Poly); } else CRCr = (int) (CRCr << 1); //使CRCr高16位为0 CRCr = CRCr & 0x0000ffff; } //将校验码放到CRC的低16位(CRC原来低16位由补0产生) CRC = CRC ^ CRCr; } /* * @intent:输出重要数据 * @param:无 * @return:无 */ private static void getInfo() { System.out.println("Send :" + Integer.toBinaryString(Send)); System.out.println("CRCr :" + Integer.toBinaryString(CRCr)); System.out.println("CRC :" + Long.toBinaryString(CRC)); System.out.println("Rev :" + Long.toBinaryString(Rev)); System.out.println("\n"); } }
NEK-ROO/CRC16-0x8005-
CRC16.java
1,557
//带校验码的数据 32位(由Send数据16位,校验码16位组成)
line_comment
zh-cn
package CRC; import java.math.BigInteger; import java.util.Scanner; /* * @overview:按提示输入所需数据,最终得到检验结果 * @input:二进制形式的整数,如要发送整数5,则输入101 * @output:1.输入提示 * 2.验证结果(true or false) * @author:张羽白 * @warning:1.输入二进制数不要超过16位 * 2.要求bit转换位置不要超过32 */ public class CRC16 { private static int Poly; //生成多项式16位(使用CRC16,简记码0x8005) //(实际位数为16位,这里使用int是要模拟无符号位的short整形) private static int Send; //发送方输入的原数据 16位 //(实际位数为16位,这里使用int是要模拟无符号位的short整形) private static int CRCr; //生成校验码时的余数(最后一次运算余数为校验码) //(实际位数为16位,这里使用int是要模拟无符号位的short整形) private static long CRC; //带校 <SUF> //(实际位数为32位,使用long模拟无符号位int整形) private static long Rev; //接收到的带验证码的数据 32位 //(实际位数为32位,使用long模拟无符号位int整形) public static void main(String arg[]){ Scanner sc = new Scanner(System.in); //提示输入二进制形式整数 System.out.println("Please input the num you want to send"); String SendStr = sc.next(); //初始化Send和Poly Send = new BigInteger(SendStr, 2).intValue(); Poly = 0x8005; //CRCr为余数,初始值等于Send CRCr = Send; //getCRC()初始化CRC值,得到32位(由Send数据16位,校验码16位组成) getCRC(); //初始化接收方数据(初始化与CRC相等) Rev = CRC; getInfo(); //提示输入是否要反转bit模拟数据出错情况(输入限制0-32,其中0为正确传输,不改变数据) System.out.println("Do you need to invert a bit?" + "\n" + "If no input 0,Else input the position number" + "\n" + "(Number start from 1 and Position is from right to left)"); int Position = sc.nextInt(); if(Position == 0){ getInfo(); System.out.println("Result :" + verify()); } else{ invert(Position); getInfo(); System.out.println("Result :" + verify()); } } /* * @intent:反转特定位置bit值 * @param:反转bit的位置(顺序为右到左) * @return:无 */ private static void invert(int position) { StringBuilder sb = new StringBuilder(); for(int i = 1;i <= 32; i++) if(position == 32 - i + 1) sb.append("1"); else sb.append("0"); int xor = new BigInteger(sb.toString(), 2).intValue(); //修改Rev值,得到bit反转后的32位损坏数据 Rev = Rev ^ xor; } /* * @intent:检验数据是否正确 * @param:反转bit位置(顺序为右到左) * @return:true for right * false for bad */ private static Boolean verify() { for(int i = 0; i < 32; i++){ //最高位32位是否为1,若为1则做位异或(位除法),否则左移一位至最高位为1 if((Rev & 0x80000000) != 0 /*&& Rev < */){ Rev = (long) (Rev << 1); //poly左移16位对Rev高16位做位异或(位除法) Rev = Rev ^ ((long)Poly << 16); } else Rev = (long) (Rev << 1); //使Rev高32位为0 Rev = Rev & 0xffffffffl; } if(Rev == 0) return true; else return false; } /* * @intent:得到32位CRC码 * @param:无 * @return:无 */ private static void getCRC() { //Send的16位移至高16位,低位补0 CRC = (long)Send << 16; for(int i = 0; i < 16; i++){ //if判断CRCr中最高位(16位)是否为1,是则做除法,否则左移一位直到最高位为1 if((CRCr & 0x8000) != 0){ CRCr = (int) (CRCr << 1); //位异或运算得到位除法余数CRCr(CRCr为最后一次余数时即为校验码) CRCr = (int) (CRCr ^ Poly); } else CRCr = (int) (CRCr << 1); //使CRCr高16位为0 CRCr = CRCr & 0x0000ffff; } //将校验码放到CRC的低16位(CRC原来低16位由补0产生) CRC = CRC ^ CRCr; } /* * @intent:输出重要数据 * @param:无 * @return:无 */ private static void getInfo() { System.out.println("Send :" + Integer.toBinaryString(Send)); System.out.println("CRCr :" + Integer.toBinaryString(CRCr)); System.out.println("CRC :" + Long.toBinaryString(CRC)); System.out.println("Rev :" + Long.toBinaryString(Rev)); System.out.println("\n"); } }
true
40630_0
package Word1_5; import java.util.Scanner; public class word1_5 { public static void main(String[] args) { int [][] map = {{1,1,0,0,0,0,1,1,1,1}, {1,0,1,1,1,1,0,0,0,1}, {1,0,1,2,2,3,1,1,6,0}, {0,1,5,1,3,1,3,1,6,6}, {1,0,1,3,1,3,1,1,6,6}, {1,0,1,1,1,0,0,0,0,0}, {1,1,0,0,0,1,1,1,1,1}}; int playerX=3; int playerY=2; int win = 0; Scanner input = new Scanner(System.in); int playerX1=0; int playerY1=2; // while(true) { for(int i=0; i<7; i++) { for(int j=0; j<10; j++) { switch (map[i][j]) { case 0: System.out.print("🟫"); break; case 1: System.out.print("🟩"); break; case 2: System.out.print("🔥"); break; case 3: System.out.print("📦"); break; case 5: System.out.print("👩"); break; case 6: System.out.print("⛳"); break; case 7: System.out.print("👏"); break; case 8: System.out.print("👩"); break; default: break; } } System.out.println(""); } if(win==5) { System.out.println("恭喜你闯关成功!!!"); break; } String player = input.next(); player=player.toLowerCase(); switch (player) { case "w": if(map[playerX-1][playerY]==1) { map[playerX-1][playerY]=5; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX-1][playerY]==3) { if(map[playerX-2][playerY]==1) { map[playerX-1][playerY]=5; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX-2][playerY]=3; playerX = playerX1; continue; }else if(map[playerX-2][playerY]==6) { map[playerX-2][playerY]=7; win++; map[playerX-1][playerY]=5; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } }else if(map[playerX-1][playerY]==6) { map[playerX-1][playerY]=8; playerX1=playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX-1][playerY]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX-2][playerY]==1) { map[playerX-1][playerY]=8; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX-2][playerY]=3; win--; playerX = playerX1; continue; }else if(map[playerX-2][playerY]==6) { map[playerX-2][playerY]=7; map[playerX-1][playerY]=8; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } } break; case "s": if(map[playerX+1][playerY]==1) { map[playerX+1][playerY]=5; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX+1][playerY]==3) { if(map[playerX+2][playerY]==1) { map[playerX+1][playerY]=5; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX+2][playerY]=3; playerX = playerX1; continue; }else if(map[playerX+2][playerY]==6) { map[playerX+2][playerY]=7; win++; map[playerX+1][playerY]=5; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } }else if(map[playerX+1][playerY]==6) { map[playerX+1][playerY]=8; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX+1][playerY]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX+2][playerY]==1) { map[playerX+1][playerY]=8; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX+2][playerY]=3; win--; playerX = playerX1; continue; }else if(map[playerX+2][playerY]==6) { map[playerX+2][playerY]=7; map[playerX+1][playerY]=8; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } } break; case "a": if(map[playerX][playerY-1]==1) { map[playerX][playerY-1]=5; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY-1]==3) { if(map[playerX][playerY-2]==1) { map[playerX][playerY-1]=5; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY-2]=3; playerY = playerY1; continue; }else if(map[playerX][playerY-2]==6) { map[playerX][playerY-2]=7; win++; map[playerX][playerY-1]=5; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } }else if(map[playerX][playerY-1]==6) { map[playerX][playerY-1]=8; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY-1]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX][playerY-2]==1) { map[playerX][playerY-1]=8; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY-2]=3; win--; playerX = playerX1; continue; }else if(map[playerX][playerY-2]==6) { map[playerX][playerY-2]=7; map[playerX][playerY-1]=8; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } } break; case "d": if(map[playerX][playerY+1]==1) { map[playerX][playerY+1]=5; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY+1]==3) { if(map[playerX][playerY+2]==1) { map[playerX][playerY+1]=5; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY+2]=3; playerY = playerY1; continue; }else if(map[playerX][playerY+2]==6) { map[playerX][playerY+2]=7; win++; map[playerX][playerY+1]=5; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } }else if(map[playerX][playerY+1]==6) { map[playerX][playerY+1]=8; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY+1]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX][playerY+2]==1) { map[playerX][playerY+1]=8; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY+2]=3; win--; playerX = playerX1; continue; }else if(map[playerX][playerY+2]==6) { map[playerX][playerY+2]=7; map[playerX][playerY+1]=8; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } } break; default: break; } } }}
NJKFSDNK/pushBoxGame
word1_5.java
4,021
// 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地
line_comment
zh-cn
package Word1_5; import java.util.Scanner; public class word1_5 { public static void main(String[] args) { int [][] map = {{1,1,0,0,0,0,1,1,1,1}, {1,0,1,1,1,1,0,0,0,1}, {1,0,1,2,2,3,1,1,6,0}, {0,1,5,1,3,1,3,1,6,6}, {1,0,1,3,1,3,1,1,6,6}, {1,0,1,1,1,0,0,0,0,0}, {1,1,0,0,0,1,1,1,1,1}}; int playerX=3; int playerY=2; int win = 0; Scanner input = new Scanner(System.in); int playerX1=0; int playerY1=2; // while(true) { for(int i=0; i<7; i++) { for(int j=0; j<10; j++) { switch (map[i][j]) { case 0: System.out.print("🟫"); break; case 1: System.out.print("🟩"); break; case 2: System.out.print("🔥"); break; case 3: System.out.print("📦"); break; case 5: System.out.print("👩"); break; case 6: System.out.print("⛳"); break; case 7: System.out.print("👏"); break; case 8: System.out.print("👩"); break; default: break; } } System.out.println(""); } if(win==5) { System.out.println("恭喜你闯关成功!!!"); break; } String player = input.next(); player=player.toLowerCase(); switch (player) { case "w": if(map[playerX-1][playerY]==1) { map[playerX-1][playerY]=5; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX-1][playerY]==3) { if(map[playerX-2][playerY]==1) { map[playerX-1][playerY]=5; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX-2][playerY]=3; playerX = playerX1; continue; }else if(map[playerX-2][playerY]==6) { map[playerX-2][playerY]=7; win++; map[playerX-1][playerY]=5; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } }else if(map[playerX-1][playerY]==6) { map[playerX-1][playerY]=8; playerX1=playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX-1][playerY]==7) { // 0: <SUF> if(map[playerX-2][playerY]==1) { map[playerX-1][playerY]=8; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX-2][playerY]=3; win--; playerX = playerX1; continue; }else if(map[playerX-2][playerY]==6) { map[playerX-2][playerY]=7; map[playerX-1][playerY]=8; playerX1 = playerX-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } } break; case "s": if(map[playerX+1][playerY]==1) { map[playerX+1][playerY]=5; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX+1][playerY]==3) { if(map[playerX+2][playerY]==1) { map[playerX+1][playerY]=5; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX+2][playerY]=3; playerX = playerX1; continue; }else if(map[playerX+2][playerY]==6) { map[playerX+2][playerY]=7; win++; map[playerX+1][playerY]=5; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } }else if(map[playerX+1][playerY]==6) { map[playerX+1][playerY]=8; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; }else if(map[playerX+1][playerY]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX+2][playerY]==1) { map[playerX+1][playerY]=8; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX+2][playerY]=3; win--; playerX = playerX1; continue; }else if(map[playerX+2][playerY]==6) { map[playerX+2][playerY]=7; map[playerX+1][playerY]=8; playerX1 = playerX+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerX = playerX1; continue; } } break; case "a": if(map[playerX][playerY-1]==1) { map[playerX][playerY-1]=5; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY-1]==3) { if(map[playerX][playerY-2]==1) { map[playerX][playerY-1]=5; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY-2]=3; playerY = playerY1; continue; }else if(map[playerX][playerY-2]==6) { map[playerX][playerY-2]=7; win++; map[playerX][playerY-1]=5; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } }else if(map[playerX][playerY-1]==6) { map[playerX][playerY-1]=8; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY-1]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX][playerY-2]==1) { map[playerX][playerY-1]=8; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY-2]=3; win--; playerX = playerX1; continue; }else if(map[playerX][playerY-2]==6) { map[playerX][playerY-2]=7; map[playerX][playerY-1]=8; playerY1 = playerY-1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } } break; case "d": if(map[playerX][playerY+1]==1) { map[playerX][playerY+1]=5; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY+1]==3) { if(map[playerX][playerY+2]==1) { map[playerX][playerY+1]=5; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY+2]=3; playerY = playerY1; continue; }else if(map[playerX][playerY+2]==6) { map[playerX][playerY+2]=7; win++; map[playerX][playerY+1]=5; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } }else if(map[playerX][playerY+1]==6) { map[playerX][playerY+1]=8; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; }else if(map[playerX][playerY+1]==7) { // 0:墙 1:地 2:障碍物 3:箱子 5:人 6:目的地 7.箱子加目的地 8.人加目的地 if(map[playerX][playerY+2]==1) { map[playerX][playerY+1]=8; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } map[playerX][playerY+2]=3; win--; playerX = playerX1; continue; }else if(map[playerX][playerY+2]==6) { map[playerX][playerY+2]=7; map[playerX][playerY+1]=8; playerY1 = playerY+1; if(map[playerX][playerY]==5) { map[playerX][playerY]=1; }else if(map[playerX][playerY]==8) { map[playerX][playerY]=6; } playerY = playerY1; continue; } } break; default: break; } } }}
false
59344_1
package utility; public enum Position{ COURIER,//快递员 BUSINESS_OFFICE_CLERK,//营业厅业务员 CENTER_CLERK,//中转中心业务员 CENTER_REPERTORY_CLERK,//中转中心仓库管理员 FINANCIAL_STAFF_LOW,//低权限财务人员 FINANCIAL_STAFF_HIGH,//高权限财务人员 TOP_MANAGER,//总经理 ADMIN,//系统管理员 DRIVER,//司机 SUPERGOMAN,//押运员 GUARDMAN//监督员 }
NJU-Nonames/Logistics-System
Logistics_System/Common/src/main/java/utility/Position.java
138
//营业厅业务员
line_comment
zh-cn
package utility; public enum Position{ COURIER,//快递员 BUSINESS_OFFICE_CLERK,//营业 <SUF> CENTER_CLERK,//中转中心业务员 CENTER_REPERTORY_CLERK,//中转中心仓库管理员 FINANCIAL_STAFF_LOW,//低权限财务人员 FINANCIAL_STAFF_HIGH,//高权限财务人员 TOP_MANAGER,//总经理 ADMIN,//系统管理员 DRIVER,//司机 SUPERGOMAN,//押运员 GUARDMAN//监督员 }
true
33100_3
package HttpServer; import HttpServer.persistentUtil.DefaultObjectAction; import HttpServer.persistentUtil.ObjectAction; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ConcurrentHashMap; import static Util.ColorUtil.*; /** * @description: 长连接测试请求处理 * @author: GZK * @date: 2021/6/27 10:16 * @Modifiers: YDJSIR */ public class PersistentRequestHandler extends Thread{ private int port; private boolean running=true; private long receiveTimeDelay = 8000; // 连接断开时间 private ConcurrentHashMap<Class, ObjectAction> actionMapping = new ConcurrentHashMap<Class,ObjectAction>(); private Thread connWatchDog; public PersistentRequestHandler(int port) { this.port = port; } /** * 进程启动 */ public void start(){ System.out.println(ANSI_RED +"---->>>> Persistent Connection Keep Alive<<<<----"+ ANSI_RESET); connWatchDog = new ConnWatchDog(); connWatchDog.start(); } public static void main(String[] args) { int port = 8081; PersistentRequestHandler server = new PersistentRequestHandler(port); server.start(); } /** * 持续监听端口,并处理客户端发来的连接维持包 */ class ConnWatchDog extends Thread { @Override public void start(){ try { ServerSocket ss = new ServerSocket(port,5); printRed("WatchDog ON"); while(running){ Socket s = ss.accept(); new SocketAction(s).start(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 具体处理客户端发来的连接维持包 */ class SocketAction extends Thread{ Socket s; boolean run=true; int timeWarnAdvance = 3000; boolean hasWarned = false; long lastReceiveTime = System.currentTimeMillis(); public SocketAction(Socket s) { this.s = s; } @Override public void start() { while(running && run) { if (System.currentTimeMillis() - lastReceiveTime > receiveTimeDelay - timeWarnAdvance) { if (System.currentTimeMillis() - lastReceiveTime > receiveTimeDelay) { overThis(); // 调用超时处理方法 } else if (!hasWarned) { printRed("没有收到维持包,\t3\t秒内连接即将关闭"); hasWarned = true; } } else { try { InputStream in = s.getInputStream(); if (in.available() > 0) { ObjectInputStream ois = new ObjectInputStream(in); Object obj = ois.readObject(); lastReceiveTime = System.currentTimeMillis(); printGreen("\n接收来自 " + s.getRemoteSocketAddress() + " " + obj); ObjectAction oa = actionMapping.get(obj.getClass()); oa = oa == null ? new DefaultObjectAction() : oa; Object out = oa.doAction(obj, PersistentRequestHandler.this); if (out != null) { ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); oos.writeObject(out); oos.flush(); } } else { Thread.sleep(10); // 读不到输入流就睡一会儿 } } catch (Exception e) { overThis(); } } } } /** * 超过等待时间后,服务端关闭连接 */ private void overThis() { if(run)run=false; if(s!=null){ try { s.close(); } catch (IOException e) { e.printStackTrace(); } } if(s != null) printRed("\n关闭与"+s.getRemoteSocketAddress() + "的连接"); printRed("=========================================="); } } }
NJU-SE-15-share-review/professional-class
计算机网络/大作业/Socket/src/HttpServer/PersistentRequestHandler.java
951
/** * 持续监听端口,并处理客户端发来的连接维持包 */
block_comment
zh-cn
package HttpServer; import HttpServer.persistentUtil.DefaultObjectAction; import HttpServer.persistentUtil.ObjectAction; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ConcurrentHashMap; import static Util.ColorUtil.*; /** * @description: 长连接测试请求处理 * @author: GZK * @date: 2021/6/27 10:16 * @Modifiers: YDJSIR */ public class PersistentRequestHandler extends Thread{ private int port; private boolean running=true; private long receiveTimeDelay = 8000; // 连接断开时间 private ConcurrentHashMap<Class, ObjectAction> actionMapping = new ConcurrentHashMap<Class,ObjectAction>(); private Thread connWatchDog; public PersistentRequestHandler(int port) { this.port = port; } /** * 进程启动 */ public void start(){ System.out.println(ANSI_RED +"---->>>> Persistent Connection Keep Alive<<<<----"+ ANSI_RESET); connWatchDog = new ConnWatchDog(); connWatchDog.start(); } public static void main(String[] args) { int port = 8081; PersistentRequestHandler server = new PersistentRequestHandler(port); server.start(); } /** * 持续监 <SUF>*/ class ConnWatchDog extends Thread { @Override public void start(){ try { ServerSocket ss = new ServerSocket(port,5); printRed("WatchDog ON"); while(running){ Socket s = ss.accept(); new SocketAction(s).start(); } } catch (IOException e) { e.printStackTrace(); } } } /** * 具体处理客户端发来的连接维持包 */ class SocketAction extends Thread{ Socket s; boolean run=true; int timeWarnAdvance = 3000; boolean hasWarned = false; long lastReceiveTime = System.currentTimeMillis(); public SocketAction(Socket s) { this.s = s; } @Override public void start() { while(running && run) { if (System.currentTimeMillis() - lastReceiveTime > receiveTimeDelay - timeWarnAdvance) { if (System.currentTimeMillis() - lastReceiveTime > receiveTimeDelay) { overThis(); // 调用超时处理方法 } else if (!hasWarned) { printRed("没有收到维持包,\t3\t秒内连接即将关闭"); hasWarned = true; } } else { try { InputStream in = s.getInputStream(); if (in.available() > 0) { ObjectInputStream ois = new ObjectInputStream(in); Object obj = ois.readObject(); lastReceiveTime = System.currentTimeMillis(); printGreen("\n接收来自 " + s.getRemoteSocketAddress() + " " + obj); ObjectAction oa = actionMapping.get(obj.getClass()); oa = oa == null ? new DefaultObjectAction() : oa; Object out = oa.doAction(obj, PersistentRequestHandler.this); if (out != null) { ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); oos.writeObject(out); oos.flush(); } } else { Thread.sleep(10); // 读不到输入流就睡一会儿 } } catch (Exception e) { overThis(); } } } } /** * 超过等待时间后,服务端关闭连接 */ private void overThis() { if(run)run=false; if(s!=null){ try { s.close(); } catch (IOException e) { e.printStackTrace(); } } if(s != null) printRed("\n关闭与"+s.getRemoteSocketAddress() + "的连接"); printRed("=========================================="); } } }
true
31695_12
/* * 作者:胡天翔 * 时间:2019.8.35 * 作用:该类用于对特定格式的短信进行信息提取,提取的信息有内容、时间、地域、类别。 * 每个文件都是同一个手机APP发出的短信集合,末尾为手机所在地域;即所有该文件中短信均为同一地域 * */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractionMySQL { public String body; //短信主体 public String number; //号码 public String time; //时间 public boolean known; //属性 public int type; //类别 private String pub_ip=""; //默认的公网IP private String address=""; //默认的手机地域 private String MATCHStr="++++| This is the end of file! Next is the information about IP address. |++++"; /*上个变量作为匹配字符串存在,表明该字符串的下一个即目标字符串*/ public Bayes_main myBayes; public ExtractionMySQL(){ myBayes=new Bayes_main(); } /* * 删除字符串中指定的字符 * */ public static String deleteString0(String str, char delChar){ String delStr = ""; for (int i = 0; i < str.length(); i++) { if(str.charAt(i) != delChar){ delStr += str.charAt(i); } } return delStr; } /* * 该函数用于对文件确定公网IP与地域 * 确定成功返回true,失败返回false * 参数为文件名加路径 * */ private boolean Find_ip_adr(String pathname) { String line=null; try { RandomAccessFile rf = new RandomAccessFile(pathname, "r"); long filelength=rf.length(); long start=rf.getFilePointer(); long readIndex=start+filelength-1;//将指针指到文件末尾 rf.seek(readIndex); int c=-1; while(readIndex>start) { c=rf.read(); if(c=='\n'||c=='\r') { line = rf.readLine(); if (line != null) {//得到最后一行的内容 //System.out.println("read line:" + line); break; } readIndex--; } readIndex--; rf.seek(readIndex); } rf.close(); }catch (FileNotFoundException fne) { fne.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } if(line!=null) { List<String> ls=new ArrayList<>(); String regex="\"[^\"]*\""; Pattern pattern=Pattern.compile(regex); Matcher matcher=pattern.matcher(line); while(matcher.find()) { ls.add(matcher.group()); } if(ls.size()<6) return false;//说明最后一行的格式并不是约定好的格式,所以无法进行信息提取 String temp_ip=ls.get(1); //按照规定格式,ip应该在的位置 String temp_adr=ls.get(5); //按照规定格式,地域应该在的位置 this.pub_ip=deleteString0(temp_ip,'\"'); //删除开头和结尾的字符" this.address=deleteString0(temp_adr,'\"'); //同上 return true; } return false; } /* * 对单独的一条短信进行信息提取,并将信息上传至数据库 * 特殊要求为 * 1,短信中的换行符必须在str中 * 2,必须首先使用了Find_ip_adr()函数设置完成了pub_ip和address * 3,因为一些玄学原因,Bayes_main类型需由外界提供 * */ private void solve_single(String str,Bayes_main bm) { //匹配、填写body变量 String regex1="!@#\\$%\\^&[\\s\\S]*!@#\\$%\\^&"; Pattern pattern1= Pattern.compile(regex1); Matcher matcher1=pattern1.matcher(str); if(matcher1.find()) { String s1 = matcher1.group(); String[] ss = s1.split("!@#\\$%\\^&"); String temp_body = deleteString0(ss[1],'\n'); this.body=temp_body; } //匹配、填写time变量 String regex2="\\d{4}-\\d{2}-\\d{2}\\s?\\d{2}:\\d{2}:\\d{2}"; Pattern pattern2=Pattern.compile(regex2); Matcher matcher2=pattern2.matcher(str); if(matcher2.find()) { String s2=matcher2.group(); this.time=s2; } //获得短信类别 int cla=bm.handle(this.body); this.type=cla; //将内容上传数据库 String ip_adr=this.pub_ip+","+this.address; Inserter.input_mysql(this.body,ip_adr,this.time,this.type); } /* * 对文件进行处理,将短信内容上传数据库 * */ public boolean MySQL_solve_file(Bayes_main bm,String pathname) { if(!Find_ip_adr(pathname)) { return false; } try{ RandomAccessFile rf=new RandomAccessFile(pathname,"r"); long filelength=rf.length(); long readIndex=rf.getFilePointer(); String context_all=""; int count=0; Pattern pattern=Pattern.compile("------------"); while(readIndex<filelength) { String line=rf.readLine(); String newline=new String(line.getBytes("8859_1"),"UTF-8"); if(line!=null) { Matcher matcher=pattern.matcher(line); if(matcher.find()) { count++; } context_all+=newline+"\n"; //context_all+=line+"\n"; if(count==2)//表明一条短信已经被接收到 { count=0; solve_single(context_all,bm); context_all=""; } } readIndex=rf.getFilePointer(); } rf.close(); }catch (FileNotFoundException fne) { fne.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return true; } /* * 对文件夹进行处理——将文件夹内所有txt文件都进行处理 * */ public void MySQL_slove_flod(Bayes_main bm,String pathname) { File file=new File(pathname); File[] f_array=file.listFiles(); Pattern pattern=Pattern.compile("(\\.txt)$"); for (File f:f_array) { String s = f.getName(); Matcher matcher = pattern.matcher(s); if (matcher.find())//对txt文件进行处理 { String name = pathname + s; MySQL_solve_file(bm,name); } } } }
NJU-TJL/smsAPP-Server
src/ExtractionMySQL.java
1,746
//按照规定格式,地域应该在的位置
line_comment
zh-cn
/* * 作者:胡天翔 * 时间:2019.8.35 * 作用:该类用于对特定格式的短信进行信息提取,提取的信息有内容、时间、地域、类别。 * 每个文件都是同一个手机APP发出的短信集合,末尾为手机所在地域;即所有该文件中短信均为同一地域 * */ import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ExtractionMySQL { public String body; //短信主体 public String number; //号码 public String time; //时间 public boolean known; //属性 public int type; //类别 private String pub_ip=""; //默认的公网IP private String address=""; //默认的手机地域 private String MATCHStr="++++| This is the end of file! Next is the information about IP address. |++++"; /*上个变量作为匹配字符串存在,表明该字符串的下一个即目标字符串*/ public Bayes_main myBayes; public ExtractionMySQL(){ myBayes=new Bayes_main(); } /* * 删除字符串中指定的字符 * */ public static String deleteString0(String str, char delChar){ String delStr = ""; for (int i = 0; i < str.length(); i++) { if(str.charAt(i) != delChar){ delStr += str.charAt(i); } } return delStr; } /* * 该函数用于对文件确定公网IP与地域 * 确定成功返回true,失败返回false * 参数为文件名加路径 * */ private boolean Find_ip_adr(String pathname) { String line=null; try { RandomAccessFile rf = new RandomAccessFile(pathname, "r"); long filelength=rf.length(); long start=rf.getFilePointer(); long readIndex=start+filelength-1;//将指针指到文件末尾 rf.seek(readIndex); int c=-1; while(readIndex>start) { c=rf.read(); if(c=='\n'||c=='\r') { line = rf.readLine(); if (line != null) {//得到最后一行的内容 //System.out.println("read line:" + line); break; } readIndex--; } readIndex--; rf.seek(readIndex); } rf.close(); }catch (FileNotFoundException fne) { fne.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } if(line!=null) { List<String> ls=new ArrayList<>(); String regex="\"[^\"]*\""; Pattern pattern=Pattern.compile(regex); Matcher matcher=pattern.matcher(line); while(matcher.find()) { ls.add(matcher.group()); } if(ls.size()<6) return false;//说明最后一行的格式并不是约定好的格式,所以无法进行信息提取 String temp_ip=ls.get(1); //按照规定格式,ip应该在的位置 String temp_adr=ls.get(5); //按照 <SUF> this.pub_ip=deleteString0(temp_ip,'\"'); //删除开头和结尾的字符" this.address=deleteString0(temp_adr,'\"'); //同上 return true; } return false; } /* * 对单独的一条短信进行信息提取,并将信息上传至数据库 * 特殊要求为 * 1,短信中的换行符必须在str中 * 2,必须首先使用了Find_ip_adr()函数设置完成了pub_ip和address * 3,因为一些玄学原因,Bayes_main类型需由外界提供 * */ private void solve_single(String str,Bayes_main bm) { //匹配、填写body变量 String regex1="!@#\\$%\\^&[\\s\\S]*!@#\\$%\\^&"; Pattern pattern1= Pattern.compile(regex1); Matcher matcher1=pattern1.matcher(str); if(matcher1.find()) { String s1 = matcher1.group(); String[] ss = s1.split("!@#\\$%\\^&"); String temp_body = deleteString0(ss[1],'\n'); this.body=temp_body; } //匹配、填写time变量 String regex2="\\d{4}-\\d{2}-\\d{2}\\s?\\d{2}:\\d{2}:\\d{2}"; Pattern pattern2=Pattern.compile(regex2); Matcher matcher2=pattern2.matcher(str); if(matcher2.find()) { String s2=matcher2.group(); this.time=s2; } //获得短信类别 int cla=bm.handle(this.body); this.type=cla; //将内容上传数据库 String ip_adr=this.pub_ip+","+this.address; Inserter.input_mysql(this.body,ip_adr,this.time,this.type); } /* * 对文件进行处理,将短信内容上传数据库 * */ public boolean MySQL_solve_file(Bayes_main bm,String pathname) { if(!Find_ip_adr(pathname)) { return false; } try{ RandomAccessFile rf=new RandomAccessFile(pathname,"r"); long filelength=rf.length(); long readIndex=rf.getFilePointer(); String context_all=""; int count=0; Pattern pattern=Pattern.compile("------------"); while(readIndex<filelength) { String line=rf.readLine(); String newline=new String(line.getBytes("8859_1"),"UTF-8"); if(line!=null) { Matcher matcher=pattern.matcher(line); if(matcher.find()) { count++; } context_all+=newline+"\n"; //context_all+=line+"\n"; if(count==2)//表明一条短信已经被接收到 { count=0; solve_single(context_all,bm); context_all=""; } } readIndex=rf.getFilePointer(); } rf.close(); }catch (FileNotFoundException fne) { fne.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return true; } /* * 对文件夹进行处理——将文件夹内所有txt文件都进行处理 * */ public void MySQL_slove_flod(Bayes_main bm,String pathname) { File file=new File(pathname); File[] f_array=file.listFiles(); Pattern pattern=Pattern.compile("(\\.txt)$"); for (File f:f_array) { String s = f.getName(); Matcher matcher = pattern.matcher(s); if (matcher.find())//对txt文件进行处理 { String name = pathname + s; MySQL_solve_file(bm,name); } } } }
true
20016_75
import java.io.*; import java.net.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.lang.Thread; public class Client { // Hello^_^, I'm Pchan. public Packet receivedPacket = null; public Packet sentPacket = null; public int MSS = 20; protected int port; protected Window window = new Window(); //创建一个窗口,维护这个window private byte[] serverAddr = new byte[4]; private int serverPort; protected ServerSocket welcomeSocket; protected Socket connectionSocket = null; public boolean fileRdy = false;//server的文件是否就绪 private int serverWindowSize = 100; public boolean screen = true; //是否回显,默认true protected void receive(Packet packet) { receivedPacket = packet; } /** * 从流里读字节直到读到终止符"\0~~~~" * */ protected byte[] getBytes(InputStream stream) throws Exception{ int byteRead; ArrayList<Byte> list = new ArrayList<>(); int quit = 0; boolean eof = false; while (quit < 4) { byteRead = stream.read(); if (byteRead == '\0') eof = true; else if ((byte) byteRead == '~' && eof) { quit++; }else { eof = false; quit = 0; } list.add((byte) byteRead); } byte[] buf = new byte[list.size() - 5]; for (int i = 0; i < list.size() - 5; i++) { buf[i] = list.get(i); } return buf; } protected boolean checkACK(Packet packet) { return packet.ackValid(); } protected boolean checkPSH(Packet packet) { return packet.pushNow(); } protected boolean checkRST(Packet packet) { return packet.isReset(); } protected boolean checkURG(Packet packet) { return packet.urgentValid(); } /** * 检查FIN位,判断是否挥手释放连接 * @param packet * @return boolean * */ protected boolean checkFIN(Packet packet) { return packet.checkFIN(); } /** * 检查SYN位,判断是否握手建立连接 * @param packet * @return boolean * */ protected boolean checkSYN(Packet packet) { return packet.checkSYN(); } /** * 该方法发送报文 * @param connectionSocket: 与客户端建立连结的服务端 * @param packet 报文 * */ protected void send(Socket connectionSocket, Packet packet) throws IOException { OutputStream outToServer = connectionSocket.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); if (packet == null) { System.out.println("error: nullPointerException in packet: NULL"); return; } out.write(packet.getBytes()); } /*** *回显当前报文内容,即显示收到的信息 *回显格式:src:... dest:... id:... ack:... window:... data:... */ protected void print() { System.out.println(receivedPacket); } /** * 把收到的字节流组装成报文, 字节流中一定包含首部,可能包含数据 * @param fromClient: 从客户端收到的字节流 * @return Packet: 组装后的报文 * */ protected Packet buildPacket(byte[] fromClient) { // System.out.println(fromClient.length); Packet p = new Packet(Arrays.copyOfRange(fromClient, 0, 2), Arrays.copyOfRange(fromClient, 2, 4), Arrays.copyOfRange(fromClient, 4, 8), Arrays.copyOfRange(fromClient, 8, 12), Arrays.copyOfRange(fromClient, 12, 14), Arrays.copyOfRange(fromClient, 14, 16), Arrays.copyOfRange(fromClient, 16, 18), Arrays.copyOfRange(fromClient, 18, 20), new byte[]{}, new byte[]{}, Transformer.toInteger(Arrays.copyOfRange(fromClient, 20, 24))); // System.out.println("gggg"); byte[] data = Arrays.copyOfRange(fromClient, 24, fromClient.length); if (data.length > 0) p.setData(new Data(data)); return p; } private void printSleep(int times, int slp) throws Exception{ for (int i = 0; i < times; i++) { Thread.sleep(slp); System.out.print("."); } Thread.sleep(slp); System.out.println(); } /** * Client握手建立连接 * */ private void buildConnection(Socket target) throws Exception { //ServerSocket welcomeSocket = new ServerSocket(port); System.out.println("Trying to connect " + target.getInetAddress().toString().substring(1) + ":" + serverPort + "..."); // 发送syn请求报文 int seq = new Random().nextInt(123);// 该报文第一个字节id byte[] id = Transformer.toBytes(seq, 4); int ack = 0; byte[] Ack = Transformer.toBytes(ack, 4); byte[] spcBytes = new byte[2]; spcBytes[1] = 2;// SYN置1 int checkSum = 0; Packet firstShakeHand = new Packet( Transformer.toBytes(port, 2), Transformer.toBytes(serverPort, 2), id, Ack, spcBytes, Transformer.toBytes(serverWindowSize, 2), Transformer.toBytes(checkSum, 2), new byte[]{0, 0}, new byte[]{}, new byte[]{}, MSS); System.out.println("开始握手:"); printSleep(5, 200); if (screen) { System.out.println("------------------------------first from client------------------------------"); System.out.println(); System.out.println(firstShakeHand); System.out.println("-----------------------------------------------------------------------------"); } send(target, firstShakeHand); // 接收Ack报文 InputStream bytesFromClient = target.getInputStream(); //OutputStream bytesToClient = target.getOutputStream(); byte[] buffer = getBytes(bytesFromClient);// buffer中存放client发来报文的字节形式 Packet secondHandShake = buildPacket(buffer);// 组装报文 receive(secondHandShake);// 收到client的第一次握手报文 MSS = secondHandShake.MSS; //MSS大小统一,先统一为server的(发数据方) printSleep(5, 200); if (screen) { System.out.println("-----------------------------second from server------------------------------"); System.out.println(); print();// 回显报文 System.out.println("-----------------------------------------------------------------------------"); } // 发送Ack报文 seq++; id = Transformer.toBytes(seq, 4); ack = Transformer.toInteger(receivedPacket.getId()) + 1;// 该报文ack应为上一个报文id + 1 Ack = Transformer.toBytes(ack, 4); spcBytes = new byte[2]; spcBytes[0] = receivedPacket.getSpcBytes()[0]; spcBytes[1] = (byte) (receivedPacket.getSpcBytes()[1] | (1 << 4));// ACK置1 Packet secondShakeHand = new Packet( receivedPacket.getDest(), receivedPacket.getSrc(), id, Ack, spcBytes, Transformer.toBytes(serverWindowSize, 2), Transformer.toBytes(checkSum, 2), receivedPacket.getUrgent(), receivedPacket.getOptions(), receivedPacket.getAlign(), receivedPacket.MSS ); printSleep(5, 200); if (screen) { System.out.println("-----------------------------third from client-------------------------------"); System.out.println(); System.out.println(secondShakeHand); System.out.println("-----------------------------------------------------------------------------"); } send(target, secondShakeHand); } /** * Client挥手释放连接 * */ private static void releaseConnection(Client client, Socket connectingSocket) throws Exception { System.out.println("开始挥手:"); int ack = 0; int checkSum = 0; int seq = new Random().nextInt(123);// 随机 InputStream bytesFromClient; byte[] buffer; byte[] id = Transformer.toBytes(seq, 4); byte[] Ack = Transformer.toBytes(ack, 4); byte[] spcBytes = new byte[2]; spcBytes[1] = (byte) 0b00000001;// FIN置1 Packet firstHandShake = new Packet( Transformer.toBytes(client.port, 2), Transformer.toBytes(client.serverPort, 2), id, Ack, spcBytes, Transformer.toBytes(client.serverWindowSize, 2), Transformer.toBytes(checkSum, 2), client.receivedPacket.getUrgent(), client.receivedPacket.getOptions(), client.receivedPacket.getAlign(), client.MSS); client.printSleep(5, 200); if (client.screen) { System.out.println("------------------------------first from client------------------------------"); System.out.println(); System.out.println(firstHandShake); System.out.println("-----------------------------------------------------------------------------"); } client.send(connectingSocket, firstHandShake); // client 进入 FIN-WAIT-1 bytesFromClient = connectingSocket.getInputStream(); buffer = client.getBytes(bytesFromClient); Packet secondShakeHand = client.buildPacket(buffer); client.receive(secondShakeHand); client.printSleep(5, 200); if(client.screen) { System.out.println("------------------------------second from server-----------------------------"); System.out.println(); client.print(); System.out.println("-----------------------------------------------------------------------------"); } System.out.print("等待剩余数据传输完毕."); client.printSleep(6, 300); //模拟数据传输完毕的确认 Packet ctrl = Controller.getCtrlPkt(0, "release");//可以继续释放连接 client.send(connectingSocket, ctrl); if (client.checkACK(secondShakeHand)) { // client 进入 FIN-WAIT-2 bytesFromClient = connectingSocket.getInputStream(); buffer = client.getBytes(bytesFromClient); Packet thirdShakeHand = client.buildPacket(buffer); client.receive(thirdShakeHand); client.printSleep(5, 200); if (client.screen) { System.out.println("------------------------------third from server------------------------------"); System.out.println(); client.print(); System.out.println("-----------------------------------------------------------------------------"); } if (client.checkFIN(thirdShakeHand)) { spcBytes[1] |= 0b00010000; //ACK=1 seq = Transformer.toInteger(client.receivedPacket.getAck()); ack = Transformer.toInteger(client.receivedPacket.getId()) + 1; Packet fourthHandShake = new Packet( client.receivedPacket.getDest(), client.receivedPacket.getSrc(), Transformer.toBytes(seq, 4), Transformer.toBytes(ack, 4), spcBytes, Transformer.toBytes(client.serverWindowSize, 2), Transformer.toBytes(checkSum, 2), client.receivedPacket.getUrgent(), client.receivedPacket.getOptions(), client.receivedPacket.getAlign(), client.receivedPacket.MSS); client.printSleep(5, 200); if (client.screen) { System.out.println("------------------------------fourth from client-----------------------------"); System.out.println(); System.out.println(fourthHandShake); System.out.println("-----------------------------------------------------------------------------"); } client.send(connectingSocket, fourthHandShake); // 进入TIME-WAIT超时等待2MSL System.out.print("wait for 2MSL."); client.printSleep(10, 200); System.out.println("Connection released!"); connectingSocket.close(); } else { System.out.println("Failed to release connection."); } // 不符合挥手规范,抛出异常 // } } else { System.out.println("Failed to release connection."); } // 不符合挥手规范,抛出异常 } /** * 数据传输 * @param host 发送方 * */ protected static void dataTransfer(Client host, Socket connectionSocket, String path) throws Exception { Window window1 = host.window; RandomAccessFile file = new RandomAccessFile(path, "r"); long fileLen = file.length(); long filePointer = file.getFilePointer(); int segmentSize = window1.getSegmentSize(), size = window1.getSize(); int windowBufferSize = size / segmentSize;//window一次可以放的报文段数 //第一个报文特殊处理 file.seek(filePointer); InputStream input = new FileInputStream(file.getFD()); int seq = new Random().nextInt(123);// 该报文第一个字节id int tmp = seq; //step1: 用数据包填满window(需要检查是否可以装填) int wd = 1, ack = 0; while (filePointer < fileLen){ System.out.println("*******************************第" + wd + "个窗口********************************"); System.out.println(); wd++; System.out.println("-----------------------------build packets------------------------------"); if (window1.ifFinished()) { while (!window1.full()) { if (filePointer >= fileLen) break; file.seek(filePointer); int cnt = 0; ArrayList<Byte> list = new ArrayList<Byte>(); while (cnt < segmentSize && filePointer < fileLen) { cnt++; filePointer++;//更新指针 list.add((byte) input.read()); } byte[] buffer = new byte[list.size()]; for (int i = 0; i < list.size(); i++) buffer[i] = list.get(i); byte[] id = Transformer.toBytes(seq, 4); //ack在不知道应答的时候无法确认是多少 byte[] Ack = Transformer.toBytes(ack, 4); byte[] spcBytes = new byte[2]; spcBytes[1] = (byte) (1 << 4);// ACK置1 int checkSum = 0; Packet p = new Packet( Transformer.toBytes(host.port, 2), host.receivedPacket.getSrc(), id, Ack, spcBytes, Transformer.toBytes(window1.getSize(), 2), Transformer.toBytes(checkSum, 2), host.receivedPacket.getUrgent(), host.receivedPacket.getOptions(), host.receivedPacket.getAlign(), host.receivedPacket.MSS ); p.setData(new Data(buffer)); window1.replace(p); Controller.printHex(p); seq += segmentSize; //if (seq < 0) seq += (1 << 31); } } System.out.println("packet has been in window"); System.out.println("------------------------------------------------------------------------"); System.out.println(); //step2: 处理应答、逐包发送 int i = 0; seq = tmp; for (int j = 0; j < window1.getSize() / window1.getSegmentSize(); j++) { if (window1.packets[j] == null || window1.packets[j].isAck) continue; //发送 window1.packets[j].setAck(Transformer.toBytes(ack, 4)); window1.packets[j].setId(Transformer.toBytes(seq, 4)); int possible = new Random().nextInt(1000); Packet p = window1.packets[j]; if (possible < 100) { if (possible < 25) { //miss p.setMessage(Error.MISS_MSG); }else if (possible < 50) { //shuffle p.setMessage(Error.SHUFFLE_MSG); }else if (possible < 75) { //timeout p.setMessage(Error.TIME_OUT); }else { //wrong p.setMessage(Error.WRONG_MSG); } host.send(connectionSocket, p); //阻塞等待重传要求 InputStream help = connectionSocket.getInputStream(); Packet buf = host.buildPacket(host.getBytes(help)); } window1.packets[j].setMessage(Error.NO_ERROR); System.out.println("------start sending packet:------"); Controller.printHex(window1.packets[j]); host.send(connectionSocket, window1.packets[j]); System.out.println("------------send done------------"); //处理应答 byte[] buffer; InputStream bytesFromServer = connectionSocket.getInputStream();// 获取字节流 buffer = host.getBytes(bytesFromServer);// buffer中存放发来报文的字节形式 System.out.println("receive reply"); Packet reply = host.buildPacket(buffer);// 组装报文 host.receive(reply);// 收到对方的reply ack = Transformer.toInteger(host.receivedPacket.getId()) + 1; seq = Transformer.toInteger(host.receivedPacket.getAck()); if (host.receivedPacket != null) { System.out.printf("第%d个应答: \n", ++i); // host.printSleep(); host.print();// 回显报文 checkAndRenew(host.receivedPacket, window1); } else { System.out.println("null reply"); } } tmp = seq; System.out.print("************************************************************************"); for (int k = 0; k < wd / 10; k++) System.out.print("*"); System.out.println(); } Packet eof = new Packet(); eof.setMessage(Controller.EOF); host.send(connectionSocket, eof);//告知client数据传输完毕(不需要应答) } /** * 检查应答报文,并更新windows窗口状态 * @param packet 需要检查的报文 * @param window 需要更新的窗口 */ private static void checkAndRenew(Packet packet,Window window){ for (int i = 0; i < window.getSize() / window.getSegmentSize(); i++){ if (Transformer.toInteger(window.packets[i].getAck()) == Transformer.toInteger(packet.getId()) && packet.ackValid()){ window.packets[i].isAck = true; break; } } } /** * 对于收到的报文进行应答 * @param srcPacket 收到的报文 * @param connectionSocket 建立连接的服务端 * */ public void reply(Client client, Packet srcPacket, Socket connectionSocket) throws Exception{ if (srcPacket == null) { System.out.println("src = null!!!!!!!!!!!!!!!!!!!"); return; } if (sentPacket != null) { if (Transformer.toInteger(sentPacket.getAck()) != Transformer.toInteger(srcPacket.getId())) System.out.println("wrong sequence"); } byte[] seq = Transformer.toBytes(Transformer.toInteger(srcPacket.getAck()), 4); int len = 1; if (srcPacket.getData() != null) { len = srcPacket.getData().getData().length; } byte[] ack = Transformer.toBytes(Transformer.toInteger(srcPacket.getId()) + len, 4); byte[] spc = srcPacket.getSpcBytes(); spc[1] |= (byte) 0b0010000;//ACK=1 Packet p = new Packet( Transformer.toBytes(client.port, 2), srcPacket.getSrc(), seq, ack, spc, Transformer.toBytes(client.serverWindowSize, 2), srcPacket.getCheck(), new byte[]{0, 0}, new byte[]{}, new byte[]{}, MSS ); sentPacket = p; send(connectionSocket, p); } public Client(String addr, String serverPort, String port) { String addrPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)"; Pattern r = Pattern.compile(addrPattern); Matcher matcher = r.matcher(addr); if (matcher.find()) { serverAddr[0] = Byte.parseByte(matcher.group(1)); serverAddr[1] = Byte.parseByte(matcher.group(2)); serverAddr[2] = Byte.parseByte(matcher.group(3)); serverAddr[3] = Byte.parseByte(matcher.group(4)); } else { System.out.println("Wrong IP Address!"); } this.serverPort = Integer.parseInt(serverPort); this.port = Integer.parseInt(port); } public Client() { } /** 可能存在的指令(暂定): * send (filename) * get (filename) */ private static int cmd2number(Matcher matcher) { return Integer.parseInt(matcher.group(2)); } private static void setWindow(Client client, Socket socket, int window_size) throws Exception{ System.out.print("setting server."); client.printSleep(5, 200); System.out.println("done!"); Packet p = Controller.getCtrlPkt(window_size, "window"); client.send(socket, p); InputStream fromSvr = socket.getInputStream(); client.receive(client.buildPacket(client.getBytes(fromSvr))); //获取”控制应答“报文来知晓server window的更新,以确保后续报文正确 if (Error.check(client.receivedPacket) == Error.NO_ERROR) client.serverWindowSize = Transformer.toInteger(client.receivedPacket.getWindow()); System.out.println(new String(client.receivedPacket.getData().getData())); } private static void setMSS(Client client, Socket socket, int mss) throws Exception{ System.out.print("setting server."); client.printSleep(5, 200); System.out.println("done!"); Packet p = Controller.getCtrlPkt(mss, "MSS"); client.send(socket, p); InputStream fromSvr = socket.getInputStream(); client.receive(client.buildPacket(client.getBytes(fromSvr))); System.out.println(new String(client.receivedPacket.getData().getData())); } private static void getData(Client client, Socket socket, String s) throws Exception { String storeFileName = UUID.randomUUID().toString(); File newfile = new File(storeFileName); boolean flag = newfile.createNewFile(); FileOutputStream store = null; if (flag) { store = new FileOutputStream(storeFileName, true); } Packet p = Controller.getCtrlPkt(0, "get"); client.send(socket, p);//get报文的ACK视为0, 后续的都是1 while (true) { InputStream fromServer = socket.getInputStream(); Packet segment = client.buildPacket(client.getBytes(fromServer)); int chc = Controller.check(segment); if (chc == Controller.EOF) { client.printSleep(5, 200); System.out.println("send done!"); break; }//检查数据报文是否传输完毕 chc = Error.check(segment);//检查是否异常 if (chc != Error.NO_ERROR) { client.errorMsg(chc); client.send(socket, new Packet());//结束对方的阻塞相当于要求重传 continue; } if (flag) { byte[] data = segment.getData().getData(); store.write(data); } client.printSleep(5, 200); if (client.screen) { System.out.println("--------------------------receive data--------------------------"); System.out.println(); System.out.println(segment); System.out.println("----------------------------------------------------------------"); } client.reply(client, segment, socket); } if (flag) { System.out.println("'" + s + "'" + " has been stored in file '" + storeFileName + "'."); store.close(); } } protected void errorMsg(int chc) throws Exception{ switch (chc) { case Error.MISS_MSG: printSleep(10, 400); System.err.println("################## 丢失 ##################"); System.err.println("-------------------重传-------------------"); break; case Error.SHUFFLE_MSG: printSleep(5, 400); System.err.println("################## 乱序 ##################"); System.err.println("---------------按照序号重组---------------"); break; case Error.TIME_OUT: printSleep(5, 1000); System.err.println("################## 超时 ##################"); System.err.println("------------已获得重新传输内容------------"); break; case Error.WRONG_MSG: printSleep(5, 300); System.err.println("################## 出错 ##################"); System.err.println("-------------------重传-------------------"); break; default: break; } } private void check(Socket socket, Client client) throws Exception{ Packet ctrl = Controller.getCtrlPkt(0, "check"); client.send(socket, ctrl); InputStream stream = socket.getInputStream(); Packet rcv = client.buildPacket(client.getBytes(stream)); System.out.print(new String(rcv.getData().getData())); } public static void main(String[] argv) throws Exception{ String usr = "user"; int portTmp = 64; if (argv.length != 1) { System.out.println("Parameter count error!"); return; } try { portTmp = Integer.parseInt(argv[0]); if (portTmp < 0 || portTmp > 65535) { System.out.println("Invalid port!"); return; } }catch (Exception e) { System.out.println("Invalid port!"); return; } Scanner scanner = new Scanner(System.in); System.out.println("Client started!"); while (true) { System.out.println("Enter the ip to connect:"); String ip_str = scanner.next(); String addrPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)"; Pattern r = Pattern.compile(addrPattern); Matcher matcher = r.matcher(ip_str); if (!matcher.find()) { System.out.println("Invalid ip!"); continue; } System.out.println("Enter the port to connect:"); String serverPort = scanner.next(); try { int po = Integer.parseInt(serverPort); if (po < 0 || po > 65535) { System.out.println("Invalid port!"); continue; } }catch (Exception e) { System.out.println("Invalid port!"); continue; } try { Client client = new Client(ip_str, serverPort, String.valueOf(portTmp)); InetAddress address = InetAddress.getByAddress(client.serverAddr); Socket socket = new Socket(address, client.serverPort); client.buildConnection(socket); System.out.println("Connection succeeded!!!"); System.out.println("welcome!"); scanner.nextLine();//吃掉回车 while (true) { System.out.printf("%s> ", usr); String command = scanner.nextLine(); String pattern1 = "set\\s+-(w|m) (\\d+)"; String pattern1t = "set\\s+-(w|m)"; String pattern1tt = "^set.*"; String pattern2 = "^get\\s+(.+)$";// (pathname)设置要传的文件 String pattern3 = "^hostname\\s+(.+)$"; // hostname (name)设置用户名 //文件路径就绪才可传输(fileRdy) Pattern regex1 = Pattern.compile(pattern1), regex2 = Pattern.compile(pattern2), regex3 = Pattern.compile(pattern3); Pattern regex1t = Pattern.compile(pattern1t), regex1tt = Pattern.compile(pattern1tt); Matcher matcher1 = regex1.matcher(command), matcher2 = regex2.matcher(command), matcher3 = regex3.matcher(command); Matcher matcher1t = regex1t.matcher(command), matcher1tt = regex1tt.matcher(command); if (command.equals("quit") || command.equals("exit")) { Packet rel = Controller.getCtrlPkt(0, "release"); client.send(socket, rel); //模拟四次挥手过程 releaseConnection(client, socket); System.out.println("Bye, " + usr + "."); socket.close();//可能冗余,但是无害 return; }else if (matcher1.find()) { if (matcher1.group(1).equals("w")) { int window_size = cmd2number(matcher1); setWindow(client, socket, window_size); }else if (matcher1.group(1).equals("m")) { int mss = cmd2number(matcher1); setMSS(client, socket, mss); }else { System.out.printf("no command set %s.\n", matcher1.group(1)); } }else if (matcher1t.find()){ System.out.println("number param needed."); }else if (matcher1tt.find()) { System.out.println("You may mean 'set -w' or 'set -m' ?"); }else if (command.equals("set")){ System.out.println("set needs more params, use 'help' to learn."); }else if (matcher3.find()) { //hostname usr = matcher3.group(1); System.out.println("Hello, " + usr + "!"); }else if (command.equals("hostname")){ System.out.println("user name needed."); }else if (matcher2.find()) { //get file String s = matcher2.group(1); Packet ctrl = Controller.getCtrlPkt(s); Controller.setPath(client, ctrl, socket); client.sentPacket = null; if (client.fileRdy) { getData(client, socket, s); }else { System.out.println("No such file '" + s + "'"); } client.fileRdy = false; }else if (command.equals("get")) { System.out.println("filename needed."); }else if (command.equals("help")) { Controller.printHelp(); }else if (command.equals("display")) { System.out.println("回显模式开启"); client.screen = true; }else if (command.equals("close")) { System.out.println("回显模式关闭"); client.screen = false; }else if (command.equals("check")) { client.check(socket, client); } else { System.out.println("command '" + command + "' not found."); } } } catch (IOException e) { Thread.sleep(2000); System.out.println("Connection failed. Request time out..."); } }
NJU-ymhui/project2023
src/Client.java
7,384
//模拟四次挥手过程
line_comment
zh-cn
import java.io.*; import java.net.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.lang.Thread; public class Client { // Hello^_^, I'm Pchan. public Packet receivedPacket = null; public Packet sentPacket = null; public int MSS = 20; protected int port; protected Window window = new Window(); //创建一个窗口,维护这个window private byte[] serverAddr = new byte[4]; private int serverPort; protected ServerSocket welcomeSocket; protected Socket connectionSocket = null; public boolean fileRdy = false;//server的文件是否就绪 private int serverWindowSize = 100; public boolean screen = true; //是否回显,默认true protected void receive(Packet packet) { receivedPacket = packet; } /** * 从流里读字节直到读到终止符"\0~~~~" * */ protected byte[] getBytes(InputStream stream) throws Exception{ int byteRead; ArrayList<Byte> list = new ArrayList<>(); int quit = 0; boolean eof = false; while (quit < 4) { byteRead = stream.read(); if (byteRead == '\0') eof = true; else if ((byte) byteRead == '~' && eof) { quit++; }else { eof = false; quit = 0; } list.add((byte) byteRead); } byte[] buf = new byte[list.size() - 5]; for (int i = 0; i < list.size() - 5; i++) { buf[i] = list.get(i); } return buf; } protected boolean checkACK(Packet packet) { return packet.ackValid(); } protected boolean checkPSH(Packet packet) { return packet.pushNow(); } protected boolean checkRST(Packet packet) { return packet.isReset(); } protected boolean checkURG(Packet packet) { return packet.urgentValid(); } /** * 检查FIN位,判断是否挥手释放连接 * @param packet * @return boolean * */ protected boolean checkFIN(Packet packet) { return packet.checkFIN(); } /** * 检查SYN位,判断是否握手建立连接 * @param packet * @return boolean * */ protected boolean checkSYN(Packet packet) { return packet.checkSYN(); } /** * 该方法发送报文 * @param connectionSocket: 与客户端建立连结的服务端 * @param packet 报文 * */ protected void send(Socket connectionSocket, Packet packet) throws IOException { OutputStream outToServer = connectionSocket.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); if (packet == null) { System.out.println("error: nullPointerException in packet: NULL"); return; } out.write(packet.getBytes()); } /*** *回显当前报文内容,即显示收到的信息 *回显格式:src:... dest:... id:... ack:... window:... data:... */ protected void print() { System.out.println(receivedPacket); } /** * 把收到的字节流组装成报文, 字节流中一定包含首部,可能包含数据 * @param fromClient: 从客户端收到的字节流 * @return Packet: 组装后的报文 * */ protected Packet buildPacket(byte[] fromClient) { // System.out.println(fromClient.length); Packet p = new Packet(Arrays.copyOfRange(fromClient, 0, 2), Arrays.copyOfRange(fromClient, 2, 4), Arrays.copyOfRange(fromClient, 4, 8), Arrays.copyOfRange(fromClient, 8, 12), Arrays.copyOfRange(fromClient, 12, 14), Arrays.copyOfRange(fromClient, 14, 16), Arrays.copyOfRange(fromClient, 16, 18), Arrays.copyOfRange(fromClient, 18, 20), new byte[]{}, new byte[]{}, Transformer.toInteger(Arrays.copyOfRange(fromClient, 20, 24))); // System.out.println("gggg"); byte[] data = Arrays.copyOfRange(fromClient, 24, fromClient.length); if (data.length > 0) p.setData(new Data(data)); return p; } private void printSleep(int times, int slp) throws Exception{ for (int i = 0; i < times; i++) { Thread.sleep(slp); System.out.print("."); } Thread.sleep(slp); System.out.println(); } /** * Client握手建立连接 * */ private void buildConnection(Socket target) throws Exception { //ServerSocket welcomeSocket = new ServerSocket(port); System.out.println("Trying to connect " + target.getInetAddress().toString().substring(1) + ":" + serverPort + "..."); // 发送syn请求报文 int seq = new Random().nextInt(123);// 该报文第一个字节id byte[] id = Transformer.toBytes(seq, 4); int ack = 0; byte[] Ack = Transformer.toBytes(ack, 4); byte[] spcBytes = new byte[2]; spcBytes[1] = 2;// SYN置1 int checkSum = 0; Packet firstShakeHand = new Packet( Transformer.toBytes(port, 2), Transformer.toBytes(serverPort, 2), id, Ack, spcBytes, Transformer.toBytes(serverWindowSize, 2), Transformer.toBytes(checkSum, 2), new byte[]{0, 0}, new byte[]{}, new byte[]{}, MSS); System.out.println("开始握手:"); printSleep(5, 200); if (screen) { System.out.println("------------------------------first from client------------------------------"); System.out.println(); System.out.println(firstShakeHand); System.out.println("-----------------------------------------------------------------------------"); } send(target, firstShakeHand); // 接收Ack报文 InputStream bytesFromClient = target.getInputStream(); //OutputStream bytesToClient = target.getOutputStream(); byte[] buffer = getBytes(bytesFromClient);// buffer中存放client发来报文的字节形式 Packet secondHandShake = buildPacket(buffer);// 组装报文 receive(secondHandShake);// 收到client的第一次握手报文 MSS = secondHandShake.MSS; //MSS大小统一,先统一为server的(发数据方) printSleep(5, 200); if (screen) { System.out.println("-----------------------------second from server------------------------------"); System.out.println(); print();// 回显报文 System.out.println("-----------------------------------------------------------------------------"); } // 发送Ack报文 seq++; id = Transformer.toBytes(seq, 4); ack = Transformer.toInteger(receivedPacket.getId()) + 1;// 该报文ack应为上一个报文id + 1 Ack = Transformer.toBytes(ack, 4); spcBytes = new byte[2]; spcBytes[0] = receivedPacket.getSpcBytes()[0]; spcBytes[1] = (byte) (receivedPacket.getSpcBytes()[1] | (1 << 4));// ACK置1 Packet secondShakeHand = new Packet( receivedPacket.getDest(), receivedPacket.getSrc(), id, Ack, spcBytes, Transformer.toBytes(serverWindowSize, 2), Transformer.toBytes(checkSum, 2), receivedPacket.getUrgent(), receivedPacket.getOptions(), receivedPacket.getAlign(), receivedPacket.MSS ); printSleep(5, 200); if (screen) { System.out.println("-----------------------------third from client-------------------------------"); System.out.println(); System.out.println(secondShakeHand); System.out.println("-----------------------------------------------------------------------------"); } send(target, secondShakeHand); } /** * Client挥手释放连接 * */ private static void releaseConnection(Client client, Socket connectingSocket) throws Exception { System.out.println("开始挥手:"); int ack = 0; int checkSum = 0; int seq = new Random().nextInt(123);// 随机 InputStream bytesFromClient; byte[] buffer; byte[] id = Transformer.toBytes(seq, 4); byte[] Ack = Transformer.toBytes(ack, 4); byte[] spcBytes = new byte[2]; spcBytes[1] = (byte) 0b00000001;// FIN置1 Packet firstHandShake = new Packet( Transformer.toBytes(client.port, 2), Transformer.toBytes(client.serverPort, 2), id, Ack, spcBytes, Transformer.toBytes(client.serverWindowSize, 2), Transformer.toBytes(checkSum, 2), client.receivedPacket.getUrgent(), client.receivedPacket.getOptions(), client.receivedPacket.getAlign(), client.MSS); client.printSleep(5, 200); if (client.screen) { System.out.println("------------------------------first from client------------------------------"); System.out.println(); System.out.println(firstHandShake); System.out.println("-----------------------------------------------------------------------------"); } client.send(connectingSocket, firstHandShake); // client 进入 FIN-WAIT-1 bytesFromClient = connectingSocket.getInputStream(); buffer = client.getBytes(bytesFromClient); Packet secondShakeHand = client.buildPacket(buffer); client.receive(secondShakeHand); client.printSleep(5, 200); if(client.screen) { System.out.println("------------------------------second from server-----------------------------"); System.out.println(); client.print(); System.out.println("-----------------------------------------------------------------------------"); } System.out.print("等待剩余数据传输完毕."); client.printSleep(6, 300); //模拟数据传输完毕的确认 Packet ctrl = Controller.getCtrlPkt(0, "release");//可以继续释放连接 client.send(connectingSocket, ctrl); if (client.checkACK(secondShakeHand)) { // client 进入 FIN-WAIT-2 bytesFromClient = connectingSocket.getInputStream(); buffer = client.getBytes(bytesFromClient); Packet thirdShakeHand = client.buildPacket(buffer); client.receive(thirdShakeHand); client.printSleep(5, 200); if (client.screen) { System.out.println("------------------------------third from server------------------------------"); System.out.println(); client.print(); System.out.println("-----------------------------------------------------------------------------"); } if (client.checkFIN(thirdShakeHand)) { spcBytes[1] |= 0b00010000; //ACK=1 seq = Transformer.toInteger(client.receivedPacket.getAck()); ack = Transformer.toInteger(client.receivedPacket.getId()) + 1; Packet fourthHandShake = new Packet( client.receivedPacket.getDest(), client.receivedPacket.getSrc(), Transformer.toBytes(seq, 4), Transformer.toBytes(ack, 4), spcBytes, Transformer.toBytes(client.serverWindowSize, 2), Transformer.toBytes(checkSum, 2), client.receivedPacket.getUrgent(), client.receivedPacket.getOptions(), client.receivedPacket.getAlign(), client.receivedPacket.MSS); client.printSleep(5, 200); if (client.screen) { System.out.println("------------------------------fourth from client-----------------------------"); System.out.println(); System.out.println(fourthHandShake); System.out.println("-----------------------------------------------------------------------------"); } client.send(connectingSocket, fourthHandShake); // 进入TIME-WAIT超时等待2MSL System.out.print("wait for 2MSL."); client.printSleep(10, 200); System.out.println("Connection released!"); connectingSocket.close(); } else { System.out.println("Failed to release connection."); } // 不符合挥手规范,抛出异常 // } } else { System.out.println("Failed to release connection."); } // 不符合挥手规范,抛出异常 } /** * 数据传输 * @param host 发送方 * */ protected static void dataTransfer(Client host, Socket connectionSocket, String path) throws Exception { Window window1 = host.window; RandomAccessFile file = new RandomAccessFile(path, "r"); long fileLen = file.length(); long filePointer = file.getFilePointer(); int segmentSize = window1.getSegmentSize(), size = window1.getSize(); int windowBufferSize = size / segmentSize;//window一次可以放的报文段数 //第一个报文特殊处理 file.seek(filePointer); InputStream input = new FileInputStream(file.getFD()); int seq = new Random().nextInt(123);// 该报文第一个字节id int tmp = seq; //step1: 用数据包填满window(需要检查是否可以装填) int wd = 1, ack = 0; while (filePointer < fileLen){ System.out.println("*******************************第" + wd + "个窗口********************************"); System.out.println(); wd++; System.out.println("-----------------------------build packets------------------------------"); if (window1.ifFinished()) { while (!window1.full()) { if (filePointer >= fileLen) break; file.seek(filePointer); int cnt = 0; ArrayList<Byte> list = new ArrayList<Byte>(); while (cnt < segmentSize && filePointer < fileLen) { cnt++; filePointer++;//更新指针 list.add((byte) input.read()); } byte[] buffer = new byte[list.size()]; for (int i = 0; i < list.size(); i++) buffer[i] = list.get(i); byte[] id = Transformer.toBytes(seq, 4); //ack在不知道应答的时候无法确认是多少 byte[] Ack = Transformer.toBytes(ack, 4); byte[] spcBytes = new byte[2]; spcBytes[1] = (byte) (1 << 4);// ACK置1 int checkSum = 0; Packet p = new Packet( Transformer.toBytes(host.port, 2), host.receivedPacket.getSrc(), id, Ack, spcBytes, Transformer.toBytes(window1.getSize(), 2), Transformer.toBytes(checkSum, 2), host.receivedPacket.getUrgent(), host.receivedPacket.getOptions(), host.receivedPacket.getAlign(), host.receivedPacket.MSS ); p.setData(new Data(buffer)); window1.replace(p); Controller.printHex(p); seq += segmentSize; //if (seq < 0) seq += (1 << 31); } } System.out.println("packet has been in window"); System.out.println("------------------------------------------------------------------------"); System.out.println(); //step2: 处理应答、逐包发送 int i = 0; seq = tmp; for (int j = 0; j < window1.getSize() / window1.getSegmentSize(); j++) { if (window1.packets[j] == null || window1.packets[j].isAck) continue; //发送 window1.packets[j].setAck(Transformer.toBytes(ack, 4)); window1.packets[j].setId(Transformer.toBytes(seq, 4)); int possible = new Random().nextInt(1000); Packet p = window1.packets[j]; if (possible < 100) { if (possible < 25) { //miss p.setMessage(Error.MISS_MSG); }else if (possible < 50) { //shuffle p.setMessage(Error.SHUFFLE_MSG); }else if (possible < 75) { //timeout p.setMessage(Error.TIME_OUT); }else { //wrong p.setMessage(Error.WRONG_MSG); } host.send(connectionSocket, p); //阻塞等待重传要求 InputStream help = connectionSocket.getInputStream(); Packet buf = host.buildPacket(host.getBytes(help)); } window1.packets[j].setMessage(Error.NO_ERROR); System.out.println("------start sending packet:------"); Controller.printHex(window1.packets[j]); host.send(connectionSocket, window1.packets[j]); System.out.println("------------send done------------"); //处理应答 byte[] buffer; InputStream bytesFromServer = connectionSocket.getInputStream();// 获取字节流 buffer = host.getBytes(bytesFromServer);// buffer中存放发来报文的字节形式 System.out.println("receive reply"); Packet reply = host.buildPacket(buffer);// 组装报文 host.receive(reply);// 收到对方的reply ack = Transformer.toInteger(host.receivedPacket.getId()) + 1; seq = Transformer.toInteger(host.receivedPacket.getAck()); if (host.receivedPacket != null) { System.out.printf("第%d个应答: \n", ++i); // host.printSleep(); host.print();// 回显报文 checkAndRenew(host.receivedPacket, window1); } else { System.out.println("null reply"); } } tmp = seq; System.out.print("************************************************************************"); for (int k = 0; k < wd / 10; k++) System.out.print("*"); System.out.println(); } Packet eof = new Packet(); eof.setMessage(Controller.EOF); host.send(connectionSocket, eof);//告知client数据传输完毕(不需要应答) } /** * 检查应答报文,并更新windows窗口状态 * @param packet 需要检查的报文 * @param window 需要更新的窗口 */ private static void checkAndRenew(Packet packet,Window window){ for (int i = 0; i < window.getSize() / window.getSegmentSize(); i++){ if (Transformer.toInteger(window.packets[i].getAck()) == Transformer.toInteger(packet.getId()) && packet.ackValid()){ window.packets[i].isAck = true; break; } } } /** * 对于收到的报文进行应答 * @param srcPacket 收到的报文 * @param connectionSocket 建立连接的服务端 * */ public void reply(Client client, Packet srcPacket, Socket connectionSocket) throws Exception{ if (srcPacket == null) { System.out.println("src = null!!!!!!!!!!!!!!!!!!!"); return; } if (sentPacket != null) { if (Transformer.toInteger(sentPacket.getAck()) != Transformer.toInteger(srcPacket.getId())) System.out.println("wrong sequence"); } byte[] seq = Transformer.toBytes(Transformer.toInteger(srcPacket.getAck()), 4); int len = 1; if (srcPacket.getData() != null) { len = srcPacket.getData().getData().length; } byte[] ack = Transformer.toBytes(Transformer.toInteger(srcPacket.getId()) + len, 4); byte[] spc = srcPacket.getSpcBytes(); spc[1] |= (byte) 0b0010000;//ACK=1 Packet p = new Packet( Transformer.toBytes(client.port, 2), srcPacket.getSrc(), seq, ack, spc, Transformer.toBytes(client.serverWindowSize, 2), srcPacket.getCheck(), new byte[]{0, 0}, new byte[]{}, new byte[]{}, MSS ); sentPacket = p; send(connectionSocket, p); } public Client(String addr, String serverPort, String port) { String addrPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)"; Pattern r = Pattern.compile(addrPattern); Matcher matcher = r.matcher(addr); if (matcher.find()) { serverAddr[0] = Byte.parseByte(matcher.group(1)); serverAddr[1] = Byte.parseByte(matcher.group(2)); serverAddr[2] = Byte.parseByte(matcher.group(3)); serverAddr[3] = Byte.parseByte(matcher.group(4)); } else { System.out.println("Wrong IP Address!"); } this.serverPort = Integer.parseInt(serverPort); this.port = Integer.parseInt(port); } public Client() { } /** 可能存在的指令(暂定): * send (filename) * get (filename) */ private static int cmd2number(Matcher matcher) { return Integer.parseInt(matcher.group(2)); } private static void setWindow(Client client, Socket socket, int window_size) throws Exception{ System.out.print("setting server."); client.printSleep(5, 200); System.out.println("done!"); Packet p = Controller.getCtrlPkt(window_size, "window"); client.send(socket, p); InputStream fromSvr = socket.getInputStream(); client.receive(client.buildPacket(client.getBytes(fromSvr))); //获取”控制应答“报文来知晓server window的更新,以确保后续报文正确 if (Error.check(client.receivedPacket) == Error.NO_ERROR) client.serverWindowSize = Transformer.toInteger(client.receivedPacket.getWindow()); System.out.println(new String(client.receivedPacket.getData().getData())); } private static void setMSS(Client client, Socket socket, int mss) throws Exception{ System.out.print("setting server."); client.printSleep(5, 200); System.out.println("done!"); Packet p = Controller.getCtrlPkt(mss, "MSS"); client.send(socket, p); InputStream fromSvr = socket.getInputStream(); client.receive(client.buildPacket(client.getBytes(fromSvr))); System.out.println(new String(client.receivedPacket.getData().getData())); } private static void getData(Client client, Socket socket, String s) throws Exception { String storeFileName = UUID.randomUUID().toString(); File newfile = new File(storeFileName); boolean flag = newfile.createNewFile(); FileOutputStream store = null; if (flag) { store = new FileOutputStream(storeFileName, true); } Packet p = Controller.getCtrlPkt(0, "get"); client.send(socket, p);//get报文的ACK视为0, 后续的都是1 while (true) { InputStream fromServer = socket.getInputStream(); Packet segment = client.buildPacket(client.getBytes(fromServer)); int chc = Controller.check(segment); if (chc == Controller.EOF) { client.printSleep(5, 200); System.out.println("send done!"); break; }//检查数据报文是否传输完毕 chc = Error.check(segment);//检查是否异常 if (chc != Error.NO_ERROR) { client.errorMsg(chc); client.send(socket, new Packet());//结束对方的阻塞相当于要求重传 continue; } if (flag) { byte[] data = segment.getData().getData(); store.write(data); } client.printSleep(5, 200); if (client.screen) { System.out.println("--------------------------receive data--------------------------"); System.out.println(); System.out.println(segment); System.out.println("----------------------------------------------------------------"); } client.reply(client, segment, socket); } if (flag) { System.out.println("'" + s + "'" + " has been stored in file '" + storeFileName + "'."); store.close(); } } protected void errorMsg(int chc) throws Exception{ switch (chc) { case Error.MISS_MSG: printSleep(10, 400); System.err.println("################## 丢失 ##################"); System.err.println("-------------------重传-------------------"); break; case Error.SHUFFLE_MSG: printSleep(5, 400); System.err.println("################## 乱序 ##################"); System.err.println("---------------按照序号重组---------------"); break; case Error.TIME_OUT: printSleep(5, 1000); System.err.println("################## 超时 ##################"); System.err.println("------------已获得重新传输内容------------"); break; case Error.WRONG_MSG: printSleep(5, 300); System.err.println("################## 出错 ##################"); System.err.println("-------------------重传-------------------"); break; default: break; } } private void check(Socket socket, Client client) throws Exception{ Packet ctrl = Controller.getCtrlPkt(0, "check"); client.send(socket, ctrl); InputStream stream = socket.getInputStream(); Packet rcv = client.buildPacket(client.getBytes(stream)); System.out.print(new String(rcv.getData().getData())); } public static void main(String[] argv) throws Exception{ String usr = "user"; int portTmp = 64; if (argv.length != 1) { System.out.println("Parameter count error!"); return; } try { portTmp = Integer.parseInt(argv[0]); if (portTmp < 0 || portTmp > 65535) { System.out.println("Invalid port!"); return; } }catch (Exception e) { System.out.println("Invalid port!"); return; } Scanner scanner = new Scanner(System.in); System.out.println("Client started!"); while (true) { System.out.println("Enter the ip to connect:"); String ip_str = scanner.next(); String addrPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)"; Pattern r = Pattern.compile(addrPattern); Matcher matcher = r.matcher(ip_str); if (!matcher.find()) { System.out.println("Invalid ip!"); continue; } System.out.println("Enter the port to connect:"); String serverPort = scanner.next(); try { int po = Integer.parseInt(serverPort); if (po < 0 || po > 65535) { System.out.println("Invalid port!"); continue; } }catch (Exception e) { System.out.println("Invalid port!"); continue; } try { Client client = new Client(ip_str, serverPort, String.valueOf(portTmp)); InetAddress address = InetAddress.getByAddress(client.serverAddr); Socket socket = new Socket(address, client.serverPort); client.buildConnection(socket); System.out.println("Connection succeeded!!!"); System.out.println("welcome!"); scanner.nextLine();//吃掉回车 while (true) { System.out.printf("%s> ", usr); String command = scanner.nextLine(); String pattern1 = "set\\s+-(w|m) (\\d+)"; String pattern1t = "set\\s+-(w|m)"; String pattern1tt = "^set.*"; String pattern2 = "^get\\s+(.+)$";// (pathname)设置要传的文件 String pattern3 = "^hostname\\s+(.+)$"; // hostname (name)设置用户名 //文件路径就绪才可传输(fileRdy) Pattern regex1 = Pattern.compile(pattern1), regex2 = Pattern.compile(pattern2), regex3 = Pattern.compile(pattern3); Pattern regex1t = Pattern.compile(pattern1t), regex1tt = Pattern.compile(pattern1tt); Matcher matcher1 = regex1.matcher(command), matcher2 = regex2.matcher(command), matcher3 = regex3.matcher(command); Matcher matcher1t = regex1t.matcher(command), matcher1tt = regex1tt.matcher(command); if (command.equals("quit") || command.equals("exit")) { Packet rel = Controller.getCtrlPkt(0, "release"); client.send(socket, rel); //模拟 <SUF> releaseConnection(client, socket); System.out.println("Bye, " + usr + "."); socket.close();//可能冗余,但是无害 return; }else if (matcher1.find()) { if (matcher1.group(1).equals("w")) { int window_size = cmd2number(matcher1); setWindow(client, socket, window_size); }else if (matcher1.group(1).equals("m")) { int mss = cmd2number(matcher1); setMSS(client, socket, mss); }else { System.out.printf("no command set %s.\n", matcher1.group(1)); } }else if (matcher1t.find()){ System.out.println("number param needed."); }else if (matcher1tt.find()) { System.out.println("You may mean 'set -w' or 'set -m' ?"); }else if (command.equals("set")){ System.out.println("set needs more params, use 'help' to learn."); }else if (matcher3.find()) { //hostname usr = matcher3.group(1); System.out.println("Hello, " + usr + "!"); }else if (command.equals("hostname")){ System.out.println("user name needed."); }else if (matcher2.find()) { //get file String s = matcher2.group(1); Packet ctrl = Controller.getCtrlPkt(s); Controller.setPath(client, ctrl, socket); client.sentPacket = null; if (client.fileRdy) { getData(client, socket, s); }else { System.out.println("No such file '" + s + "'"); } client.fileRdy = false; }else if (command.equals("get")) { System.out.println("filename needed."); }else if (command.equals("help")) { Controller.printHelp(); }else if (command.equals("display")) { System.out.println("回显模式开启"); client.screen = true; }else if (command.equals("close")) { System.out.println("回显模式关闭"); client.screen = false; }else if (command.equals("check")) { client.check(socket, client); } else { System.out.println("command '" + command + "' not found."); } } } catch (IOException e) { Thread.sleep(2000); System.out.println("Connection failed. Request time out..."); } }
true
52402_5
package bl; import java.sql.Date; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import po.DatePack; import po.HistoryData; import po.QuotaData; import pr.HistoryDataPr; import pr.QuotaDataPr; import tool.CrossResult; import tool.CrossTool; import tool.MMSTool; import tool.TrendFlag; import tool.TrendPoint; import tool.TrendTool; import vo.QuotaAnalysis; import mapper.HistoryDataMapper; import mapper.QuotaDataMapper; public class BollAnalyse extends QuotaAnalyse{ private HistoryDataMapper historyDataMapper; private double deviation; public BollAnalyse(String siid) { super(siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String type,String siid) { super(type,siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String siid,double deviation) { super(siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } public BollAnalyse(String type,String siid,double deviation) { super(type,siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } public BollAnalyse(String siid,Date enddate) { super(siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String type,String siid,Date enddate) { super(type,siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String siid,Date enddate,double deviation) { super(siid,enddate); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } public BollAnalyse(String type,String siid,Date enddate,double deviation) { super(type,siid,enddate); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } /**评分标准:以5日来的趋势和交叉情况判断买卖情况 * 一个卖/买点加分 */ public QuotaAnalysis pro_quo() throws Exception { double scoreIn5=0; double scoreOut5=0; DatePack datePack=new DatePack(); datePack.setSiid(siid); datePack.setDate1(enddate); datePack.setNum(5); QuotaData quotaData_new=quotaDataMapper.selectQuotaData_latest(datePack); datePack.setDate1(quotaData_new.getDate()); List<Double> boll1list5=quotaDataMapper.selectBoll1_num_date(datePack); List<Double> boll2list5=quotaDataMapper.selectBoll2_num_date(datePack); List<Double> boll3list5=quotaDataMapper.selectBoll3_num_date(datePack); List<Double> closelist5=historyDataMapper.selectHistoryDataClose_num_date(datePack); List<Long> volumelist5=historyDataMapper.selectHistoryDataVolume_num_date(datePack); List<TrendPoint> closetrend5=new ArrayList<TrendPoint>(); List<TrendPoint> volumetrend5=new ArrayList<TrendPoint>(); List<TrendPoint> boll1trend5=new ArrayList<TrendPoint>(); List<TrendPoint> boll2trend5=new ArrayList<TrendPoint>(); List<TrendPoint> boll3trend5=new ArrayList<TrendPoint>(); List<Double> closeincrease5=new ArrayList<Double>(); List<Double> volumeincrease5=new ArrayList<Double>(); List<Double> boll1increase5=new ArrayList<Double>(); List<Double> boll2increase5=new ArrayList<Double>(); List<Double> boll3increase5=new ArrayList<Double>(); closetrend5.add(new TrendPoint(0,closelist5.get(0))); volumetrend5.add(new TrendPoint(0,volumelist5.get(0))); boll1trend5.add(new TrendPoint(0,boll1list5.get(0))); boll2trend5.add(new TrendPoint(0,boll2list5.get(0))); boll3trend5.add(new TrendPoint(0,boll3list5.get(0))); for(int i=1;i<boll1list5.size();i++) { closetrend5.add(new TrendPoint(i,closelist5.get(i))); boll1trend5.add(new TrendPoint(i,boll1list5.get(i))); boll2trend5.add(new TrendPoint(i,boll2list5.get(i))); boll3trend5.add(new TrendPoint(i,boll3list5.get(i))); volumetrend5.add(new TrendPoint(i,volumelist5.get(i))); closeincrease5.add(closelist5.get(i)-closelist5.get(i-1)); boll3increase5.add(boll3list5.get(i)-boll3list5.get(i-1)); volumeincrease5.add((double) (volumelist5.get(i)-volumelist5.get(i-1))); } TrendPoint min=MMSTool.min_trendpoint(closetrend5); TrendPoint max=MMSTool.max_trendpoint(closetrend5); double closeStandard=MMSTool.absmean_double(closeincrease5); TrendFlag closeflag5=new TrendTool(closeStandard,closetrend5).trend(); TrendFlag boll1flag5=new TrendTool(MMSTool.absmean_double(boll1increase5),boll1trend5).trend(); TrendFlag boll2flag5=new TrendTool(MMSTool.absmean_double(boll2increase5),boll2trend5).trend(); TrendFlag boll3flag5=new TrendTool(MMSTool.absmean_double(boll3increase5),boll3trend5).trend(); TrendFlag volumeflag5=new TrendTool(MMSTool.absmean_double(volumeincrease5),volumetrend5).trend(); /*下轨走平或上涨时,股价下跌到下轨获得支撑为买入信号, 成交量温和放大,看涨信号更可靠 如果股价突破中轨,上涨趋势形成,由下轨支撑到突破中轨所耗费的时间越短,看涨信号越强烈*/ if(boll3flag5.trend>=0&&min.index>=1&&min.index<=closelist5.size()-1) { TrendFlag closeflag5_front=new TrendTool(closeStandard,closetrend5.subList(0, min.index+1)).trend(); TrendFlag closeflag5_back=new TrendTool(closeStandard,closetrend5.subList(min.index,closetrend5.size())).trend(); if(closeflag5_front.trend<0&&closeflag5_back.trend<=0&&min.value>=boll3list5.get(min.index)*(1-deviation)) { //股价跌到下轨获得支撑 scoreIn5+=60; analysis.message+="Boll下轨走平或上涨时股价跌到下轨获得支撑,建议买入.\n"; if(volumeflag5.trend>0&&volumeflag5.trend<Math.PI/6) { //成交量温和放大 scoreIn5+=10; analysis.message+="成交量温和放大,买入信号更可信.\n"; } CrossResult crossResult=new CrossTool(closelist5,boll2list5).cross(); if(crossResult.cross>0&&crossResult.crosspoint-min.index!=0) { analysis.message+="股价突破中轨,上涨趋势形成,买入信号更可信.\n"; scoreIn5+=1.0/(crossResult.crosspoint-min.index)*20; } } } /*下跌到下轨时,股价沿下轨一起下跌应继续观望*/ if(closeflag5.trend<0&&boll3flag5.trend<0&&closelist5.get(closelist5.size()-1)<boll3list5.get(boll3list5.size()-1)*(1+deviation)) { scoreIn5=0; analysis.message+="下跌到下轨时,股价沿下轨一起下跌应继续观望.\n"; } /*股价在上轨遇阻回调,轻仓观望,股价跌破中轨,下跌趋势已经形成,尽快卖出,间隔时间越短,看跌信号越强烈 当股价遇阻回调时,如果KDJ指标中K和D在高位出现死叉,是对看跌信号的确认,尽快卖出*/ if(max.index>=1&&max.index<=closelist5.size()-1) { TrendFlag closeflag5_front=new TrendTool(closeStandard,closetrend5.subList(0, min.index+1)).trend(); TrendFlag closeflag5_back=new TrendTool(closeStandard,closetrend5.subList(min.index,closetrend5.size())).trend(); if(closeflag5_front.trend>0&&closeflag5_back.trend<=0&&max.value<=boll1list5.get(min.index)*(1+deviation)) { //股价在上轨遇阻回调 scoreOut5+=60; analysis.message+="股价在上轨遇阻回调,轻仓观望.\n"; if(volumeflag5.trend<0&&volumeflag5.trend>-Math.PI/6) { //成交量温和减少 scoreOut5+=10; analysis.message+="成交量温和减少,卖出信号更可信.\n"; } CrossResult crossResult=new CrossTool(closelist5,boll2list5).cross(); if(crossResult.cross<0&&crossResult.crosspoint-max.index!=0) { analysis.message+="股价跌破中轨,下跌趋势已经形成,尽快卖出.\n"; scoreIn5+=1.0/(crossResult.crosspoint-max.index)*20; } } } /*如股价上涨到上轨附近没有遇到阻力下跌,而是沿上轨上涨,是上涨行情还将继续的信号,可放心持股*/ if(closeflag5.trend>0&&boll1flag5.trend>0&&closelist5.get(closelist5.size()-1)>boll1list5.get(boll1list5.size()-1)*(1-deviation)) { scoreOut5=0; analysis.message+="股价上涨到上轨附近没有遇到阻力下跌,而是沿上轨上涨,是上涨行情还将继续的信号,可放心持股.\n"; } /*股价突破上轨表示进入短暂狂热状态,当跌破上轨时,有超买回调的危险,尽快卖出 如果跌回轨道内后仍沿着上轨继续上涨,则未来还可能有一定上涨空间,可以轻仓观望 当股价突破上轨,KDJ中J进入100以上区域,如果J重新跌落到100以下时,形成另一个卖点*/ if(closelist5.get(closelist5.size()-1)>boll1list5.get(boll1list5.size()-1)) { scoreOut5=80; analysis.message+="股价跌破上轨,有超买回调的危险,尽快卖出.\n"; } analysis.scoreIn=DataHelper.controldigit(scoreIn5); analysis.scoreOut=DataHelper.controldigit(scoreOut5); return analysis; } }
NJUse2014yz/AnyQuant
AnyQuant_web/src/main/java/bl/BollAnalyse.java
3,357
/*股价在上轨遇阻回调,轻仓观望,股价跌破中轨,下跌趋势已经形成,尽快卖出,间隔时间越短,看跌信号越强烈 当股价遇阻回调时,如果KDJ指标中K和D在高位出现死叉,是对看跌信号的确认,尽快卖出*/
block_comment
zh-cn
package bl; import java.sql.Date; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import po.DatePack; import po.HistoryData; import po.QuotaData; import pr.HistoryDataPr; import pr.QuotaDataPr; import tool.CrossResult; import tool.CrossTool; import tool.MMSTool; import tool.TrendFlag; import tool.TrendPoint; import tool.TrendTool; import vo.QuotaAnalysis; import mapper.HistoryDataMapper; import mapper.QuotaDataMapper; public class BollAnalyse extends QuotaAnalyse{ private HistoryDataMapper historyDataMapper; private double deviation; public BollAnalyse(String siid) { super(siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String type,String siid) { super(type,siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String siid,double deviation) { super(siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } public BollAnalyse(String type,String siid,double deviation) { super(type,siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } public BollAnalyse(String siid,Date enddate) { super(siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String type,String siid,Date enddate) { super(type,siid); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); deviation=0.05; analysis.message="boll: "; } public BollAnalyse(String siid,Date enddate,double deviation) { super(siid,enddate); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } public BollAnalyse(String type,String siid,Date enddate,double deviation) { super(type,siid,enddate); historyDataMapper=(HistoryDataMapper) applicationContext.getBean("historyDataMapper"); this.deviation=deviation; analysis.message="boll: "; } /**评分标准:以5日来的趋势和交叉情况判断买卖情况 * 一个卖/买点加分 */ public QuotaAnalysis pro_quo() throws Exception { double scoreIn5=0; double scoreOut5=0; DatePack datePack=new DatePack(); datePack.setSiid(siid); datePack.setDate1(enddate); datePack.setNum(5); QuotaData quotaData_new=quotaDataMapper.selectQuotaData_latest(datePack); datePack.setDate1(quotaData_new.getDate()); List<Double> boll1list5=quotaDataMapper.selectBoll1_num_date(datePack); List<Double> boll2list5=quotaDataMapper.selectBoll2_num_date(datePack); List<Double> boll3list5=quotaDataMapper.selectBoll3_num_date(datePack); List<Double> closelist5=historyDataMapper.selectHistoryDataClose_num_date(datePack); List<Long> volumelist5=historyDataMapper.selectHistoryDataVolume_num_date(datePack); List<TrendPoint> closetrend5=new ArrayList<TrendPoint>(); List<TrendPoint> volumetrend5=new ArrayList<TrendPoint>(); List<TrendPoint> boll1trend5=new ArrayList<TrendPoint>(); List<TrendPoint> boll2trend5=new ArrayList<TrendPoint>(); List<TrendPoint> boll3trend5=new ArrayList<TrendPoint>(); List<Double> closeincrease5=new ArrayList<Double>(); List<Double> volumeincrease5=new ArrayList<Double>(); List<Double> boll1increase5=new ArrayList<Double>(); List<Double> boll2increase5=new ArrayList<Double>(); List<Double> boll3increase5=new ArrayList<Double>(); closetrend5.add(new TrendPoint(0,closelist5.get(0))); volumetrend5.add(new TrendPoint(0,volumelist5.get(0))); boll1trend5.add(new TrendPoint(0,boll1list5.get(0))); boll2trend5.add(new TrendPoint(0,boll2list5.get(0))); boll3trend5.add(new TrendPoint(0,boll3list5.get(0))); for(int i=1;i<boll1list5.size();i++) { closetrend5.add(new TrendPoint(i,closelist5.get(i))); boll1trend5.add(new TrendPoint(i,boll1list5.get(i))); boll2trend5.add(new TrendPoint(i,boll2list5.get(i))); boll3trend5.add(new TrendPoint(i,boll3list5.get(i))); volumetrend5.add(new TrendPoint(i,volumelist5.get(i))); closeincrease5.add(closelist5.get(i)-closelist5.get(i-1)); boll3increase5.add(boll3list5.get(i)-boll3list5.get(i-1)); volumeincrease5.add((double) (volumelist5.get(i)-volumelist5.get(i-1))); } TrendPoint min=MMSTool.min_trendpoint(closetrend5); TrendPoint max=MMSTool.max_trendpoint(closetrend5); double closeStandard=MMSTool.absmean_double(closeincrease5); TrendFlag closeflag5=new TrendTool(closeStandard,closetrend5).trend(); TrendFlag boll1flag5=new TrendTool(MMSTool.absmean_double(boll1increase5),boll1trend5).trend(); TrendFlag boll2flag5=new TrendTool(MMSTool.absmean_double(boll2increase5),boll2trend5).trend(); TrendFlag boll3flag5=new TrendTool(MMSTool.absmean_double(boll3increase5),boll3trend5).trend(); TrendFlag volumeflag5=new TrendTool(MMSTool.absmean_double(volumeincrease5),volumetrend5).trend(); /*下轨走平或上涨时,股价下跌到下轨获得支撑为买入信号, 成交量温和放大,看涨信号更可靠 如果股价突破中轨,上涨趋势形成,由下轨支撑到突破中轨所耗费的时间越短,看涨信号越强烈*/ if(boll3flag5.trend>=0&&min.index>=1&&min.index<=closelist5.size()-1) { TrendFlag closeflag5_front=new TrendTool(closeStandard,closetrend5.subList(0, min.index+1)).trend(); TrendFlag closeflag5_back=new TrendTool(closeStandard,closetrend5.subList(min.index,closetrend5.size())).trend(); if(closeflag5_front.trend<0&&closeflag5_back.trend<=0&&min.value>=boll3list5.get(min.index)*(1-deviation)) { //股价跌到下轨获得支撑 scoreIn5+=60; analysis.message+="Boll下轨走平或上涨时股价跌到下轨获得支撑,建议买入.\n"; if(volumeflag5.trend>0&&volumeflag5.trend<Math.PI/6) { //成交量温和放大 scoreIn5+=10; analysis.message+="成交量温和放大,买入信号更可信.\n"; } CrossResult crossResult=new CrossTool(closelist5,boll2list5).cross(); if(crossResult.cross>0&&crossResult.crosspoint-min.index!=0) { analysis.message+="股价突破中轨,上涨趋势形成,买入信号更可信.\n"; scoreIn5+=1.0/(crossResult.crosspoint-min.index)*20; } } } /*下跌到下轨时,股价沿下轨一起下跌应继续观望*/ if(closeflag5.trend<0&&boll3flag5.trend<0&&closelist5.get(closelist5.size()-1)<boll3list5.get(boll3list5.size()-1)*(1+deviation)) { scoreIn5=0; analysis.message+="下跌到下轨时,股价沿下轨一起下跌应继续观望.\n"; } /*股价在 <SUF>*/ if(max.index>=1&&max.index<=closelist5.size()-1) { TrendFlag closeflag5_front=new TrendTool(closeStandard,closetrend5.subList(0, min.index+1)).trend(); TrendFlag closeflag5_back=new TrendTool(closeStandard,closetrend5.subList(min.index,closetrend5.size())).trend(); if(closeflag5_front.trend>0&&closeflag5_back.trend<=0&&max.value<=boll1list5.get(min.index)*(1+deviation)) { //股价在上轨遇阻回调 scoreOut5+=60; analysis.message+="股价在上轨遇阻回调,轻仓观望.\n"; if(volumeflag5.trend<0&&volumeflag5.trend>-Math.PI/6) { //成交量温和减少 scoreOut5+=10; analysis.message+="成交量温和减少,卖出信号更可信.\n"; } CrossResult crossResult=new CrossTool(closelist5,boll2list5).cross(); if(crossResult.cross<0&&crossResult.crosspoint-max.index!=0) { analysis.message+="股价跌破中轨,下跌趋势已经形成,尽快卖出.\n"; scoreIn5+=1.0/(crossResult.crosspoint-max.index)*20; } } } /*如股价上涨到上轨附近没有遇到阻力下跌,而是沿上轨上涨,是上涨行情还将继续的信号,可放心持股*/ if(closeflag5.trend>0&&boll1flag5.trend>0&&closelist5.get(closelist5.size()-1)>boll1list5.get(boll1list5.size()-1)*(1-deviation)) { scoreOut5=0; analysis.message+="股价上涨到上轨附近没有遇到阻力下跌,而是沿上轨上涨,是上涨行情还将继续的信号,可放心持股.\n"; } /*股价突破上轨表示进入短暂狂热状态,当跌破上轨时,有超买回调的危险,尽快卖出 如果跌回轨道内后仍沿着上轨继续上涨,则未来还可能有一定上涨空间,可以轻仓观望 当股价突破上轨,KDJ中J进入100以上区域,如果J重新跌落到100以下时,形成另一个卖点*/ if(closelist5.get(closelist5.size()-1)>boll1list5.get(boll1list5.size()-1)) { scoreOut5=80; analysis.message+="股价跌破上轨,有超买回调的危险,尽快卖出.\n"; } analysis.scoreIn=DataHelper.controldigit(scoreIn5); analysis.scoreOut=DataHelper.controldigit(scoreOut5); return analysis; } }
true
62348_12
package po; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.List; /** * @author zqh */ @Entity @Table(name = "hotel", schema = "msoh_database") public class HotelPO implements Serializable, Cloneable { private static final long serialVersionUID = 1L; // 酒店名称 @Column(name = "hotelName") private String hotelName; // 酒店ID @Id @Column(name = "hotelID") private String hotelID; // 酒店地址 @Column(name = "hotelAddress") private String hotelAddress; // 酒店所处商圈 @Column(name = "area") private String area; // 酒店简介 @Column(name = "intro") private String intro; // 酒店设施(在数据库存储时无法存储List<String>,存成String,每个设施之间以';'分开 @Column(name = "infra") private String infra; // 酒店房间类型(在数据库存储时无法存储List<String>,存成String,每种房间类型之间以';'分开 @Column(name = "hotelRoomType") private String hotelRoomType; // 酒店星级 @Column(name = "star") private int star; // 酒店评分 @Column(name = "score") private double score; // 酒店经营许可证号 @Column(name = "license") private String license; // 酒店照片(在数据库存储时无法存储List<String>,存成String,每个图片链接之间以';'分开 @Column(name = "picUrl") private String picUrls; // 系统中该酒店负责人 @Column(name = "clerkID") private String clerkID; public HotelPO() { } public HotelPO(String hotelName, String hotelAddress, String area, String intro, String infra, String hotelRoomType, int star, double score, String license, String picUrls, String clerkID) { this.hotelName = hotelName; this.hotelAddress = hotelAddress; this.area = area; this.intro = intro; this.infra = infra; this.hotelRoomType = hotelRoomType; this.star = star; this.score = score; this.license = license; this.picUrls = picUrls; this.clerkID = clerkID; } public String getHotelName() { return hotelName; } public void setHotelName(String hotelName) { this.hotelName = hotelName; } public String getHotelAddress() { return hotelAddress; } public void setHotelAddress(String hotelAddress) { this.hotelAddress = hotelAddress; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getInfra() { return infra; } public void setInfra(String infra) { this.infra = infra; } public String getHotelRoomType() { return hotelRoomType; } public void setHotelRoomType(String hotelRoomType) { this.hotelRoomType = hotelRoomType; } public int getStar() { return star; } public void setStar(int star) { this.star = star; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getPicUrls() { return picUrls; } public void setPicUrls(String picUrls) { this.picUrls = picUrls; } public String getClerkID() { return clerkID; } public void setClerkID(String clerkID) { this.clerkID = clerkID; } public String getHotelID() { return hotelID; } public void setHotelID(String hotelID) { this.hotelID = hotelID; } @Override public Object clone() { HotelPO hotelPO = null; try { hotelPO = (HotelPO) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return hotelPO; } }
NJUxOctopus/MSOH
MSOHServer/src/main/java/po/HotelPO.java
1,126
// 系统中该酒店负责人
line_comment
zh-cn
package po; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.List; /** * @author zqh */ @Entity @Table(name = "hotel", schema = "msoh_database") public class HotelPO implements Serializable, Cloneable { private static final long serialVersionUID = 1L; // 酒店名称 @Column(name = "hotelName") private String hotelName; // 酒店ID @Id @Column(name = "hotelID") private String hotelID; // 酒店地址 @Column(name = "hotelAddress") private String hotelAddress; // 酒店所处商圈 @Column(name = "area") private String area; // 酒店简介 @Column(name = "intro") private String intro; // 酒店设施(在数据库存储时无法存储List<String>,存成String,每个设施之间以';'分开 @Column(name = "infra") private String infra; // 酒店房间类型(在数据库存储时无法存储List<String>,存成String,每种房间类型之间以';'分开 @Column(name = "hotelRoomType") private String hotelRoomType; // 酒店星级 @Column(name = "star") private int star; // 酒店评分 @Column(name = "score") private double score; // 酒店经营许可证号 @Column(name = "license") private String license; // 酒店照片(在数据库存储时无法存储List<String>,存成String,每个图片链接之间以';'分开 @Column(name = "picUrl") private String picUrls; // 系统 <SUF> @Column(name = "clerkID") private String clerkID; public HotelPO() { } public HotelPO(String hotelName, String hotelAddress, String area, String intro, String infra, String hotelRoomType, int star, double score, String license, String picUrls, String clerkID) { this.hotelName = hotelName; this.hotelAddress = hotelAddress; this.area = area; this.intro = intro; this.infra = infra; this.hotelRoomType = hotelRoomType; this.star = star; this.score = score; this.license = license; this.picUrls = picUrls; this.clerkID = clerkID; } public String getHotelName() { return hotelName; } public void setHotelName(String hotelName) { this.hotelName = hotelName; } public String getHotelAddress() { return hotelAddress; } public void setHotelAddress(String hotelAddress) { this.hotelAddress = hotelAddress; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getIntro() { return intro; } public void setIntro(String intro) { this.intro = intro; } public String getInfra() { return infra; } public void setInfra(String infra) { this.infra = infra; } public String getHotelRoomType() { return hotelRoomType; } public void setHotelRoomType(String hotelRoomType) { this.hotelRoomType = hotelRoomType; } public int getStar() { return star; } public void setStar(int star) { this.star = star; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getPicUrls() { return picUrls; } public void setPicUrls(String picUrls) { this.picUrls = picUrls; } public String getClerkID() { return clerkID; } public void setClerkID(String clerkID) { this.clerkID = clerkID; } public String getHotelID() { return hotelID; } public void setHotelID(String hotelID) { this.hotelID = hotelID; } @Override public Object clone() { HotelPO hotelPO = null; try { hotelPO = (HotelPO) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return hotelPO; } }
true
4043_11
package com.lingjoin.demo; import com.lingjoin.util.OSInfo; import com.sun.jna.Library; import com.sun.jna.Native; /** * 分词组件的Java接口,采用JNA技术来实现 * * @author move * */ public interface NlpirLib extends Library { // 定义并初始化接口的静态变量,通过JNA调用NLPIR.dll; NlpirLib Instance = (NlpirLib) Native.loadLibrary(OSInfo.getModulePath("NLPIR"), NlpirLib.class); /** * 组件初始化 * * @param sDataPath * Data文件夹的父目录,如果为空字符串(即:""),那么,程序自动从项目的根目录中寻找 * @param encoding * 编码格式,具体的编码对照如下: 0:GBK;1:UTF8;2:BIG5;3:GBK,里面包含繁体字 * @param sLicenceCode * 授权码,为空字符串(即:"")就可以了 * @return true:初始化成功;false:初始化失败 */ public boolean NLPIR_Init(String sDataPath, int encoding, String sLicenceCode); /** * 分词 * * @param sSrc * 文本内容 * @param bPOSTagged * 1:显示词性;0:不显示词性 * @return 分词结果 */ public String NLPIR_ParagraphProcess(String sParagraph, int bPOSTagged); /** * 分词 * * @param sSourceFilename * 文本文件的路径 * @param sResultFilename * 结果文件的路径 * @param bPOStagged * 1:显示词性;0:不显示词性 * @return */ public double NLPIR_FileProcess(String sSourceFilename, String sResultFilename, int bPOStagged); /** * 细粒度分词 * * @param lenWords * 文本内容 * @return 分词结果 */ public String NLPIR_FinerSegment(String lenWords); /** * 关键词 * * @param sLine * 文本内容 * @param nMaxKeyLimit * 生成关键词的个数上限 * @param bWeightOut * true:显示词性;false:不显示词性 * @return 关键词组成的字符串 备注:黑名单中出现的词,不会作为关键词出现 */ public String NLPIR_GetKeyWords(String sLine, int nMaxKeyLimit, boolean bWeightOut); /** * 关键词 * * @param sFilename * 文本文件的路径 * @param nMaxKeyLimit * 生成的关键词的个数上限 * @param bWeightOut * true:显示词性;false:不显示词性 * @return 关键词组成的字符串 备注:黑名单中出现的词,不会作为关键词出现 */ public String NLPIR_GetFileKeyWords(String sFilename, int nMaxKeyLimit, boolean bWeightOut); /** * 新词 * * @param sLine * 文本内容 * @param nMaxKeyLimit * 生成的新词的个数上限 * @param bWeightOut * true:显示词性;false:不显示词性 * @return 新词组成的字符串 */ public String NLPIR_GetNewWords(String sLine, int nMaxKeyLimit, boolean bWeightOut); /** * 新词 * * @param string * 文本文件的路径 * @param nMaxKeyLimit * 生成的新词的个数上限 * @param bWeightOut * true:显示词性信息;false:不显示词性信息 * @return 新词组成的字符串 */ public String NLPIR_GetFileNewWords(String sFilename, int nMaxKeyLimit, boolean bWeightOut); /** * 添加用户自定义词 * * @param userWord * 用户词 格式:单词+空格+词性,例如:你好 v * @return 1:内存中不存在;2:内存中已存在 备注:保存到内存中,下次初始化后失效,需要用save保存到文件中 */ public int NLPIR_AddUserWord(String userWord); /** * 保存用户自定义词(保存到文件中) * * @return 1:成功;0:失败 */ public int NLPIR_SaveTheUsrDic(); /** * 删除用户自定义词 * * @param sWord * 需要删除的单词 * @return 被删除单词在内存中的位置,-1表示不存在 备注:删除内存中的自定义词,下次初始化后失效,需要用save保存到文件中 */ public int NLPIR_DelUsrWord(String sWord); /** * 导入用户自定义词典 * * @param dictFileName * 用户词典的路径 * @param bOverwrite * 是否删除原有的自定义用户词典,true:删除;false:不删除 * @return 导入用户单词个数 备注:系统会自动处理重复词的问题 */ public int NLPIR_ImportUserDict(String dictFileName, boolean bOverwrite); /** * 导入关键词黑名单 * * @param sFilename * 文件的路径 * @return 备注:成功导入后,黑名单中出现的词,不会作为关键词出现 */ public int NLPIR_ImportKeyBlackList(String sFilename); /** * 文章指纹码 * * @param sLine * 文本内容 * @return 指纹码 */ public long NLPIR_FingerPrint(String sLine); /** * 单词的词性 * * @param sWords * 单词,例如:中华人民共和国 * @return 单词的词性,例如:中华人民共和国/ns/607# */ public String NLPIR_GetWordPOS(String sWords); /** * 判断单词是否在核心词库中 * * @param word * 输入的单词 * @return 如果单词不存在就返回-1,否则返回单词在词典中的句柄 */ public int NLPIR_IsWord(String word); /** * 获取输入文本的词,词性,频统计结果,按照词频大小排序 * * @param sText * 文本内容 * @return 词频统计结果形式如下:张华平/nr/10#博士/n/9#分词/n/8 */ public String NLPIR_WordFreqStat(String sText); /** * 获取输入文本文件的词,词性,频统计结果,按照词频大小排序 * * @param sFilename * 文本文件的全路径 * @return 词频统计结果形式如下:张华平/nr/10#博士/n/9#分词/n/8 */ public String NLPIR_FileWordFreqStat(String sFilename); /** * 获取各类英文单词的原型,考虑了过去分词、单复数等情况 * * @param sWord * 输入的单词 * @return 词原型形式,例如:driven->drive drives->drive drove-->drive */ public String NLPIR_GetEngWordOrign(String sWord); /** * 返回最后一次的出错信息 * * @return 最后一次的出错信息 */ public String NLPIR_GetLastErrorMsg(); /** * 退出,释放资源 * * @return */ public boolean NLPIR_Exit(); }
NLPIR-team/NLPIR
NLPIR SDK/NLPIR-ICTCLAS/projects/ICTCLAS_Java/src/com/lingjoin/demo/NlpirLib.java
1,894
/** * 保存用户自定义词(保存到文件中) * * @return 1:成功;0:失败 */
block_comment
zh-cn
package com.lingjoin.demo; import com.lingjoin.util.OSInfo; import com.sun.jna.Library; import com.sun.jna.Native; /** * 分词组件的Java接口,采用JNA技术来实现 * * @author move * */ public interface NlpirLib extends Library { // 定义并初始化接口的静态变量,通过JNA调用NLPIR.dll; NlpirLib Instance = (NlpirLib) Native.loadLibrary(OSInfo.getModulePath("NLPIR"), NlpirLib.class); /** * 组件初始化 * * @param sDataPath * Data文件夹的父目录,如果为空字符串(即:""),那么,程序自动从项目的根目录中寻找 * @param encoding * 编码格式,具体的编码对照如下: 0:GBK;1:UTF8;2:BIG5;3:GBK,里面包含繁体字 * @param sLicenceCode * 授权码,为空字符串(即:"")就可以了 * @return true:初始化成功;false:初始化失败 */ public boolean NLPIR_Init(String sDataPath, int encoding, String sLicenceCode); /** * 分词 * * @param sSrc * 文本内容 * @param bPOSTagged * 1:显示词性;0:不显示词性 * @return 分词结果 */ public String NLPIR_ParagraphProcess(String sParagraph, int bPOSTagged); /** * 分词 * * @param sSourceFilename * 文本文件的路径 * @param sResultFilename * 结果文件的路径 * @param bPOStagged * 1:显示词性;0:不显示词性 * @return */ public double NLPIR_FileProcess(String sSourceFilename, String sResultFilename, int bPOStagged); /** * 细粒度分词 * * @param lenWords * 文本内容 * @return 分词结果 */ public String NLPIR_FinerSegment(String lenWords); /** * 关键词 * * @param sLine * 文本内容 * @param nMaxKeyLimit * 生成关键词的个数上限 * @param bWeightOut * true:显示词性;false:不显示词性 * @return 关键词组成的字符串 备注:黑名单中出现的词,不会作为关键词出现 */ public String NLPIR_GetKeyWords(String sLine, int nMaxKeyLimit, boolean bWeightOut); /** * 关键词 * * @param sFilename * 文本文件的路径 * @param nMaxKeyLimit * 生成的关键词的个数上限 * @param bWeightOut * true:显示词性;false:不显示词性 * @return 关键词组成的字符串 备注:黑名单中出现的词,不会作为关键词出现 */ public String NLPIR_GetFileKeyWords(String sFilename, int nMaxKeyLimit, boolean bWeightOut); /** * 新词 * * @param sLine * 文本内容 * @param nMaxKeyLimit * 生成的新词的个数上限 * @param bWeightOut * true:显示词性;false:不显示词性 * @return 新词组成的字符串 */ public String NLPIR_GetNewWords(String sLine, int nMaxKeyLimit, boolean bWeightOut); /** * 新词 * * @param string * 文本文件的路径 * @param nMaxKeyLimit * 生成的新词的个数上限 * @param bWeightOut * true:显示词性信息;false:不显示词性信息 * @return 新词组成的字符串 */ public String NLPIR_GetFileNewWords(String sFilename, int nMaxKeyLimit, boolean bWeightOut); /** * 添加用户自定义词 * * @param userWord * 用户词 格式:单词+空格+词性,例如:你好 v * @return 1:内存中不存在;2:内存中已存在 备注:保存到内存中,下次初始化后失效,需要用save保存到文件中 */ public int NLPIR_AddUserWord(String userWord); /** * 保存用 <SUF>*/ public int NLPIR_SaveTheUsrDic(); /** * 删除用户自定义词 * * @param sWord * 需要删除的单词 * @return 被删除单词在内存中的位置,-1表示不存在 备注:删除内存中的自定义词,下次初始化后失效,需要用save保存到文件中 */ public int NLPIR_DelUsrWord(String sWord); /** * 导入用户自定义词典 * * @param dictFileName * 用户词典的路径 * @param bOverwrite * 是否删除原有的自定义用户词典,true:删除;false:不删除 * @return 导入用户单词个数 备注:系统会自动处理重复词的问题 */ public int NLPIR_ImportUserDict(String dictFileName, boolean bOverwrite); /** * 导入关键词黑名单 * * @param sFilename * 文件的路径 * @return 备注:成功导入后,黑名单中出现的词,不会作为关键词出现 */ public int NLPIR_ImportKeyBlackList(String sFilename); /** * 文章指纹码 * * @param sLine * 文本内容 * @return 指纹码 */ public long NLPIR_FingerPrint(String sLine); /** * 单词的词性 * * @param sWords * 单词,例如:中华人民共和国 * @return 单词的词性,例如:中华人民共和国/ns/607# */ public String NLPIR_GetWordPOS(String sWords); /** * 判断单词是否在核心词库中 * * @param word * 输入的单词 * @return 如果单词不存在就返回-1,否则返回单词在词典中的句柄 */ public int NLPIR_IsWord(String word); /** * 获取输入文本的词,词性,频统计结果,按照词频大小排序 * * @param sText * 文本内容 * @return 词频统计结果形式如下:张华平/nr/10#博士/n/9#分词/n/8 */ public String NLPIR_WordFreqStat(String sText); /** * 获取输入文本文件的词,词性,频统计结果,按照词频大小排序 * * @param sFilename * 文本文件的全路径 * @return 词频统计结果形式如下:张华平/nr/10#博士/n/9#分词/n/8 */ public String NLPIR_FileWordFreqStat(String sFilename); /** * 获取各类英文单词的原型,考虑了过去分词、单复数等情况 * * @param sWord * 输入的单词 * @return 词原型形式,例如:driven->drive drives->drive drove-->drive */ public String NLPIR_GetEngWordOrign(String sWord); /** * 返回最后一次的出错信息 * * @return 最后一次的出错信息 */ public String NLPIR_GetLastErrorMsg(); /** * 退出,释放资源 * * @return */ public boolean NLPIR_Exit(); }
true
61136_28
package org.nlpcn.jcoder.service; import com.alibaba.fastjson.JSONObject; import com.github.javaparser.ParseException; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.TypeDeclaration; import org.apache.curator.framework.CuratorFramework; import org.nlpcn.jcoder.constant.TaskStatus; import org.nlpcn.jcoder.constant.TaskType; import org.nlpcn.jcoder.domain.*; import org.nlpcn.jcoder.domain.CodeInfo.ExecuteMethod; import org.nlpcn.jcoder.filter.TestingFilter; import org.nlpcn.jcoder.run.CodeException; import org.nlpcn.jcoder.run.java.JavaRunner; import org.nlpcn.jcoder.scheduler.TaskRunManager; import org.nlpcn.jcoder.util.*; import org.nlpcn.jcoder.util.dao.BasicDao; import org.nutz.castor.Castors; import org.nutz.dao.Cnd; import org.nutz.dao.Condition; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.mvc.annotation.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static org.nlpcn.jcoder.service.SharedSpaceService.GROUP_PATH; @IocBean public class TaskService { public static final String VERSION_SPLIT = "_"; private static final Logger LOG = LoggerFactory.getLogger(TaskService.class); private static final ConcurrentHashMap<Object, Task> TASK_MAP_CACHE = new ConcurrentHashMap<>(); /** * 记录task执行成功失败的计数器 */ private static final Map<String, AtomicLong> taskSuccess = new ConcurrentHashMap<>(); /** * 记录task执行成功失败的计数器 */ private static final Map<String, AtomicLong> taskErr = new ConcurrentHashMap<>(); private BasicDao basicDao = StaticValue.systemDao; public static synchronized Task findTaskByCache(Long id) { return TASK_MAP_CACHE.get(id); } public static synchronized Task findTaskByCache(String groupName, String name) { return TASK_MAP_CACHE.get(makeKey(groupName, name)); } public static synchronized Task findTaskByDB(Long id) { LOG.info("find task by db!"); return StaticValue.systemDao.findByCondition(Task.class, Cnd.where("id", "=", id)); } public static synchronized TaskHistory findTaskByDBHistory(Long taskId, String version) { LOG.info("find task by dbHistory!"); return StaticValue.systemDao.findByCondition(TaskHistory.class, Cnd.where("version", "=", version).and("taskId", "=", taskId)); } public static List<TaskHistory> findDBHistory() { return StaticValue.systemDao.search(TaskHistory.class, Cnd.NEW()); } /** * 根据类型查找task集合 */ public static synchronized Collection<Task> findTaskList(Integer type) { Collection<Task> values = TASK_MAP_CACHE.values(); if (type == null) { return values; } LinkedHashSet<Task> result = new LinkedHashSet<>(); for (Task task : values) { if (type.equals(task.getType())) { result.add(task); } } return result; } /** * 查找出缓存中的所有task * * @return */ public static List<Task> findAllTasksByCache() { return TASK_MAP_CACHE.entrySet().stream().filter(e -> e.getKey() instanceof Long).map(e -> e.getValue()).collect(Collectors.toList()); } /** * 查找出缓存中的所有task * * @return */ public static List<Task> findAllTasksByCache(String groupName) { return findAllTasksByCache().stream().filter(t -> groupName.equals(t.getGroupName())).collect(Collectors.toList()); } // 生成任务的版本号 private static String generateVersion(Task t) { StringBuilder sb = new StringBuilder(); sb.append(t.getUpdateUser()); sb.append(VERSION_SPLIT); sb.append(DateUtils.formatDate(t.getUpdateTime(), "yyyy-MM-dd HH:mm:ss")); return sb.toString(); } /** * 内部执行一个task 绕过请求,request为用户请求地址,只限于内部api使用 */ public static <T> T executeTask(String className, String methodName, Map<String, Object> params) throws ExecutionException { return executeTask(StaticValue.getCurrentGroup(), className, methodName, params); } /** * 内部执行一个task 绕过请求,request为用户请求地址,只限于内部api使用 */ public static <T> T executeTask(String groupName, String className, String methodName, Map<String, Object> params) throws ExecutionException { Task task = findTaskByCache(groupName, className); if (task == null) { if (TestingFilter.methods != null) { LOG.info("use testing method to run "); return executeTaskByTest(groupName, className, methodName, params); } throw new ApiException(ApiException.NotFound, methodName + " not found"); } task = new JavaRunner(task).compile().instance().getTask(); ExecuteMethod method = task.codeInfo().getExecuteMethod(methodName); if (method == null) { throw new ApiException(ApiException.NotFound, methodName + "/" + methodName + " not found"); } Object[] args = map2Args(params, method.getMethod()); return (T) StaticValue.MAPPING.getOrCreateByUrl(groupName, className, methodName).getChain().getInvokeProcessor().executeByCache(task, method.getMethod(), args); } /** * 通过test方式执行内部调用 */ public static <T> T executeTaskByArgs(String groupName, String className, String methodName, Object... params) throws ExecutionException { Task task = findTaskByCache(groupName, className); if (task == null) { if (TestingFilter.methods != null) { LOG.info("use testing method to run "); return executeTaskByArgsByTest(className, methodName, params); } throw new ApiException(ApiException.NotFound, methodName + " not found"); } task = new JavaRunner(task).compile().instance().getTask(); ExecuteMethod method = task.codeInfo().getExecuteMethod(methodName); if (method == null) { throw new ApiException(ApiException.NotFound, methodName + "/" + methodName + " not found"); } Object[] args = array2Args(method.getMethod(), params); return (T) StaticValue.MAPPING.getOrCreateByUrl(groupName, className, methodName).getChain().getInvokeProcessor().executeByCache(task, method.getMethod(), args); } private static <T> T executeTaskByArgsByTest(String className, String methodName, Object[] params) throws ApiException { KeyValue<Method, Object> kv = TestingFilter.methods.get(className + "/" + methodName); if (kv == null) { throw new ApiException(ApiException.NotFound, methodName + " not found"); } Object[] args = array2Args(kv.getKey(), params); try { return (T) kv.getKey().invoke(kv.getValue(), args); } catch (Exception e) { e.printStackTrace(); throw new ApiException(500, e.getMessage()); } } /** * 通过test方式执行内部调用 */ private static <T> T executeTaskByTest(String groupName, String className, String methodName, Map<String, Object> params) throws ApiException { KeyValue<Method, Object> kv = TestingFilter.methods.get(groupName + "/" + className + "/" + methodName); if (kv == null) { throw new ApiException(ApiException.NotFound, methodName + " not found"); } Object[] args = map2Args(params, kv.getKey()); try { return (T) kv.getKey().invoke(kv.getValue(), args); } catch (Exception e) { e.printStackTrace(); throw new ApiException(500, e.getMessage()); } } /** * 将map转换为参数 */ public static Object[] map2Args(Map<String, Object> params, Method method) { Parameter[] parameters = method.getParameters(); Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; String name = parameter.getName(); if (!params.containsKey(name)) { Param annotation = parameter.getAnnotation(Param.class); if (annotation != null) { name = annotation.value(); } } args[i] = Castors.me().castTo(params.get(name), parameter.getType()); } return args; } /** * 将对象数组转换为参数 */ private static Object[] array2Args(Method method, Object... params) { Parameter[] parameters = method.getParameters(); Object[] args = new Object[parameters.length]; if (args.length != params.length) { throw new IllegalArgumentException("args.length " + args.length + " not equal params.length " + params.length); } for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; args[i] = Castors.me().castTo(params[i], parameter.getType()); } return args; } /** * 计数器,记录task成功失败个数 */ public static void counter(Task task, boolean success) { String groupTaskName = makeKey(task); if (success) { taskSuccess.compute(groupTaskName, (k, v) -> { if (v == null) { v = new AtomicLong(); } v.incrementAndGet(); return v; }); } else { taskErr.compute(groupTaskName, (k, v) -> { if (v == null) { v = new AtomicLong(); } v.incrementAndGet(); return v; }); } } /** * 获得一个task成功次数 */ public static long getSuccess(Task task) { AtomicLong atomicLong = taskSuccess.get(makeKey(task)); if (atomicLong == null) { return 0L; } else { return atomicLong.get(); } } /** * 获得一个task失败次数 */ public static long getError(Task task) { AtomicLong atomicLong = taskErr.get(makeKey(task)); if (atomicLong == null) { return 0L; } else { return atomicLong.get(); } } /** * 清空计数器 * * @param */ public static void clearSucessErr(Task task) { String groupTaskName = makeKey(task); taskErr.remove(groupTaskName); taskSuccess.remove(groupTaskName); } /** * 构建task_cache 的key groupName_taskName */ private static String makeKey(Task task) { return task.getGroupName() + "/" + task.getName(); } /** * 构建task_cache 的key groupName_taskName */ private static String makeKey(String groupName, String taskName) { return groupName + "/" + taskName; } /** * 根据分组名称获取所有Task * * @param groupName 组名 */ public List<Task> getTasksByGroupNameFromCluster(String groupName) throws Exception { CuratorFramework zk = StaticValue.space().getZk(); String path = GROUP_PATH + "/" + groupName; List<String> taskNames = zk.getChildren().forPath(path); List<Task> tasks = new ArrayList<>(taskNames.size()); Task t; for (String name : taskNames) { t = JSONObject.parseObject(zk.getData().forPath(path + "/" + name), Task.class); if (t != null && StringUtil.isNotBlank(t.getCode())) { tasks.add(t); } } return tasks; } /** * 根据分组名称获取所有Task * * @param groupName 组名 */ public Task getTaskFromCluster(String groupName, String taskName) { try { return StaticValue.space().getData(GROUP_PATH + "/" + groupName + "/" + taskName, Task.class); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 删除ZK集群里的Task * * @param groupName 组名 * @param taskName 任务名 */ public void deleteTaskFromCluster(String groupName, String taskName) throws Exception { String path = GROUP_PATH + "/" + groupName + "/" + taskName; LOG.info("to delete task in zookeeper: {}", path); if (!existsInCluster(groupName, taskName)) { LOG.warn("task[{}] not found in zookeeper", path); } else { StaticValue.space().getZk().delete().forPath(path); } } public boolean existsInCluster(String groupName, String taskName) throws Exception { return StaticValue.space().getZk().checkExists().forPath(GROUP_PATH + "/" + groupName + "/" + taskName) != null; } /** * 保存或者更新一个任务 */ public boolean saveOrUpdate(Task task) throws Exception { // 历史库版本保存 boolean isModify = checkTaskModify(task); String message = null; if ((validate(task)) != null) { throw new CodeException(message); } if (isModify) { String version = generateVersion(task); task.setVersion(version); } if (task.getId() == null) { task = basicDao.save(task); } else { basicDao.update(task); } if (isModify) { basicDao.save(new TaskHistory(task)); } flush(task.getId()); return isModify; } /** * 验证一个taskcode是否正确 */ public String validate(Task task) throws ParseException { String code = task.getCode(); String name = null; String pk = null; CompilationUnit compile = JavaDocUtil.compile(code); pk = compile.getPackage().getPackageName(); if (StringUtil.isBlank(pk)) { return ("package can not empty "); } List<TypeDeclaration> types = compile.getTypes(); for (TypeDeclaration type : types) { if (type.getModifiers() == Modifier.PUBLIC) { if (name != null) { return "class not have more than one public class "; } name = type.getName(); } } if (name == null) { return "not find className "; } return null; } /** * 判断task代码是否修改过 */ private boolean checkTaskModify(Task task) { Long id = task.getId(); if (id == null) { return true; } Task t = basicDao.find(id, Task.class); if (t == null) { return true; } if (!t.getCode().equals(task.getCode())) { return true; } return false; } /** * 刷新某个task */ public void flush(Long id) throws Exception { Task oldTask = TASK_MAP_CACHE.get(id); // 查找处新的task Task newTask = this.basicDao.find(id, Task.class); Task temp = new Task(); temp.setId(0L); temp.setName(""); if (oldTask == null) { oldTask = temp; } if (newTask == null) { newTask = temp; } synchronized (oldTask) { synchronized (newTask) { TASK_MAP_CACHE.remove(oldTask.getId()); TASK_MAP_CACHE.remove(makeKey(oldTask)); TASK_MAP_CACHE.put(newTask.getId(), newTask); TASK_MAP_CACHE.put(makeKey(newTask), newTask); clearSucessErr(oldTask); clearSucessErr(newTask); TaskRunManager.flush(oldTask, newTask); } } } /** * 删除一个任务 */ public void delete(Task task) throws Exception { task.setType(TaskType.RECYCLE.getValue()); task.setStatus(TaskStatus.STOP.getValue()); saveOrUpdate(task); } /** * 彻底删除一个任务 */ public void delByDB(Task task) { // 删除任务历史 basicDao.delByCondition(TaskHistory.class, Cnd.where("taskId", "=", task.getId())); // 删除任务 basicDao.delById(task.getId(), Task.class); //删除缓存中的 TASK_MAP_CACHE.remove(task.getId()); TASK_MAP_CACHE.remove(makeKey(task)); } public Task findTask(String groupName, String name) { return basicDao.findByCondition(Task.class, Cnd.where("groupName", "=", groupName).and("name", "=", name)); } public List<Task> findTasksByGroupName(String groupName) { LOG.info("find findTasksByGroupName from groupName: {}", groupName); return basicDao.search(Task.class, Cnd.where("groupName", "=", groupName)); } /** * 找到task根据groupName */ public LinkedHashSet<Task> findTaskByGroupNameCache(String groupName) { Collection<Task> values = TASK_MAP_CACHE.values(); LinkedHashSet<Task> result = new LinkedHashSet<>(); for (Task task : values) { if (groupName.equals(task.getGroupName())) { result.add(task); } } return result; } /** * 从数据库中init所有的task */ public synchronized void flushGroup(String groupName) { removeMapping(groupName); //刪除所有映射 createMapping(groupName); //插入所有映射 } private void createMapping(String groupName) { List<Task> search = findTasksByGroupName(groupName); for (Task task : search) { try { TASK_MAP_CACHE.put(task.getId(), task); TASK_MAP_CACHE.put(makeKey(task), task); try { new JavaRunner(task).compile(); Collection<ExecuteMethod> executeMethods = task.codeInfo().getExecuteMethods(); executeMethods.forEach(e -> { StaticValue.space().addMapping(task.getGroupName(), task.getName(), e.getMethod().getName()); }); } catch (Exception e) { LOG.error("compile {}/{} err ", task.getGroupName(), task.getCode(), e); } } catch (Throwable e) { e.printStackTrace(); LOG.error(e.getMessage(), e); } } } private void removeMapping(String groupName) { //查询出缓存中的所有task并移除 List<Task> search = findAllTasksByCache(groupName); for (Task task : search) { try { task.codeInfo().getExecuteMethods().forEach(m -> { StaticValue.space().removeMapping(task.getGroupName(), task.getName(), m.getName()); }); StaticValue.MAPPING.remove(task.getGroupName(), task.getName());//删掉urlmapping重新加载 TASK_MAP_CACHE.remove(task.getId()); TASK_MAP_CACHE.remove(makeKey(task)); } catch (Throwable e) { e.printStackTrace(); LOG.error(e.getMessage(), e); } } } /** * @param taskId * @param size * @return */ public List<String> versions(Long taskId, int size) { List<String> list = new ArrayList<>(); Condition cnd = Cnd.where("taskId", "=", taskId).desc("id"); List<TaskHistory> tasks = basicDao.search(TaskHistory.class, cnd); for (TaskHistory taskHistory : tasks) { list.add(taskHistory.getVersion()); if (size-- == 0) { break; } } return list; } }
NLPchina/Jcoder
src/main/java/org/nlpcn/jcoder/service/TaskService.java
5,173
/** * 彻底删除一个任务 */
block_comment
zh-cn
package org.nlpcn.jcoder.service; import com.alibaba.fastjson.JSONObject; import com.github.javaparser.ParseException; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.body.TypeDeclaration; import org.apache.curator.framework.CuratorFramework; import org.nlpcn.jcoder.constant.TaskStatus; import org.nlpcn.jcoder.constant.TaskType; import org.nlpcn.jcoder.domain.*; import org.nlpcn.jcoder.domain.CodeInfo.ExecuteMethod; import org.nlpcn.jcoder.filter.TestingFilter; import org.nlpcn.jcoder.run.CodeException; import org.nlpcn.jcoder.run.java.JavaRunner; import org.nlpcn.jcoder.scheduler.TaskRunManager; import org.nlpcn.jcoder.util.*; import org.nlpcn.jcoder.util.dao.BasicDao; import org.nutz.castor.Castors; import org.nutz.dao.Cnd; import org.nutz.dao.Condition; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.mvc.annotation.Param; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import static org.nlpcn.jcoder.service.SharedSpaceService.GROUP_PATH; @IocBean public class TaskService { public static final String VERSION_SPLIT = "_"; private static final Logger LOG = LoggerFactory.getLogger(TaskService.class); private static final ConcurrentHashMap<Object, Task> TASK_MAP_CACHE = new ConcurrentHashMap<>(); /** * 记录task执行成功失败的计数器 */ private static final Map<String, AtomicLong> taskSuccess = new ConcurrentHashMap<>(); /** * 记录task执行成功失败的计数器 */ private static final Map<String, AtomicLong> taskErr = new ConcurrentHashMap<>(); private BasicDao basicDao = StaticValue.systemDao; public static synchronized Task findTaskByCache(Long id) { return TASK_MAP_CACHE.get(id); } public static synchronized Task findTaskByCache(String groupName, String name) { return TASK_MAP_CACHE.get(makeKey(groupName, name)); } public static synchronized Task findTaskByDB(Long id) { LOG.info("find task by db!"); return StaticValue.systemDao.findByCondition(Task.class, Cnd.where("id", "=", id)); } public static synchronized TaskHistory findTaskByDBHistory(Long taskId, String version) { LOG.info("find task by dbHistory!"); return StaticValue.systemDao.findByCondition(TaskHistory.class, Cnd.where("version", "=", version).and("taskId", "=", taskId)); } public static List<TaskHistory> findDBHistory() { return StaticValue.systemDao.search(TaskHistory.class, Cnd.NEW()); } /** * 根据类型查找task集合 */ public static synchronized Collection<Task> findTaskList(Integer type) { Collection<Task> values = TASK_MAP_CACHE.values(); if (type == null) { return values; } LinkedHashSet<Task> result = new LinkedHashSet<>(); for (Task task : values) { if (type.equals(task.getType())) { result.add(task); } } return result; } /** * 查找出缓存中的所有task * * @return */ public static List<Task> findAllTasksByCache() { return TASK_MAP_CACHE.entrySet().stream().filter(e -> e.getKey() instanceof Long).map(e -> e.getValue()).collect(Collectors.toList()); } /** * 查找出缓存中的所有task * * @return */ public static List<Task> findAllTasksByCache(String groupName) { return findAllTasksByCache().stream().filter(t -> groupName.equals(t.getGroupName())).collect(Collectors.toList()); } // 生成任务的版本号 private static String generateVersion(Task t) { StringBuilder sb = new StringBuilder(); sb.append(t.getUpdateUser()); sb.append(VERSION_SPLIT); sb.append(DateUtils.formatDate(t.getUpdateTime(), "yyyy-MM-dd HH:mm:ss")); return sb.toString(); } /** * 内部执行一个task 绕过请求,request为用户请求地址,只限于内部api使用 */ public static <T> T executeTask(String className, String methodName, Map<String, Object> params) throws ExecutionException { return executeTask(StaticValue.getCurrentGroup(), className, methodName, params); } /** * 内部执行一个task 绕过请求,request为用户请求地址,只限于内部api使用 */ public static <T> T executeTask(String groupName, String className, String methodName, Map<String, Object> params) throws ExecutionException { Task task = findTaskByCache(groupName, className); if (task == null) { if (TestingFilter.methods != null) { LOG.info("use testing method to run "); return executeTaskByTest(groupName, className, methodName, params); } throw new ApiException(ApiException.NotFound, methodName + " not found"); } task = new JavaRunner(task).compile().instance().getTask(); ExecuteMethod method = task.codeInfo().getExecuteMethod(methodName); if (method == null) { throw new ApiException(ApiException.NotFound, methodName + "/" + methodName + " not found"); } Object[] args = map2Args(params, method.getMethod()); return (T) StaticValue.MAPPING.getOrCreateByUrl(groupName, className, methodName).getChain().getInvokeProcessor().executeByCache(task, method.getMethod(), args); } /** * 通过test方式执行内部调用 */ public static <T> T executeTaskByArgs(String groupName, String className, String methodName, Object... params) throws ExecutionException { Task task = findTaskByCache(groupName, className); if (task == null) { if (TestingFilter.methods != null) { LOG.info("use testing method to run "); return executeTaskByArgsByTest(className, methodName, params); } throw new ApiException(ApiException.NotFound, methodName + " not found"); } task = new JavaRunner(task).compile().instance().getTask(); ExecuteMethod method = task.codeInfo().getExecuteMethod(methodName); if (method == null) { throw new ApiException(ApiException.NotFound, methodName + "/" + methodName + " not found"); } Object[] args = array2Args(method.getMethod(), params); return (T) StaticValue.MAPPING.getOrCreateByUrl(groupName, className, methodName).getChain().getInvokeProcessor().executeByCache(task, method.getMethod(), args); } private static <T> T executeTaskByArgsByTest(String className, String methodName, Object[] params) throws ApiException { KeyValue<Method, Object> kv = TestingFilter.methods.get(className + "/" + methodName); if (kv == null) { throw new ApiException(ApiException.NotFound, methodName + " not found"); } Object[] args = array2Args(kv.getKey(), params); try { return (T) kv.getKey().invoke(kv.getValue(), args); } catch (Exception e) { e.printStackTrace(); throw new ApiException(500, e.getMessage()); } } /** * 通过test方式执行内部调用 */ private static <T> T executeTaskByTest(String groupName, String className, String methodName, Map<String, Object> params) throws ApiException { KeyValue<Method, Object> kv = TestingFilter.methods.get(groupName + "/" + className + "/" + methodName); if (kv == null) { throw new ApiException(ApiException.NotFound, methodName + " not found"); } Object[] args = map2Args(params, kv.getKey()); try { return (T) kv.getKey().invoke(kv.getValue(), args); } catch (Exception e) { e.printStackTrace(); throw new ApiException(500, e.getMessage()); } } /** * 将map转换为参数 */ public static Object[] map2Args(Map<String, Object> params, Method method) { Parameter[] parameters = method.getParameters(); Object[] args = new Object[parameters.length]; for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; String name = parameter.getName(); if (!params.containsKey(name)) { Param annotation = parameter.getAnnotation(Param.class); if (annotation != null) { name = annotation.value(); } } args[i] = Castors.me().castTo(params.get(name), parameter.getType()); } return args; } /** * 将对象数组转换为参数 */ private static Object[] array2Args(Method method, Object... params) { Parameter[] parameters = method.getParameters(); Object[] args = new Object[parameters.length]; if (args.length != params.length) { throw new IllegalArgumentException("args.length " + args.length + " not equal params.length " + params.length); } for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; args[i] = Castors.me().castTo(params[i], parameter.getType()); } return args; } /** * 计数器,记录task成功失败个数 */ public static void counter(Task task, boolean success) { String groupTaskName = makeKey(task); if (success) { taskSuccess.compute(groupTaskName, (k, v) -> { if (v == null) { v = new AtomicLong(); } v.incrementAndGet(); return v; }); } else { taskErr.compute(groupTaskName, (k, v) -> { if (v == null) { v = new AtomicLong(); } v.incrementAndGet(); return v; }); } } /** * 获得一个task成功次数 */ public static long getSuccess(Task task) { AtomicLong atomicLong = taskSuccess.get(makeKey(task)); if (atomicLong == null) { return 0L; } else { return atomicLong.get(); } } /** * 获得一个task失败次数 */ public static long getError(Task task) { AtomicLong atomicLong = taskErr.get(makeKey(task)); if (atomicLong == null) { return 0L; } else { return atomicLong.get(); } } /** * 清空计数器 * * @param */ public static void clearSucessErr(Task task) { String groupTaskName = makeKey(task); taskErr.remove(groupTaskName); taskSuccess.remove(groupTaskName); } /** * 构建task_cache 的key groupName_taskName */ private static String makeKey(Task task) { return task.getGroupName() + "/" + task.getName(); } /** * 构建task_cache 的key groupName_taskName */ private static String makeKey(String groupName, String taskName) { return groupName + "/" + taskName; } /** * 根据分组名称获取所有Task * * @param groupName 组名 */ public List<Task> getTasksByGroupNameFromCluster(String groupName) throws Exception { CuratorFramework zk = StaticValue.space().getZk(); String path = GROUP_PATH + "/" + groupName; List<String> taskNames = zk.getChildren().forPath(path); List<Task> tasks = new ArrayList<>(taskNames.size()); Task t; for (String name : taskNames) { t = JSONObject.parseObject(zk.getData().forPath(path + "/" + name), Task.class); if (t != null && StringUtil.isNotBlank(t.getCode())) { tasks.add(t); } } return tasks; } /** * 根据分组名称获取所有Task * * @param groupName 组名 */ public Task getTaskFromCluster(String groupName, String taskName) { try { return StaticValue.space().getData(GROUP_PATH + "/" + groupName + "/" + taskName, Task.class); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 删除ZK集群里的Task * * @param groupName 组名 * @param taskName 任务名 */ public void deleteTaskFromCluster(String groupName, String taskName) throws Exception { String path = GROUP_PATH + "/" + groupName + "/" + taskName; LOG.info("to delete task in zookeeper: {}", path); if (!existsInCluster(groupName, taskName)) { LOG.warn("task[{}] not found in zookeeper", path); } else { StaticValue.space().getZk().delete().forPath(path); } } public boolean existsInCluster(String groupName, String taskName) throws Exception { return StaticValue.space().getZk().checkExists().forPath(GROUP_PATH + "/" + groupName + "/" + taskName) != null; } /** * 保存或者更新一个任务 */ public boolean saveOrUpdate(Task task) throws Exception { // 历史库版本保存 boolean isModify = checkTaskModify(task); String message = null; if ((validate(task)) != null) { throw new CodeException(message); } if (isModify) { String version = generateVersion(task); task.setVersion(version); } if (task.getId() == null) { task = basicDao.save(task); } else { basicDao.update(task); } if (isModify) { basicDao.save(new TaskHistory(task)); } flush(task.getId()); return isModify; } /** * 验证一个taskcode是否正确 */ public String validate(Task task) throws ParseException { String code = task.getCode(); String name = null; String pk = null; CompilationUnit compile = JavaDocUtil.compile(code); pk = compile.getPackage().getPackageName(); if (StringUtil.isBlank(pk)) { return ("package can not empty "); } List<TypeDeclaration> types = compile.getTypes(); for (TypeDeclaration type : types) { if (type.getModifiers() == Modifier.PUBLIC) { if (name != null) { return "class not have more than one public class "; } name = type.getName(); } } if (name == null) { return "not find className "; } return null; } /** * 判断task代码是否修改过 */ private boolean checkTaskModify(Task task) { Long id = task.getId(); if (id == null) { return true; } Task t = basicDao.find(id, Task.class); if (t == null) { return true; } if (!t.getCode().equals(task.getCode())) { return true; } return false; } /** * 刷新某个task */ public void flush(Long id) throws Exception { Task oldTask = TASK_MAP_CACHE.get(id); // 查找处新的task Task newTask = this.basicDao.find(id, Task.class); Task temp = new Task(); temp.setId(0L); temp.setName(""); if (oldTask == null) { oldTask = temp; } if (newTask == null) { newTask = temp; } synchronized (oldTask) { synchronized (newTask) { TASK_MAP_CACHE.remove(oldTask.getId()); TASK_MAP_CACHE.remove(makeKey(oldTask)); TASK_MAP_CACHE.put(newTask.getId(), newTask); TASK_MAP_CACHE.put(makeKey(newTask), newTask); clearSucessErr(oldTask); clearSucessErr(newTask); TaskRunManager.flush(oldTask, newTask); } } } /** * 删除一个任务 */ public void delete(Task task) throws Exception { task.setType(TaskType.RECYCLE.getValue()); task.setStatus(TaskStatus.STOP.getValue()); saveOrUpdate(task); } /** * 彻底删 <SUF>*/ public void delByDB(Task task) { // 删除任务历史 basicDao.delByCondition(TaskHistory.class, Cnd.where("taskId", "=", task.getId())); // 删除任务 basicDao.delById(task.getId(), Task.class); //删除缓存中的 TASK_MAP_CACHE.remove(task.getId()); TASK_MAP_CACHE.remove(makeKey(task)); } public Task findTask(String groupName, String name) { return basicDao.findByCondition(Task.class, Cnd.where("groupName", "=", groupName).and("name", "=", name)); } public List<Task> findTasksByGroupName(String groupName) { LOG.info("find findTasksByGroupName from groupName: {}", groupName); return basicDao.search(Task.class, Cnd.where("groupName", "=", groupName)); } /** * 找到task根据groupName */ public LinkedHashSet<Task> findTaskByGroupNameCache(String groupName) { Collection<Task> values = TASK_MAP_CACHE.values(); LinkedHashSet<Task> result = new LinkedHashSet<>(); for (Task task : values) { if (groupName.equals(task.getGroupName())) { result.add(task); } } return result; } /** * 从数据库中init所有的task */ public synchronized void flushGroup(String groupName) { removeMapping(groupName); //刪除所有映射 createMapping(groupName); //插入所有映射 } private void createMapping(String groupName) { List<Task> search = findTasksByGroupName(groupName); for (Task task : search) { try { TASK_MAP_CACHE.put(task.getId(), task); TASK_MAP_CACHE.put(makeKey(task), task); try { new JavaRunner(task).compile(); Collection<ExecuteMethod> executeMethods = task.codeInfo().getExecuteMethods(); executeMethods.forEach(e -> { StaticValue.space().addMapping(task.getGroupName(), task.getName(), e.getMethod().getName()); }); } catch (Exception e) { LOG.error("compile {}/{} err ", task.getGroupName(), task.getCode(), e); } } catch (Throwable e) { e.printStackTrace(); LOG.error(e.getMessage(), e); } } } private void removeMapping(String groupName) { //查询出缓存中的所有task并移除 List<Task> search = findAllTasksByCache(groupName); for (Task task : search) { try { task.codeInfo().getExecuteMethods().forEach(m -> { StaticValue.space().removeMapping(task.getGroupName(), task.getName(), m.getName()); }); StaticValue.MAPPING.remove(task.getGroupName(), task.getName());//删掉urlmapping重新加载 TASK_MAP_CACHE.remove(task.getId()); TASK_MAP_CACHE.remove(makeKey(task)); } catch (Throwable e) { e.printStackTrace(); LOG.error(e.getMessage(), e); } } } /** * @param taskId * @param size * @return */ public List<String> versions(Long taskId, int size) { List<String> list = new ArrayList<>(); Condition cnd = Cnd.where("taskId", "=", taskId).desc("id"); List<TaskHistory> tasks = basicDao.search(TaskHistory.class, cnd); for (TaskHistory taskHistory : tasks) { list.add(taskHistory.getVersion()); if (size-- == 0) { break; } } return list; } }
true
6633_12
package com.ansj.vec; import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import com.ansj.vec.domain.WordEntry; public class Word2VEC { public static void main(String[] args) throws IOException { // Learn learn = new Learn(); // learn.learnFile(new File("library/xh.txt")); // learn.saveModel(new File("library/javaSkip1")); Word2VEC vec = new Word2VEC(); vec.loadJavaModel("library/javaSkip1"); // System.out.println("中国" + "\t" + // Arrays.toString(vec.getWordVector("中国"))); // ; // System.out.println("毛泽东" + "\t" + // Arrays.toString(vec.getWordVector("毛泽东"))); // ; // System.out.println("足球" + "\t" + // Arrays.toString(vec.getWordVector("足球"))); // Word2VEC vec2 = new Word2VEC(); // vec2.loadGoogleModel("library/vectors.bin") ; // // String str = "毛泽东"; long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { System.out.println(vec.distance(str)); ; } System.out.println(System.currentTimeMillis() - start); System.out.println(System.currentTimeMillis() - start); // System.out.println(vec2.distance(str)); // // // //男人 国王 女人 // System.out.println(vec.analogy("邓小平", "毛泽东思想", "毛泽东")); // System.out.println(vec2.analogy("毛泽东", "毛泽东思想", "邓小平")); } private HashMap<String, float[]> wordMap = new HashMap<String, float[]>(); private int words; private int size; private int topNSize = 40; /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadGoogleModel(String path) throws IOException { DataInputStream dis = null; BufferedInputStream bis = null; double len = 0; float vector = 0; try { bis = new BufferedInputStream(new FileInputStream(path)); dis = new DataInputStream(bis); // //读取词数 words = Integer.parseInt(readString(dis)); // //大小 size = Integer.parseInt(readString(dis)); String word; float[] vectors = null; for (int i = 0; i < words; i++) { word = readString(dis); vectors = new float[size]; len = 0; for (int j = 0; j < size; j++) { vector = readFloat(dis); len += vector * vector; vectors[j] = (float) vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { vectors[j] /= len; } wordMap.put(word, vectors); dis.read(); } } finally { bis.close(); dis.close(); } } /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadJavaModel(String path) throws IOException { try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)))) { words = dis.readInt(); size = dis.readInt(); float vector = 0; String key = null; float[] value = null; for (int i = 0; i < words; i++) { double len = 0; key = dis.readUTF(); value = new float[size]; for (int j = 0; j < size; j++) { vector = dis.readFloat(); len += vector * vector; value[j] = vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { value[j] /= len; } wordMap.put(key, value); } } } private static final int MAX_SIZE = 50; /** * 近义词 * * @return */ public TreeSet<WordEntry> analogy(String word0, String word1, String word2) { float[] wv0 = getWordVector(word0); float[] wv1 = getWordVector(word1); float[] wv2 = getWordVector(word2); if (wv1 == null || wv2 == null || wv0 == null) { return null; } float[] wordVector = new float[size]; for (int i = 0; i < size; i++) { wordVector[i] = wv1[i] - wv0[i] + wv2[i]; } float[] tempVector; String name; List<WordEntry> wordEntrys = new ArrayList<WordEntry>(topNSize); for (Entry<String, float[]> entry : wordMap.entrySet()) { name = entry.getKey(); if (name.equals(word0) || name.equals(word1) || name.equals(word2)) { continue; } float dist = 0; tempVector = entry.getValue(); for (int i = 0; i < wordVector.length; i++) { dist += wordVector[i] * tempVector[i]; } insertTopN(name, dist, wordEntrys); } return new TreeSet<WordEntry>(wordEntrys); } private void insertTopN(String name, float score, List<WordEntry> wordsEntrys) { // TODO Auto-generated method stub if (wordsEntrys.size() < topNSize) { wordsEntrys.add(new WordEntry(name, score)); return; } float min = Float.MAX_VALUE; int minOffe = 0; for (int i = 0; i < topNSize; i++) { WordEntry wordEntry = wordsEntrys.get(i); if (min > wordEntry.score) { min = wordEntry.score; minOffe = i; } } if (score > min) { wordsEntrys.set(minOffe, new WordEntry(name, score)); } } public Set<WordEntry> distance(String queryWord) { float[] center = wordMap.get(queryWord); if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } public Set<WordEntry> distance(List<String> words) { float[] center = null; for (String word : words) { center = sum(center, wordMap.get(word)); } if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } private float[] sum(float[] center, float[] fs) { // TODO Auto-generated method stub if (center == null && fs == null) { return null; } if (fs == null) { return center; } if (center == null) { return fs; } for (int i = 0; i < fs.length; i++) { center[i] += fs[i]; } return center; } /** * 得到词向量 * * @param word * @return */ public float[] getWordVector(String word) { return wordMap.get(word); } public static float readFloat(InputStream is) throws IOException { byte[] bytes = new byte[4]; is.read(bytes); return getFloat(bytes); } /** * 读取一个float * * @param b * @return */ public static float getFloat(byte[] b) { int accum = 0; accum = accum | (b[0] & 0xff) << 0; accum = accum | (b[1] & 0xff) << 8; accum = accum | (b[2] & 0xff) << 16; accum = accum | (b[3] & 0xff) << 24; return Float.intBitsToFloat(accum); } /** * 读取一个字符串 * * @param dis * @return * @throws IOException */ private static String readString(DataInputStream dis) throws IOException { // TODO Auto-generated method stub byte[] bytes = new byte[MAX_SIZE]; byte b = dis.readByte(); int i = -1; StringBuilder sb = new StringBuilder(); while (b != 32 && b != 10) { i++; bytes[i] = b; b = dis.readByte(); if (i == 49) { sb.append(new String(bytes)); i = -1; bytes = new byte[MAX_SIZE]; } } sb.append(new String(bytes, 0, i + 1)); return sb.toString(); } public int getTopNSize() { return topNSize; } public void setTopNSize(int topNSize) { this.topNSize = topNSize; } public HashMap<String, float[]> getWordMap() { return wordMap; } public int getWords() { return words; } public int getSize() { return size; } }
NLPchina/Word2VEC_java
src/main/java/com/ansj/vec/Word2VEC.java
2,945
// //男人 国王 女人
line_comment
zh-cn
package com.ansj.vec; import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import com.ansj.vec.domain.WordEntry; public class Word2VEC { public static void main(String[] args) throws IOException { // Learn learn = new Learn(); // learn.learnFile(new File("library/xh.txt")); // learn.saveModel(new File("library/javaSkip1")); Word2VEC vec = new Word2VEC(); vec.loadJavaModel("library/javaSkip1"); // System.out.println("中国" + "\t" + // Arrays.toString(vec.getWordVector("中国"))); // ; // System.out.println("毛泽东" + "\t" + // Arrays.toString(vec.getWordVector("毛泽东"))); // ; // System.out.println("足球" + "\t" + // Arrays.toString(vec.getWordVector("足球"))); // Word2VEC vec2 = new Word2VEC(); // vec2.loadGoogleModel("library/vectors.bin") ; // // String str = "毛泽东"; long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { System.out.println(vec.distance(str)); ; } System.out.println(System.currentTimeMillis() - start); System.out.println(System.currentTimeMillis() - start); // System.out.println(vec2.distance(str)); // // // //男人 <SUF> // System.out.println(vec.analogy("邓小平", "毛泽东思想", "毛泽东")); // System.out.println(vec2.analogy("毛泽东", "毛泽东思想", "邓小平")); } private HashMap<String, float[]> wordMap = new HashMap<String, float[]>(); private int words; private int size; private int topNSize = 40; /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadGoogleModel(String path) throws IOException { DataInputStream dis = null; BufferedInputStream bis = null; double len = 0; float vector = 0; try { bis = new BufferedInputStream(new FileInputStream(path)); dis = new DataInputStream(bis); // //读取词数 words = Integer.parseInt(readString(dis)); // //大小 size = Integer.parseInt(readString(dis)); String word; float[] vectors = null; for (int i = 0; i < words; i++) { word = readString(dis); vectors = new float[size]; len = 0; for (int j = 0; j < size; j++) { vector = readFloat(dis); len += vector * vector; vectors[j] = (float) vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { vectors[j] /= len; } wordMap.put(word, vectors); dis.read(); } } finally { bis.close(); dis.close(); } } /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadJavaModel(String path) throws IOException { try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)))) { words = dis.readInt(); size = dis.readInt(); float vector = 0; String key = null; float[] value = null; for (int i = 0; i < words; i++) { double len = 0; key = dis.readUTF(); value = new float[size]; for (int j = 0; j < size; j++) { vector = dis.readFloat(); len += vector * vector; value[j] = vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { value[j] /= len; } wordMap.put(key, value); } } } private static final int MAX_SIZE = 50; /** * 近义词 * * @return */ public TreeSet<WordEntry> analogy(String word0, String word1, String word2) { float[] wv0 = getWordVector(word0); float[] wv1 = getWordVector(word1); float[] wv2 = getWordVector(word2); if (wv1 == null || wv2 == null || wv0 == null) { return null; } float[] wordVector = new float[size]; for (int i = 0; i < size; i++) { wordVector[i] = wv1[i] - wv0[i] + wv2[i]; } float[] tempVector; String name; List<WordEntry> wordEntrys = new ArrayList<WordEntry>(topNSize); for (Entry<String, float[]> entry : wordMap.entrySet()) { name = entry.getKey(); if (name.equals(word0) || name.equals(word1) || name.equals(word2)) { continue; } float dist = 0; tempVector = entry.getValue(); for (int i = 0; i < wordVector.length; i++) { dist += wordVector[i] * tempVector[i]; } insertTopN(name, dist, wordEntrys); } return new TreeSet<WordEntry>(wordEntrys); } private void insertTopN(String name, float score, List<WordEntry> wordsEntrys) { // TODO Auto-generated method stub if (wordsEntrys.size() < topNSize) { wordsEntrys.add(new WordEntry(name, score)); return; } float min = Float.MAX_VALUE; int minOffe = 0; for (int i = 0; i < topNSize; i++) { WordEntry wordEntry = wordsEntrys.get(i); if (min > wordEntry.score) { min = wordEntry.score; minOffe = i; } } if (score > min) { wordsEntrys.set(minOffe, new WordEntry(name, score)); } } public Set<WordEntry> distance(String queryWord) { float[] center = wordMap.get(queryWord); if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } public Set<WordEntry> distance(List<String> words) { float[] center = null; for (String word : words) { center = sum(center, wordMap.get(word)); } if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } private float[] sum(float[] center, float[] fs) { // TODO Auto-generated method stub if (center == null && fs == null) { return null; } if (fs == null) { return center; } if (center == null) { return fs; } for (int i = 0; i < fs.length; i++) { center[i] += fs[i]; } return center; } /** * 得到词向量 * * @param word * @return */ public float[] getWordVector(String word) { return wordMap.get(word); } public static float readFloat(InputStream is) throws IOException { byte[] bytes = new byte[4]; is.read(bytes); return getFloat(bytes); } /** * 读取一个float * * @param b * @return */ public static float getFloat(byte[] b) { int accum = 0; accum = accum | (b[0] & 0xff) << 0; accum = accum | (b[1] & 0xff) << 8; accum = accum | (b[2] & 0xff) << 16; accum = accum | (b[3] & 0xff) << 24; return Float.intBitsToFloat(accum); } /** * 读取一个字符串 * * @param dis * @return * @throws IOException */ private static String readString(DataInputStream dis) throws IOException { // TODO Auto-generated method stub byte[] bytes = new byte[MAX_SIZE]; byte b = dis.readByte(); int i = -1; StringBuilder sb = new StringBuilder(); while (b != 32 && b != 10) { i++; bytes[i] = b; b = dis.readByte(); if (i == 49) { sb.append(new String(bytes)); i = -1; bytes = new byte[MAX_SIZE]; } } sb.append(new String(bytes, 0, i + 1)); return sb.toString(); } public int getTopNSize() { return topNSize; } public void setTopNSize(int topNSize) { this.topNSize = topNSize; } public HashMap<String, float[]> getWordMap() { return wordMap; } public int getWords() { return words; } public int getSize() { return size; } }
false
43520_0
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import org.ansj.domain.Term; import org.ansj.splitWord.analysis.NlpAnalysis; import org.ansj.splitWord.analysis.ToAnalysis; import org.nlpcn.commons.lang.util.CollectionUtil; import org.nlpcn.commons.lang.util.IOUtil; import org.nlpcn.commons.lang.util.MapCount; import org.nlpcn.commons.lang.util.WordWeight; public class HotFinder { public static void main(String[] args) throws IOException { //用来寻找热点 WordWeight ww = new WordWeight(500000, 200000) ; String temp = null ; try(BufferedReader reader = IOUtil.getReader("test_data/fl.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "all"); } } } try(BufferedReader reader = IOUtil.getReader("test_data/corpus.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "sport"); } } } MapCount<String> mapCount = ww.exportChiSquare().get("sport") ; List<Entry<String, Double>> sortMapByValue = CollectionUtil.sortMapByValue(mapCount.get(), 2) ; int i = 0 ; for (Entry<String, Double> entry : sortMapByValue) { System.out.println(entry); if(i++>20){ break ; } } } }
NLPchina/ansj_fast_lda
src/HotFinder.java
523
//用来寻找热点
line_comment
zh-cn
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import org.ansj.domain.Term; import org.ansj.splitWord.analysis.NlpAnalysis; import org.ansj.splitWord.analysis.ToAnalysis; import org.nlpcn.commons.lang.util.CollectionUtil; import org.nlpcn.commons.lang.util.IOUtil; import org.nlpcn.commons.lang.util.MapCount; import org.nlpcn.commons.lang.util.WordWeight; public class HotFinder { public static void main(String[] args) throws IOException { //用来 <SUF> WordWeight ww = new WordWeight(500000, 200000) ; String temp = null ; try(BufferedReader reader = IOUtil.getReader("test_data/fl.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "all"); } } } try(BufferedReader reader = IOUtil.getReader("test_data/corpus.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "sport"); } } } MapCount<String> mapCount = ww.exportChiSquare().get("sport") ; List<Entry<String, Double>> sortMapByValue = CollectionUtil.sortMapByValue(mapCount.get(), 2) ; int i = 0 ; for (Entry<String, Double> entry : sortMapByValue) { System.out.println(entry); if(i++>20){ break ; } } } }
false
133_3
package org.ansj.util; import org.ansj.domain.AnsjItem; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.domain.TermNatures; import org.ansj.library.DATDictionary; import org.ansj.splitWord.Analysis.Merger; import org.ansj.util.TermUtil.InsertTermType; import org.nlpcn.commons.lang.util.WordAlert; import java.util.List; import java.util.Map; /** * 最短路径 * * @author ansj */ public class Graph { public char[] chars = null; public Term[] terms = null; protected Term end = null; protected Term root = null; protected static final String B = "BEGIN"; protected static final String E = "END"; // 是否有人名 public boolean hasPerson; public boolean hasNumQua; public String str ; // 是否需有歧异 public Graph(String str) { this.str = str ; this.chars = WordAlert.alertStr(str); terms = new Term[chars.length + 1]; end = new Term(E, chars.length, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[chars.length] = end; } public Graph(Result result) { Term last = result.get(result.size() - 1); int beginOff = result.get(0).getOffe(); int len = last.getOffe() - beginOff + last.getName().length(); terms = new Term[len + 1]; end = new Term(E, len, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[len] = end; for (Term term : result) { terms[term.getOffe() - beginOff] = term; } } /** * 构建最优路径 */ public List<Term> getResult(Merger merger) { return merger.merger(); } /** * 增加一个词语到图中 * * @param term */ public void addTerm(Term term) { // 是否有人名 if (!hasPerson && term.termNatures().personAttr.isActive()) { hasPerson = true; } if (!hasNumQua && term.termNatures().numAttr.isQua()) { hasNumQua = true; } TermUtil.insertTerm(terms, term, InsertTermType.REPLACE); } /** * 取得最优路径的root Term * * @return */ protected Term optimalRoot() { Term to = end; to.clearScore(); Term from = null; while ((from = to.from()) != null) { for (int i = from.getOffe() + 1; i < to.getOffe(); i++) { terms[i] = null; } if (from.getOffe() > -1) { terms[from.getOffe()] = from; } // 断开横向链表.节省内存 from.setNext(null); from.setTo(to); from.clearScore(); to = from; } return root; } /** * 删除最短的节点 */ public void rmLittlePath() { int maxTo = -1; Term temp = null; Term maxTerm = null; // 是否有交叉 boolean flag = false; final int length = terms.length - 1; for (int i = 0; i < length; i++) { maxTerm = getMaxTerm(i); if (maxTerm == null) { continue; } maxTo = maxTerm.toValue(); /** * 对字数进行优化.如果一个字.就跳过..两个字.且第二个为null则.也跳过.从第二个后开始 */ switch (maxTerm.getName().length()) { case 1: continue; case 2: if (terms[i + 1] == null) { i = i + 1; continue; } } /** * 判断是否有交叉 */ for (int j = i + 1; j < maxTo; j++) { temp = getMaxTerm(j); if (temp == null) { continue; } if (maxTo < temp.toValue()) { maxTo = temp.toValue(); flag = true; } } if (flag) { i = maxTo - 1; flag = false; } else { maxTerm.setNext(null); terms[i] = maxTerm; for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } } /** * 得道最到本行最大term,也就是最右面的term * * @param i * @return */ private Term getMaxTerm(int i) { Term maxTerm = terms[i]; if (maxTerm == null) { return null; } Term term = maxTerm; while ((term = term.next()) != null) { maxTerm = term; } return maxTerm; } /** * 删除无意义的节点,防止viterbi太多 */ public void rmLittleSinglePath() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } maxTo = terms[i].toValue(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp != null && temp.toValue() <= maxTo && temp.getName().length() == 1) { terms[j] = null; } } } } /** * 删除小节点。保证被删除的小节点的单个分数小于等于大节点的分数 */ public void rmLittlePathByScore() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } Term maxTerm = null; double maxScore = 0; Term term = terms[i]; // 找到自身分数对大最长的 do { if (maxTerm == null || maxScore > term.score()) { maxTerm = term; } else if (maxScore == term.score() && maxTerm.getName().length() < term.getName().length()) { maxTerm = term; } } while ((term = term.next()) != null); term = maxTerm; do { maxTo = term.toValue(); maxScore = term.score(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } boolean flag = true;// 可以删除 out: for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp == null) { continue; } do { if (temp.toValue() > maxTo || temp.score() < maxScore) { flag = false; break out; } } while ((temp = temp.next()) != null); } // 验证通过可以删除了 if (flag) { for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } while ((term = term.next()) != null); } } /** * 默认按照最大分数作为路径 */ public void walkPathByScore(){ walkPathByScore(true); } /** * 路径方式 * @param asc true 最大路径,false 最小路径 */ public void walkPathByScore(boolean asc) { Term term = null; // BEGIN先行打分 mergerByScore(root, 0, asc); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); mergerByScore(term, to, asc); term = term.next(); } } optimalRoot(); } public void walkPath() { walkPath(null); } /** * 干涉性增加相对权重 * * @param relationMap */ public void walkPath(Map<String, Double> relationMap) { Term term = null; // BEGIN先行打分 merger(root, 0, relationMap); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); merger(term, to, relationMap); term = term.next(); } } optimalRoot(); } /** * 具体的遍历打分方法 * * @param to */ private void merger(Term fromTerm, int to, Map<String, Double> relationMap) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathScore(fromTerm, relationMap); term = term.next(); } } else { char c = chars[to]; TermNatures tn = DATDictionary.getItem(c).termNatures; if (tn == null || tn == TermNatures.NULL) { tn = TermNatures.NULL; } terms[to] = new Term(String.valueOf(c), to, tn); terms[to].setPathScore(fromTerm, relationMap); } } /** * 根据分数 */ private void mergerByScore(Term fromTerm, int to, boolean asc) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathSelfScore(fromTerm, asc); term = term.next(); } } } /** * 对graph进行调试用的 */ public void printGraph() { for (Term term : terms) { if (term == null) { continue; } System.out.print(term.getName() + "\t" + term.score() + " ,"); while ((term = term.next()) != null) { System.out.print(term + "\t" + term.score() + " ,"); } System.out.println(); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/util/Graph.java
2,888
/** * 构建最优路径 */
block_comment
zh-cn
package org.ansj.util; import org.ansj.domain.AnsjItem; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.domain.TermNatures; import org.ansj.library.DATDictionary; import org.ansj.splitWord.Analysis.Merger; import org.ansj.util.TermUtil.InsertTermType; import org.nlpcn.commons.lang.util.WordAlert; import java.util.List; import java.util.Map; /** * 最短路径 * * @author ansj */ public class Graph { public char[] chars = null; public Term[] terms = null; protected Term end = null; protected Term root = null; protected static final String B = "BEGIN"; protected static final String E = "END"; // 是否有人名 public boolean hasPerson; public boolean hasNumQua; public String str ; // 是否需有歧异 public Graph(String str) { this.str = str ; this.chars = WordAlert.alertStr(str); terms = new Term[chars.length + 1]; end = new Term(E, chars.length, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[chars.length] = end; } public Graph(Result result) { Term last = result.get(result.size() - 1); int beginOff = result.get(0).getOffe(); int len = last.getOffe() - beginOff + last.getName().length(); terms = new Term[len + 1]; end = new Term(E, len, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[len] = end; for (Term term : result) { terms[term.getOffe() - beginOff] = term; } } /** * 构建最 <SUF>*/ public List<Term> getResult(Merger merger) { return merger.merger(); } /** * 增加一个词语到图中 * * @param term */ public void addTerm(Term term) { // 是否有人名 if (!hasPerson && term.termNatures().personAttr.isActive()) { hasPerson = true; } if (!hasNumQua && term.termNatures().numAttr.isQua()) { hasNumQua = true; } TermUtil.insertTerm(terms, term, InsertTermType.REPLACE); } /** * 取得最优路径的root Term * * @return */ protected Term optimalRoot() { Term to = end; to.clearScore(); Term from = null; while ((from = to.from()) != null) { for (int i = from.getOffe() + 1; i < to.getOffe(); i++) { terms[i] = null; } if (from.getOffe() > -1) { terms[from.getOffe()] = from; } // 断开横向链表.节省内存 from.setNext(null); from.setTo(to); from.clearScore(); to = from; } return root; } /** * 删除最短的节点 */ public void rmLittlePath() { int maxTo = -1; Term temp = null; Term maxTerm = null; // 是否有交叉 boolean flag = false; final int length = terms.length - 1; for (int i = 0; i < length; i++) { maxTerm = getMaxTerm(i); if (maxTerm == null) { continue; } maxTo = maxTerm.toValue(); /** * 对字数进行优化.如果一个字.就跳过..两个字.且第二个为null则.也跳过.从第二个后开始 */ switch (maxTerm.getName().length()) { case 1: continue; case 2: if (terms[i + 1] == null) { i = i + 1; continue; } } /** * 判断是否有交叉 */ for (int j = i + 1; j < maxTo; j++) { temp = getMaxTerm(j); if (temp == null) { continue; } if (maxTo < temp.toValue()) { maxTo = temp.toValue(); flag = true; } } if (flag) { i = maxTo - 1; flag = false; } else { maxTerm.setNext(null); terms[i] = maxTerm; for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } } /** * 得道最到本行最大term,也就是最右面的term * * @param i * @return */ private Term getMaxTerm(int i) { Term maxTerm = terms[i]; if (maxTerm == null) { return null; } Term term = maxTerm; while ((term = term.next()) != null) { maxTerm = term; } return maxTerm; } /** * 删除无意义的节点,防止viterbi太多 */ public void rmLittleSinglePath() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } maxTo = terms[i].toValue(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp != null && temp.toValue() <= maxTo && temp.getName().length() == 1) { terms[j] = null; } } } } /** * 删除小节点。保证被删除的小节点的单个分数小于等于大节点的分数 */ public void rmLittlePathByScore() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } Term maxTerm = null; double maxScore = 0; Term term = terms[i]; // 找到自身分数对大最长的 do { if (maxTerm == null || maxScore > term.score()) { maxTerm = term; } else if (maxScore == term.score() && maxTerm.getName().length() < term.getName().length()) { maxTerm = term; } } while ((term = term.next()) != null); term = maxTerm; do { maxTo = term.toValue(); maxScore = term.score(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } boolean flag = true;// 可以删除 out: for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp == null) { continue; } do { if (temp.toValue() > maxTo || temp.score() < maxScore) { flag = false; break out; } } while ((temp = temp.next()) != null); } // 验证通过可以删除了 if (flag) { for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } while ((term = term.next()) != null); } } /** * 默认按照最大分数作为路径 */ public void walkPathByScore(){ walkPathByScore(true); } /** * 路径方式 * @param asc true 最大路径,false 最小路径 */ public void walkPathByScore(boolean asc) { Term term = null; // BEGIN先行打分 mergerByScore(root, 0, asc); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); mergerByScore(term, to, asc); term = term.next(); } } optimalRoot(); } public void walkPath() { walkPath(null); } /** * 干涉性增加相对权重 * * @param relationMap */ public void walkPath(Map<String, Double> relationMap) { Term term = null; // BEGIN先行打分 merger(root, 0, relationMap); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); merger(term, to, relationMap); term = term.next(); } } optimalRoot(); } /** * 具体的遍历打分方法 * * @param to */ private void merger(Term fromTerm, int to, Map<String, Double> relationMap) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathScore(fromTerm, relationMap); term = term.next(); } } else { char c = chars[to]; TermNatures tn = DATDictionary.getItem(c).termNatures; if (tn == null || tn == TermNatures.NULL) { tn = TermNatures.NULL; } terms[to] = new Term(String.valueOf(c), to, tn); terms[to].setPathScore(fromTerm, relationMap); } } /** * 根据分数 */ private void mergerByScore(Term fromTerm, int to, boolean asc) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathSelfScore(fromTerm, asc); term = term.next(); } } } /** * 对graph进行调试用的 */ public void printGraph() { for (Term term : terms) { if (term == null) { continue; } System.out.print(term.getName() + "\t" + term.score() + " ,"); while ((term = term.next()) != null) { System.out.print(term + "\t" + term.score() + " ,"); } System.out.println(); } } }
false
6949_12
package org.nlpcn.es4sql.parse; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.google.common.base.Joiner; import org.nlpcn.es4sql.Util; import org.nlpcn.es4sql.domain.Condition; import org.nlpcn.es4sql.domain.Condition.OPEAR; import org.nlpcn.es4sql.domain.Where; import org.nlpcn.es4sql.exception.SqlParseException; import java.util.ArrayList; import java.util.List; /** * Created by allwefantasy on 9/3/16. */ public class CaseWhenParser { private SQLCaseExpr caseExpr; //zhongshu-comment 以下这两个属性貌似没有被使用 private String alias; private String tableAlias; public CaseWhenParser(SQLCaseExpr caseExpr, String alias, String tableAlias) { this.alias = alias; this.tableAlias = tableAlias; this.caseExpr = caseExpr; } public String parse() throws SqlParseException { List<String> result = new ArrayList<String>(); for (SQLCaseExpr.Item item : caseExpr.getItems()) { SQLExpr conditionExpr = item.getConditionExpr(); WhereParser parser = new WhereParser(new SqlParser(), conditionExpr); /* zhongshu-comment 将case when的各种条件判断转换为script的if-else判断,举例如下 case when: CASE WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' ELSE os script的if-else: 将上文case when例子中的WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' 解析成如下的script: (doc['platform_id'].value=='PC') && (doc['os'].value != '全部' ) */ String scriptCode = explain(parser.findWhere()); if (scriptCode.startsWith(" &&")) { scriptCode = scriptCode.substring(3); } if (result.size() == 0) { result.add("if(" + scriptCode + ")" + "{" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } else { result.add("else if(" + scriptCode + ")" + "{" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } } SQLExpr elseExpr = caseExpr.getElseExpr(); if (elseExpr == null) { result.add("else { null }"); } else { result.add("else {" + Util.getScriptValueWithQuote(elseExpr, "'") + "}"); } return Joiner.on(" ").join(result); } /** * zhongshu-comment * 1、该方法的作用:将在where子句中的case when解析为es script * 2、该种情况的es script和select、group by、order by等子句中的case when的es script不一样, * 因为在where子句中script的返回值是布尔类型,所以script中需要有个布尔判断, * 而其他情况的script返回值就是转换后的值,该值一般是字符串、数值 * @author zhongshu * @return * @throws SqlParseException */ public String parseCaseWhenInWhere(Object[] valueArr) throws SqlParseException { List<String> result = new ArrayList<String>(); String TMP = "tmp"; result.add("String " + TMP + " = '';"); for (SQLCaseExpr.Item item : caseExpr.getItems()) { SQLExpr conditionExpr = item.getConditionExpr(); WhereParser parser = new WhereParser(new SqlParser(), conditionExpr); String scriptCode = explain(parser.findWhere()); if (scriptCode.startsWith(" &&")) { scriptCode = scriptCode.substring(3); } if (result.size() == 1) { //zhongshu-comment 在for循环之前就已经先add了一个元素 result.add("if(" + scriptCode + ")" + "{" + TMP + "=" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } else { result.add("else if(" + scriptCode + ")" + "{" + TMP + "=" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } } SQLExpr elseExpr = caseExpr.getElseExpr(); if (elseExpr == null) { result.add("else { null }"); } else { result.add("else {" + TMP + "=" + Util.getScriptValueWithQuote(elseExpr, "'") + "}"); } /* zhongshu-comment 1、第一种情况in field in (a, b, c) --> field == a || field == b || field == c 2、第二种情况not in field not in (a, b, c) --> field != a && field != b && field != c 等价于 --> !(field == a || field == b || field == c) 即对第一种情况取反, (field == a || field == b || field == c)里的a、b、c要全部为false,!(field == a || field == b || field == c)才为true 3、这里只拼接第一种情况,不拼接第一种情况, 如果要需要第二种情况,那就调用该方法得到返回值后自行拼上取反符号和括号: !(${该方法的返回值}) */ String judgeStatement = parseInNotInJudge(valueArr, TMP, "==", "||", true); result.add("return " + judgeStatement + ";"); return Joiner.on(" ").join(result); } /** * zhongshu-comment 这个方法应该设为private比较合适,因为只在上文的parse()方法中被调用了 * zhongshu-comment 将case when的各种条件判断转换为script的if-else判断,举例如下 case when: CASE WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' ELSE os script的if-else: 将上文case when例子中的WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' 解析成如下的script: (doc['platform_id'].value=='PC') && (doc['os'].value != '全部' ) * @param where * @return * @throws SqlParseException */ public String explain(Where where) throws SqlParseException { List<String> codes = new ArrayList<String>(); while (where.getWheres().size() == 1) { where = where.getWheres().getFirst(); } explainWhere(codes, where); String relation = where.getConn().name().equals("AND") ? " && " : " || "; return Joiner.on(relation).join(codes); } private void explainWhere(List<String> codes, Where where) throws SqlParseException { if (where instanceof Condition) { Condition condition = (Condition) where; if (condition.getValue() instanceof ScriptFilter) { codes.add(String.format("Function.identity().compose((o)->{%s}).apply(null)", ((ScriptFilter) condition.getValue()).getScript())); } else if (condition.getOpear() == OPEAR.BETWEEN) { Object[] objs = (Object[]) condition.getValue(); codes.add("(" + "doc['" + condition.getName() + "'].value >= " + objs[0] + " && doc['" + condition.getName() + "'].value <=" + objs[1] + ")"); } else if (condition.getOpear() == OPEAR.IN) {// in //zhongshu-comment 增加该分支,可以解析case when判断语句中的in、not in判断语句 codes.add(parseInNotInJudge(condition, "==", "||", false)); } else if (condition.getOpear() == OPEAR.NIN) { // not in codes.add(parseInNotInJudge(condition, "!=", "&&", false)); } else { SQLExpr nameExpr = condition.getNameExpr(); SQLExpr valueExpr = condition.getValueExpr(); if(valueExpr instanceof SQLNullExpr) { //zhongshu-comment 空值查询的意思吗?例如:查a字段没有值的那些文档,是这个意思吗 codes.add("(" + "doc['" + nameExpr.toString() + "']" + ".empty)"); } else { //zhongshu-comment 该分支示例:(doc['c'].value==1) codes.add("(" + Util.getScriptValueWithQuote(nameExpr, "'") + condition.getOpertatorSymbol() + Util.getScriptValueWithQuote(valueExpr, "'") + ")"); } } } else { for (Where subWhere : where.getWheres()) { List<String> subCodes = new ArrayList<String>(); explainWhere(subCodes, subWhere); String relation = subWhere.getConn().name().equals("AND") ? "&&" : "||"; codes.add(Joiner.on(relation).join(subCodes)); } } } /** * @author zhongshu * @param condition * @param judgeOperator * @param booleanOperator * @throws SqlParseException */ private String parseInNotInJudge(Condition condition, String judgeOperator, String booleanOperator, boolean flag) throws SqlParseException { Object[] objArr = (Object[]) condition.getValue(); if (objArr.length == 0) throw new SqlParseException("you should assign some value in bracket!!"); String script = "("; String template = "doc['" + condition.getName() + "'].value " + judgeOperator + " %s " + booleanOperator + " "; //结尾这个空格就只空一格 if (flag) { template = condition.getName() + " " + judgeOperator + " %s " + booleanOperator + " "; //结尾这个空格就只空一格; } for (Object obj : objArr) { script = script + String.format(template, parseInNotInValueWithQuote(obj)); } script = script.substring(0, script.lastIndexOf(booleanOperator));//去掉末尾的&& script += ")"; //zhongshu-comment script结果示例 (doc['a'].value == 1 && doc['a'].value == 2 && doc['a'].value == 3 ) return script; } private String parseInNotInJudge(Object value, String fieldName, String judgeOperator, String booleanOperator, boolean flag) throws SqlParseException { Condition cond = new Condition(null); cond.setValue(value); cond.setName(fieldName); return parseInNotInJudge(cond, judgeOperator, booleanOperator, flag); } /** * @author zhongshu * @param obj * @return */ private Object parseInNotInValueWithQuote(Object obj) { //zhongshu-comment 因为我们的表就只有String 和 double两种类型,所以就只判断了这两种情况 if (obj instanceof String) { return "'" + obj + "'"; } else { return obj; } } }
NLPchina/elasticsearch-sql
src/main/java/org/nlpcn/es4sql/parse/CaseWhenParser.java
2,631
//结尾这个空格就只空一格
line_comment
zh-cn
package org.nlpcn.es4sql.parse; import com.alibaba.druid.sql.ast.SQLExpr; import com.alibaba.druid.sql.ast.expr.SQLCaseExpr; import com.alibaba.druid.sql.ast.expr.SQLNullExpr; import com.google.common.base.Joiner; import org.nlpcn.es4sql.Util; import org.nlpcn.es4sql.domain.Condition; import org.nlpcn.es4sql.domain.Condition.OPEAR; import org.nlpcn.es4sql.domain.Where; import org.nlpcn.es4sql.exception.SqlParseException; import java.util.ArrayList; import java.util.List; /** * Created by allwefantasy on 9/3/16. */ public class CaseWhenParser { private SQLCaseExpr caseExpr; //zhongshu-comment 以下这两个属性貌似没有被使用 private String alias; private String tableAlias; public CaseWhenParser(SQLCaseExpr caseExpr, String alias, String tableAlias) { this.alias = alias; this.tableAlias = tableAlias; this.caseExpr = caseExpr; } public String parse() throws SqlParseException { List<String> result = new ArrayList<String>(); for (SQLCaseExpr.Item item : caseExpr.getItems()) { SQLExpr conditionExpr = item.getConditionExpr(); WhereParser parser = new WhereParser(new SqlParser(), conditionExpr); /* zhongshu-comment 将case when的各种条件判断转换为script的if-else判断,举例如下 case when: CASE WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' ELSE os script的if-else: 将上文case when例子中的WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' 解析成如下的script: (doc['platform_id'].value=='PC') && (doc['os'].value != '全部' ) */ String scriptCode = explain(parser.findWhere()); if (scriptCode.startsWith(" &&")) { scriptCode = scriptCode.substring(3); } if (result.size() == 0) { result.add("if(" + scriptCode + ")" + "{" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } else { result.add("else if(" + scriptCode + ")" + "{" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } } SQLExpr elseExpr = caseExpr.getElseExpr(); if (elseExpr == null) { result.add("else { null }"); } else { result.add("else {" + Util.getScriptValueWithQuote(elseExpr, "'") + "}"); } return Joiner.on(" ").join(result); } /** * zhongshu-comment * 1、该方法的作用:将在where子句中的case when解析为es script * 2、该种情况的es script和select、group by、order by等子句中的case when的es script不一样, * 因为在where子句中script的返回值是布尔类型,所以script中需要有个布尔判断, * 而其他情况的script返回值就是转换后的值,该值一般是字符串、数值 * @author zhongshu * @return * @throws SqlParseException */ public String parseCaseWhenInWhere(Object[] valueArr) throws SqlParseException { List<String> result = new ArrayList<String>(); String TMP = "tmp"; result.add("String " + TMP + " = '';"); for (SQLCaseExpr.Item item : caseExpr.getItems()) { SQLExpr conditionExpr = item.getConditionExpr(); WhereParser parser = new WhereParser(new SqlParser(), conditionExpr); String scriptCode = explain(parser.findWhere()); if (scriptCode.startsWith(" &&")) { scriptCode = scriptCode.substring(3); } if (result.size() == 1) { //zhongshu-comment 在for循环之前就已经先add了一个元素 result.add("if(" + scriptCode + ")" + "{" + TMP + "=" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } else { result.add("else if(" + scriptCode + ")" + "{" + TMP + "=" + Util.getScriptValueWithQuote(item.getValueExpr(), "'") + "}"); } } SQLExpr elseExpr = caseExpr.getElseExpr(); if (elseExpr == null) { result.add("else { null }"); } else { result.add("else {" + TMP + "=" + Util.getScriptValueWithQuote(elseExpr, "'") + "}"); } /* zhongshu-comment 1、第一种情况in field in (a, b, c) --> field == a || field == b || field == c 2、第二种情况not in field not in (a, b, c) --> field != a && field != b && field != c 等价于 --> !(field == a || field == b || field == c) 即对第一种情况取反, (field == a || field == b || field == c)里的a、b、c要全部为false,!(field == a || field == b || field == c)才为true 3、这里只拼接第一种情况,不拼接第一种情况, 如果要需要第二种情况,那就调用该方法得到返回值后自行拼上取反符号和括号: !(${该方法的返回值}) */ String judgeStatement = parseInNotInJudge(valueArr, TMP, "==", "||", true); result.add("return " + judgeStatement + ";"); return Joiner.on(" ").join(result); } /** * zhongshu-comment 这个方法应该设为private比较合适,因为只在上文的parse()方法中被调用了 * zhongshu-comment 将case when的各种条件判断转换为script的if-else判断,举例如下 case when: CASE WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' ELSE os script的if-else: 将上文case when例子中的WHEN platform_id = 'PC' AND os NOT IN ('全部') THEN 'unknown' 解析成如下的script: (doc['platform_id'].value=='PC') && (doc['os'].value != '全部' ) * @param where * @return * @throws SqlParseException */ public String explain(Where where) throws SqlParseException { List<String> codes = new ArrayList<String>(); while (where.getWheres().size() == 1) { where = where.getWheres().getFirst(); } explainWhere(codes, where); String relation = where.getConn().name().equals("AND") ? " && " : " || "; return Joiner.on(relation).join(codes); } private void explainWhere(List<String> codes, Where where) throws SqlParseException { if (where instanceof Condition) { Condition condition = (Condition) where; if (condition.getValue() instanceof ScriptFilter) { codes.add(String.format("Function.identity().compose((o)->{%s}).apply(null)", ((ScriptFilter) condition.getValue()).getScript())); } else if (condition.getOpear() == OPEAR.BETWEEN) { Object[] objs = (Object[]) condition.getValue(); codes.add("(" + "doc['" + condition.getName() + "'].value >= " + objs[0] + " && doc['" + condition.getName() + "'].value <=" + objs[1] + ")"); } else if (condition.getOpear() == OPEAR.IN) {// in //zhongshu-comment 增加该分支,可以解析case when判断语句中的in、not in判断语句 codes.add(parseInNotInJudge(condition, "==", "||", false)); } else if (condition.getOpear() == OPEAR.NIN) { // not in codes.add(parseInNotInJudge(condition, "!=", "&&", false)); } else { SQLExpr nameExpr = condition.getNameExpr(); SQLExpr valueExpr = condition.getValueExpr(); if(valueExpr instanceof SQLNullExpr) { //zhongshu-comment 空值查询的意思吗?例如:查a字段没有值的那些文档,是这个意思吗 codes.add("(" + "doc['" + nameExpr.toString() + "']" + ".empty)"); } else { //zhongshu-comment 该分支示例:(doc['c'].value==1) codes.add("(" + Util.getScriptValueWithQuote(nameExpr, "'") + condition.getOpertatorSymbol() + Util.getScriptValueWithQuote(valueExpr, "'") + ")"); } } } else { for (Where subWhere : where.getWheres()) { List<String> subCodes = new ArrayList<String>(); explainWhere(subCodes, subWhere); String relation = subWhere.getConn().name().equals("AND") ? "&&" : "||"; codes.add(Joiner.on(relation).join(subCodes)); } } } /** * @author zhongshu * @param condition * @param judgeOperator * @param booleanOperator * @throws SqlParseException */ private String parseInNotInJudge(Condition condition, String judgeOperator, String booleanOperator, boolean flag) throws SqlParseException { Object[] objArr = (Object[]) condition.getValue(); if (objArr.length == 0) throw new SqlParseException("you should assign some value in bracket!!"); String script = "("; String template = "doc['" + condition.getName() + "'].value " + judgeOperator + " %s " + booleanOperator + " "; //结尾 <SUF> if (flag) { template = condition.getName() + " " + judgeOperator + " %s " + booleanOperator + " "; //结尾这个空格就只空一格; } for (Object obj : objArr) { script = script + String.format(template, parseInNotInValueWithQuote(obj)); } script = script.substring(0, script.lastIndexOf(booleanOperator));//去掉末尾的&& script += ")"; //zhongshu-comment script结果示例 (doc['a'].value == 1 && doc['a'].value == 2 && doc['a'].value == 3 ) return script; } private String parseInNotInJudge(Object value, String fieldName, String judgeOperator, String booleanOperator, boolean flag) throws SqlParseException { Condition cond = new Condition(null); cond.setValue(value); cond.setName(fieldName); return parseInNotInJudge(cond, judgeOperator, booleanOperator, flag); } /** * @author zhongshu * @param obj * @return */ private Object parseInNotInValueWithQuote(Object obj) { //zhongshu-comment 因为我们的表就只有String 和 double两种类型,所以就只判断了这两种情况 if (obj instanceof String) { return "'" + obj + "'"; } else { return obj; } } }
true
36953_5
package org.nlpchina.web.controller; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.ansj.app.keyword.KeyWordComputer; import org.ansj.app.keyword.Keyword; import org.ansj.app.summary.SummaryComputer; import org.ansj.app.summary.TagContent; import org.ansj.app.summary.pojo.Summary; import org.ansj.domain.Term; import org.ansj.splitWord.analysis.BaseAnalysis; import org.ansj.splitWord.analysis.IndexAnalysis; import org.ansj.splitWord.analysis.NlpAnalysis; import org.ansj.splitWord.analysis.ToAnalysis; import org.nlpchina.web.service.StanfordParserService; import org.nlpcn.commons.lang.jianfan.JianFan; import org.nlpcn.commons.lang.pinyin.Pinyin; import org.nlpcn.commons.lang.util.StringUtil; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.google.common.collect.Lists; @IocBean public class InfcnDemoAction { private static final String DEFAULT_CONTENT = "码完代码,他起身关上电脑,用滚烫的开水为自己泡制一碗腾着热气的老坛酸菜面。中国的程序员更偏爱拉上窗帘,在黑暗中享受这独特的美食。这是现代工业给一天辛苦劳作的人最好的馈赠。南方一带生长的程序员虽然在京城多年,但仍口味清淡,他们往往不加料包,由脸颊自然淌下的热泪补充恰当的盐分。他们相信,用这种方式,能够抹平思考着现在是不是过去想要的未来而带来的大部分忧伤…小李的父亲在年轻的时候也是从爷爷手里接收了祖传的代码,不过令人惊讶的是,到了小李这一代,很多东西都遗失了,但是程序员苦逼的味道保存的是如此的完整。 就在24小时之前,最新的需求从PM处传来,为了得到这份自然的馈赠,码农们开机、写码、调试、重构,四季轮回的等待换来这难得的丰收时刻。码农知道,需求的保鲜期只有短短的两天,码农们要以最快的速度对代码进行精致的加工,任何一个需求都可能在24小时之后失去原本的活力,变成一文不值的垃圾创意。"; @At("/infcn/demo/") @Ok("jsp:/infcn_demo.jsp") public void demo(@Param("content") String content, HttpServletRequest request) { if (StringUtil.isBlank(content)) { content = DEFAULT_CONTENT; } // nlp分词 List<String[]> nlpResult = nameAndNature(NlpAnalysis.parse(content)); // nlp-min分词 List<String[]> nlpMinResult = minNameAndNature(NlpAnalysis.parse(content)); // to分词 List<String[]> toResult = nameAndNature(ToAnalysis.parse(content)); // basic分词 List<String[]> minResult = nameAndNature(BaseAnalysis.parse(content)); // index分词 List<String[]> indexResult = nameAndNature(IndexAnalysis.parse(content)); // 关键词提取 KeyWordComputer keyWordComputer = new KeyWordComputer(30); Collection<Keyword> keyWords = keyWordComputer.computeArticleTfidf(content); // 文档摘要 SummaryComputer sc = new SummaryComputer(null, content); Summary summary = sc.toSummary(); String summaryStr = new TagContent("<font color=\"red\">", "</font>").tagContent(summary) + "...."; request.setAttribute("fanStr", JianFan.j2F(content)); request.setAttribute("jianStr", JianFan.f2J(content)); request.setAttribute("pinStr", Pinyin.pinyinStr(content)); request.setAttribute("nlpResult", nlpResult); request.setAttribute("nlpMinResult", nlpMinResult); request.setAttribute("toResult", toResult); request.setAttribute("minResult", minResult); request.setAttribute("indexResult", indexResult); request.setAttribute("keyWords", keyWords); request.setAttribute("summaryStr", summaryStr); request.setAttribute("content", content); } @At("/syntactic/") @Ok("jsp:/syntactic/home.jsp") public String syntactic(@Param("content") String content) { return StanfordParserService.parse(content); } private List<String[]> nameAndNature(List<Term> parse) { List<String[]> result = Lists.newArrayList(); for (Term term : parse) { if (StringUtil.isNotBlank(term.getName())) { result.add(new String[] { term.getName(), term.getNatureStr() }); } } return result; } private List<String[]> minNameAndNature(List<Term> parse) { List<String[]> result = Lists.newArrayList(); for (Term term : parse) { if (StringUtil.isNotBlank(term.getName())) { result.add(new String[] { term.getSubTerm() == null ? term.getName() : term.getSubTerm().toString(), term.getNatureStr() }); } } return result; } public static void main(String[] args) { System.out.println(ToAnalysis.parse("1987.08")); } }
NLPchina/nlp_china_web
src/main/java/org/nlpchina/web/controller/InfcnDemoAction.java
1,483
// 关键词提取
line_comment
zh-cn
package org.nlpchina.web.controller; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.ansj.app.keyword.KeyWordComputer; import org.ansj.app.keyword.Keyword; import org.ansj.app.summary.SummaryComputer; import org.ansj.app.summary.TagContent; import org.ansj.app.summary.pojo.Summary; import org.ansj.domain.Term; import org.ansj.splitWord.analysis.BaseAnalysis; import org.ansj.splitWord.analysis.IndexAnalysis; import org.ansj.splitWord.analysis.NlpAnalysis; import org.ansj.splitWord.analysis.ToAnalysis; import org.nlpchina.web.service.StanfordParserService; import org.nlpcn.commons.lang.jianfan.JianFan; import org.nlpcn.commons.lang.pinyin.Pinyin; import org.nlpcn.commons.lang.util.StringUtil; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.google.common.collect.Lists; @IocBean public class InfcnDemoAction { private static final String DEFAULT_CONTENT = "码完代码,他起身关上电脑,用滚烫的开水为自己泡制一碗腾着热气的老坛酸菜面。中国的程序员更偏爱拉上窗帘,在黑暗中享受这独特的美食。这是现代工业给一天辛苦劳作的人最好的馈赠。南方一带生长的程序员虽然在京城多年,但仍口味清淡,他们往往不加料包,由脸颊自然淌下的热泪补充恰当的盐分。他们相信,用这种方式,能够抹平思考着现在是不是过去想要的未来而带来的大部分忧伤…小李的父亲在年轻的时候也是从爷爷手里接收了祖传的代码,不过令人惊讶的是,到了小李这一代,很多东西都遗失了,但是程序员苦逼的味道保存的是如此的完整。 就在24小时之前,最新的需求从PM处传来,为了得到这份自然的馈赠,码农们开机、写码、调试、重构,四季轮回的等待换来这难得的丰收时刻。码农知道,需求的保鲜期只有短短的两天,码农们要以最快的速度对代码进行精致的加工,任何一个需求都可能在24小时之后失去原本的活力,变成一文不值的垃圾创意。"; @At("/infcn/demo/") @Ok("jsp:/infcn_demo.jsp") public void demo(@Param("content") String content, HttpServletRequest request) { if (StringUtil.isBlank(content)) { content = DEFAULT_CONTENT; } // nlp分词 List<String[]> nlpResult = nameAndNature(NlpAnalysis.parse(content)); // nlp-min分词 List<String[]> nlpMinResult = minNameAndNature(NlpAnalysis.parse(content)); // to分词 List<String[]> toResult = nameAndNature(ToAnalysis.parse(content)); // basic分词 List<String[]> minResult = nameAndNature(BaseAnalysis.parse(content)); // index分词 List<String[]> indexResult = nameAndNature(IndexAnalysis.parse(content)); // 关键 <SUF> KeyWordComputer keyWordComputer = new KeyWordComputer(30); Collection<Keyword> keyWords = keyWordComputer.computeArticleTfidf(content); // 文档摘要 SummaryComputer sc = new SummaryComputer(null, content); Summary summary = sc.toSummary(); String summaryStr = new TagContent("<font color=\"red\">", "</font>").tagContent(summary) + "...."; request.setAttribute("fanStr", JianFan.j2F(content)); request.setAttribute("jianStr", JianFan.f2J(content)); request.setAttribute("pinStr", Pinyin.pinyinStr(content)); request.setAttribute("nlpResult", nlpResult); request.setAttribute("nlpMinResult", nlpMinResult); request.setAttribute("toResult", toResult); request.setAttribute("minResult", minResult); request.setAttribute("indexResult", indexResult); request.setAttribute("keyWords", keyWords); request.setAttribute("summaryStr", summaryStr); request.setAttribute("content", content); } @At("/syntactic/") @Ok("jsp:/syntactic/home.jsp") public String syntactic(@Param("content") String content) { return StanfordParserService.parse(content); } private List<String[]> nameAndNature(List<Term> parse) { List<String[]> result = Lists.newArrayList(); for (Term term : parse) { if (StringUtil.isNotBlank(term.getName())) { result.add(new String[] { term.getName(), term.getNatureStr() }); } } return result; } private List<String[]> minNameAndNature(List<Term> parse) { List<String[]> result = Lists.newArrayList(); for (Term term : parse) { if (StringUtil.isNotBlank(term.getName())) { result.add(new String[] { term.getSubTerm() == null ? term.getName() : term.getSubTerm().toString(), term.getNatureStr() }); } } return result; } public static void main(String[] args) { System.out.println(ToAnalysis.parse("1987.08")); } }
true
37226_4
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Lib { /** * * @param input 文法 */ public static Map<String, Set<Character>> getFirst(Map<String, String> input) { Map<String, Set<Character>> res = new HashMap<>(); input.forEach((k, v) -> { Set<Character> set = res.get(k); if (set == null) getCharFirst(input, res, k); }); return res; } private static Set<Character> getCharFirst(Map<String, String> input, Map<String, Set<Character>> res, String k) { Set<Character> set = new HashSet<>(); // 寻找First(k) String v = input.get(k); String[] vs = v.split("\\|"); for (String s : vs) { char first = s.charAt(0); if (first == 'ε' || !Character.isUpperCase(first)) { // 空 | 终结符 set.add(first); } else { // 非终结符 String nextK = String.valueOf(s.charAt(0)); if (s.length() > 1 && s.charAt(1) == '\'') { nextK += '\''; } set.addAll(getCharFirst(input, res, nextK)); } } // 寻找完毕,加入结果集中 res.put(k, set); return set; } }
NOS-AE/grammerAnalyzer
src/Lib.java
371
// 寻找完毕,加入结果集中
line_comment
zh-cn
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Lib { /** * * @param input 文法 */ public static Map<String, Set<Character>> getFirst(Map<String, String> input) { Map<String, Set<Character>> res = new HashMap<>(); input.forEach((k, v) -> { Set<Character> set = res.get(k); if (set == null) getCharFirst(input, res, k); }); return res; } private static Set<Character> getCharFirst(Map<String, String> input, Map<String, Set<Character>> res, String k) { Set<Character> set = new HashSet<>(); // 寻找First(k) String v = input.get(k); String[] vs = v.split("\\|"); for (String s : vs) { char first = s.charAt(0); if (first == 'ε' || !Character.isUpperCase(first)) { // 空 | 终结符 set.add(first); } else { // 非终结符 String nextK = String.valueOf(s.charAt(0)); if (s.length() > 1 && s.charAt(1) == '\'') { nextK += '\''; } set.addAll(getCharFirst(input, res, nextK)); } } // 寻找 <SUF> res.put(k, set); return set; } }
true
28083_0
class Solution { //dp,注意类似台阶问题,字母可以分为一个字母编码或者两个编码,则dp[i]会和dp[i - 1]和dp[i - 2]有关 public int numDecodings(String s) { int[] dp = new int[s.length() + 1]; if(s.length() <= 2 && s.charAt(0) == '0') return 0; dp[0] = 1; for(int i = 1; i <= s.length(); i ++){ if(s.charAt(i - 1) != '0'){ dp[i] += dp[i - 1]; } if(i - 2 >= 0 && s.charAt(i - 2) != '0' && Integer.parseInt(s.substring(i - 2, i)) <= 26){ dp[i] += dp[i - 2]; } } return dp[s.length()]; } }
NOTHINGYQ/LeetCode
Java/1-100/91_decode ways.java
234
//dp,注意类似台阶问题,字母可以分为一个字母编码或者两个编码,则dp[i]会和dp[i - 1]和dp[i - 2]有关
line_comment
zh-cn
class Solution { //dp <SUF> public int numDecodings(String s) { int[] dp = new int[s.length() + 1]; if(s.length() <= 2 && s.charAt(0) == '0') return 0; dp[0] = 1; for(int i = 1; i <= s.length(); i ++){ if(s.charAt(i - 1) != '0'){ dp[i] += dp[i - 1]; } if(i - 2 >= 0 && s.charAt(i - 2) != '0' && Integer.parseInt(s.substring(i - 2, i)) <= 26){ dp[i] += dp[i - 2]; } } return dp[s.length()]; } }
true
60140_21
package com.tf.npu; import com.tf.npu.Init.SUPER2FH.ModBlocks.*; import com.tf.npu.Items.ItemLoader; import com.tf.npu.Proxy.CommonProxy; import com.tf.npu.Util.Reference; import com.tf.npu.Util.LoggerUtil; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.client.model.obj.OBJLoader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION) public class NPU { //**************************************************************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //**************************************************************************** public static final CreativeTabs MY_TAB = new CreativeTabs(Reference.MODID) { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.InnerPng); } }; public static final CreativeTabs MY_TAB1 = new CreativeTabs("constructions") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.ConsPng); } }; public static final CreativeTabs MY_TAB2 = new CreativeTabs("titles") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.TitlePng); } }; public static final CreativeTabs MY_TAB3 = new CreativeTabs("blocksonroad") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.OutPng); } }; public static final CreativeTabs MY_TAB4 = new CreativeTabs("windoor") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.WinDoorPng); } }; public static final CreativeTabs MY_TAB5 = new CreativeTabs("sign") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.Homework); } }; // ************************************SUPER2FH********************************************* public static final CreativeTabs TEMPORARY = new CreativeTabs("temporary") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 椅子 */ public static final CreativeTabs CHAIR = new CreativeTabs("chair") { @Override public ItemStack createIcon() { return new ItemStack(ChairBlocks.CHAIR_AUDITORIUM_BLUE); } }; /** * 方块 */ public static final CreativeTabs CUBE = new CreativeTabs("cube") { @Override public ItemStack createIcon() { return new ItemStack(CubeBlocks.CEMENT_LIGHTBLUE); } }; /** * 设施 */ public static final CreativeTabs FACILITY = new CreativeTabs("facility") { @Override public ItemStack createIcon() { return new ItemStack(FacilityBlocks.TRASH_CLASSIFICATION_MEDICAL); } }; /** * 桌子 */ public static final CreativeTabs DESK = new CreativeTabs("desk") { @Override public ItemStack createIcon() { return new ItemStack(DeskBlocks.DESK_FOLDABLE); } }; /** * 障碍 */ public static final CreativeTabs FENCE = new CreativeTabs("fence") { @Override public ItemStack createIcon() { return new ItemStack(FenceBlocks.ROADBLOCK_DOUBLE); } }; public static final CreativeTabs NPUARMOR = new CreativeTabs("npu_armor") { @Override public ItemStack createIcon() { return new ItemStack(TemporaryBlocks.MASK_MEDICAL); } }; /** * 展示相关 */ public static final CreativeTabs RACK = new CreativeTabs("rack") { @Override public ItemStack createIcon() { return new ItemStack(RackBlocks.FLAG_CY); } }; /** * 栏杆 */ public static final CreativeTabs RAILING = new CreativeTabs("railing") { @Override public ItemStack createIcon() { return new ItemStack(RailingBlocks.RAILING_HALF); } }; /** * 楼梯 */ public static final CreativeTabs STAIR = new CreativeTabs("stair") { @Override public ItemStack createIcon() { return new ItemStack(StairBlocks.STAIR_CEMENT_LIGHTBLUE); } }; /** * 杂物 */ public static final CreativeTabs SUNDRIES = new CreativeTabs("sundries") { @Override public ItemStack createIcon() { return new ItemStack(SundriesBlocks.ADMISSION_LETTER_2021); } }; /** * 车辆 */ public static final CreativeTabs VEHICLE = new CreativeTabs("vehicle") { @Override public ItemStack createIcon() { return new ItemStack(VehicleBlocks.BIKE1); } }; /** * 机械机器 */ public static final CreativeTabs MACHINE = new CreativeTabs("machine") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 家具相关 */ public static final CreativeTabs FURNITURE = new CreativeTabs("furniture") { @Override public ItemStack createIcon() { return new ItemStack(FurnitureBlocks.AIRCONDITIONER_VERTICAL); } }; /** * 灯光相关 */ public static final CreativeTabs LIGHT = new CreativeTabs("light_dormitory_bathroom") { @Override public ItemStack createIcon() { return new ItemStack(LightBlocks.LIGHT_CEILING_LONG); } }; /** * 窗户相关 */ public static final CreativeTabs WINDOW = new CreativeTabs("window") { @Override public ItemStack createIcon() { return new ItemStack(WindowBlocks.GLASS_WALL_HALF); } }; @Instance public static NPU instance; @SidedProxy(serverSide = Reference.SERVER_PROXY_CLASS, clientSide = Reference.CLIENT_PROXY_CLASS) public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { if (event.getSide().isClient()) { OBJLoader.INSTANCE.addDomain("NPU"); } proxy.preInit(event); LoggerUtil.logger = event.getModLog(); LoggerUtil.logger.warn("Project Npu Reconstruction!"); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } public static boolean DISABLE_IN_DEV = false; // private static CreativeTabs geckolibItemGroup; private boolean deobfuscatedEnvironment; // public static CreativeTabs getGeckolibItemGroup() // { // if (geckolibItemGroup == null) // { // geckolibItemGroup = new CreativeTabs(CreativeTabs.getNextID(), "geckolib_examples") // { // @Override // public ItemStack createIcon() // { // return new ItemStack(ItemRegistry.JACK_IN_THE_BOX); // } // }; // } // // return geckolibItemGroup; // } // @SideOnly(Side.CLIENT) // @Mod.EventHandler // public void registerRenderers(FMLPreInitializationEvent event) // { // ClientRegistry.bindTileEntitySpecialRenderer(CNCTileEntity.class, new CNCRenderer()); // // } }
NPUcraft/build-the-world-for-npu
src/main/java/com/tf/npu/NPU.java
2,057
/** * 机械机器 */
block_comment
zh-cn
package com.tf.npu; import com.tf.npu.Init.SUPER2FH.ModBlocks.*; import com.tf.npu.Items.ItemLoader; import com.tf.npu.Proxy.CommonProxy; import com.tf.npu.Util.Reference; import com.tf.npu.Util.LoggerUtil; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.client.model.obj.OBJLoader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION) public class NPU { //**************************************************************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //**************************************************************************** public static final CreativeTabs MY_TAB = new CreativeTabs(Reference.MODID) { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.InnerPng); } }; public static final CreativeTabs MY_TAB1 = new CreativeTabs("constructions") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.ConsPng); } }; public static final CreativeTabs MY_TAB2 = new CreativeTabs("titles") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.TitlePng); } }; public static final CreativeTabs MY_TAB3 = new CreativeTabs("blocksonroad") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.OutPng); } }; public static final CreativeTabs MY_TAB4 = new CreativeTabs("windoor") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.WinDoorPng); } }; public static final CreativeTabs MY_TAB5 = new CreativeTabs("sign") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.Homework); } }; // ************************************SUPER2FH********************************************* public static final CreativeTabs TEMPORARY = new CreativeTabs("temporary") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 椅子 */ public static final CreativeTabs CHAIR = new CreativeTabs("chair") { @Override public ItemStack createIcon() { return new ItemStack(ChairBlocks.CHAIR_AUDITORIUM_BLUE); } }; /** * 方块 */ public static final CreativeTabs CUBE = new CreativeTabs("cube") { @Override public ItemStack createIcon() { return new ItemStack(CubeBlocks.CEMENT_LIGHTBLUE); } }; /** * 设施 */ public static final CreativeTabs FACILITY = new CreativeTabs("facility") { @Override public ItemStack createIcon() { return new ItemStack(FacilityBlocks.TRASH_CLASSIFICATION_MEDICAL); } }; /** * 桌子 */ public static final CreativeTabs DESK = new CreativeTabs("desk") { @Override public ItemStack createIcon() { return new ItemStack(DeskBlocks.DESK_FOLDABLE); } }; /** * 障碍 */ public static final CreativeTabs FENCE = new CreativeTabs("fence") { @Override public ItemStack createIcon() { return new ItemStack(FenceBlocks.ROADBLOCK_DOUBLE); } }; public static final CreativeTabs NPUARMOR = new CreativeTabs("npu_armor") { @Override public ItemStack createIcon() { return new ItemStack(TemporaryBlocks.MASK_MEDICAL); } }; /** * 展示相关 */ public static final CreativeTabs RACK = new CreativeTabs("rack") { @Override public ItemStack createIcon() { return new ItemStack(RackBlocks.FLAG_CY); } }; /** * 栏杆 */ public static final CreativeTabs RAILING = new CreativeTabs("railing") { @Override public ItemStack createIcon() { return new ItemStack(RailingBlocks.RAILING_HALF); } }; /** * 楼梯 */ public static final CreativeTabs STAIR = new CreativeTabs("stair") { @Override public ItemStack createIcon() { return new ItemStack(StairBlocks.STAIR_CEMENT_LIGHTBLUE); } }; /** * 杂物 */ public static final CreativeTabs SUNDRIES = new CreativeTabs("sundries") { @Override public ItemStack createIcon() { return new ItemStack(SundriesBlocks.ADMISSION_LETTER_2021); } }; /** * 车辆 */ public static final CreativeTabs VEHICLE = new CreativeTabs("vehicle") { @Override public ItemStack createIcon() { return new ItemStack(VehicleBlocks.BIKE1); } }; /** * 机械机 <SUF>*/ public static final CreativeTabs MACHINE = new CreativeTabs("machine") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 家具相关 */ public static final CreativeTabs FURNITURE = new CreativeTabs("furniture") { @Override public ItemStack createIcon() { return new ItemStack(FurnitureBlocks.AIRCONDITIONER_VERTICAL); } }; /** * 灯光相关 */ public static final CreativeTabs LIGHT = new CreativeTabs("light_dormitory_bathroom") { @Override public ItemStack createIcon() { return new ItemStack(LightBlocks.LIGHT_CEILING_LONG); } }; /** * 窗户相关 */ public static final CreativeTabs WINDOW = new CreativeTabs("window") { @Override public ItemStack createIcon() { return new ItemStack(WindowBlocks.GLASS_WALL_HALF); } }; @Instance public static NPU instance; @SidedProxy(serverSide = Reference.SERVER_PROXY_CLASS, clientSide = Reference.CLIENT_PROXY_CLASS) public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { if (event.getSide().isClient()) { OBJLoader.INSTANCE.addDomain("NPU"); } proxy.preInit(event); LoggerUtil.logger = event.getModLog(); LoggerUtil.logger.warn("Project Npu Reconstruction!"); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } public static boolean DISABLE_IN_DEV = false; // private static CreativeTabs geckolibItemGroup; private boolean deobfuscatedEnvironment; // public static CreativeTabs getGeckolibItemGroup() // { // if (geckolibItemGroup == null) // { // geckolibItemGroup = new CreativeTabs(CreativeTabs.getNextID(), "geckolib_examples") // { // @Override // public ItemStack createIcon() // { // return new ItemStack(ItemRegistry.JACK_IN_THE_BOX); // } // }; // } // // return geckolibItemGroup; // } // @SideOnly(Side.CLIENT) // @Mod.EventHandler // public void registerRenderers(FMLPreInitializationEvent event) // { // ClientRegistry.bindTileEntitySpecialRenderer(CNCTileEntity.class, new CNCRenderer()); // // } }
false
60604_1
package me.http.utils; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import me.app.global.Constant; import android.util.Log; public class MyThreadPool { private static MyThreadPool mThreadPool = null; private static final boolean D = Constant.DEBUG; private static final String TAG = "MyThreadPool"; private static final int THREAD_NUM = 2; private ExecutorService executorService = null; protected MyThreadPool() { executorService = Executors.newFixedThreadPool(THREAD_NUM); } public static MyThreadPool getInstance() { if (mThreadPool == null) { mThreadPool = new MyThreadPool(); } return mThreadPool; } public ExecutorService getExecutorService() { return executorService; } public void mHandleGetTask(String url, Map<String, String> mapParams) { executorService.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub } }); } /** * 描述:立即关闭. */ public void shutdownNow() { if (!executorService.isTerminated()) { executorService.shutdownNow(); listenShutdown(); } } /** * 描述:平滑关闭. */ public void shutdown() { if (!executorService.isTerminated()) { executorService.shutdown(); listenShutdown(); } } /** * 描述:关闭监听. */ public void listenShutdown() { try { while (!executorService.awaitTermination(1, TimeUnit.MILLISECONDS)) { if (D) Log.d(TAG, "线程池未关闭"); } if (D) Log.d(TAG, "线程池已关闭"); } catch (Exception e) { e.printStackTrace(); } } }
NUTEGG/where
src/me/http/utils/MyThreadPool.java
493
/** * 描述:立即关闭. */
block_comment
zh-cn
package me.http.utils; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import me.app.global.Constant; import android.util.Log; public class MyThreadPool { private static MyThreadPool mThreadPool = null; private static final boolean D = Constant.DEBUG; private static final String TAG = "MyThreadPool"; private static final int THREAD_NUM = 2; private ExecutorService executorService = null; protected MyThreadPool() { executorService = Executors.newFixedThreadPool(THREAD_NUM); } public static MyThreadPool getInstance() { if (mThreadPool == null) { mThreadPool = new MyThreadPool(); } return mThreadPool; } public ExecutorService getExecutorService() { return executorService; } public void mHandleGetTask(String url, Map<String, String> mapParams) { executorService.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub } }); } /** * 描述: <SUF>*/ public void shutdownNow() { if (!executorService.isTerminated()) { executorService.shutdownNow(); listenShutdown(); } } /** * 描述:平滑关闭. */ public void shutdown() { if (!executorService.isTerminated()) { executorService.shutdown(); listenShutdown(); } } /** * 描述:关闭监听. */ public void listenShutdown() { try { while (!executorService.awaitTermination(1, TimeUnit.MILLISECONDS)) { if (D) Log.d(TAG, "线程池未关闭"); } if (D) Log.d(TAG, "线程池已关闭"); } catch (Exception e) { e.printStackTrace(); } } }
false
42303_11
package top.naccl.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import top.naccl.model.vo.BlogIdAndTitle; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @Description: 博客评论 * @Author: Naccl * @Date: 2020-07-27 */ @NoArgsConstructor @Getter @Setter @ToString public class Comment { private Long id; private String nickname;//昵称 private String email;//邮箱 private String content;//评论内容 private String avatar;//头像(图片路径) private Date createTime;//评论时间 private String website;//个人网站 private String ip;//评论者ip地址 private Boolean published;//公开或回收站 private Boolean adminComment;//博主回复 private Integer page;//0普通文章,1关于我页面 private Boolean notice;//接收邮件提醒 private Long parentCommentId;//父评论id private String qq;//如果评论昵称为QQ号,则将昵称和头像置为QQ昵称和QQ头像,并将此字段置为QQ号备份 private BlogIdAndTitle blog;//所属的文章 private List<Comment> replyComments = new ArrayList<>();//回复该评论的评论 }
Naccl/NBlog
blog-api/src/main/java/top/naccl/entity/Comment.java
333
//如果评论昵称为QQ号,则将昵称和头像置为QQ昵称和QQ头像,并将此字段置为QQ号备份
line_comment
zh-cn
package top.naccl.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import top.naccl.model.vo.BlogIdAndTitle; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @Description: 博客评论 * @Author: Naccl * @Date: 2020-07-27 */ @NoArgsConstructor @Getter @Setter @ToString public class Comment { private Long id; private String nickname;//昵称 private String email;//邮箱 private String content;//评论内容 private String avatar;//头像(图片路径) private Date createTime;//评论时间 private String website;//个人网站 private String ip;//评论者ip地址 private Boolean published;//公开或回收站 private Boolean adminComment;//博主回复 private Integer page;//0普通文章,1关于我页面 private Boolean notice;//接收邮件提醒 private Long parentCommentId;//父评论id private String qq;//如果 <SUF> private BlogIdAndTitle blog;//所属的文章 private List<Comment> replyComments = new ArrayList<>();//回复该评论的评论 }
false
18877_1
package main; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MainFrame extends JFrame implements ActionListener { private static final int DEFAULT_WIDTH = 600; private static final int DEFAULT_HEIGHT = 400; private JMenuBar menuBar = new JMenuBar(); // 用户菜单 private JMenu userMenu = new JMenu("用户"); private JMenuItem changePasswordMenuItem = new JMenuItem("修改密码"); private JMenuItem exitMenuItem = new JMenuItem("退出游戏"); // 游戏菜单 private JMenu gameMenu = new JMenu("游戏"); private JMenuItem createRoomItem = new JMenuItem("创建房间"); private JMenuItem enterRoomItem = new JMenuItem("进入房间"); private JPanel panel = new JPanel(); private JButton createRoomButton = new JButton("创建房间"); private JButton enterRoomButton = new JButton("进入房间"); // 欢迎界面 private JLabel welcomeLabel = new JLabel("五子棋"); private void addMenu() { userMenu.add(changePasswordMenuItem); userMenu.add(exitMenuItem); menuBar.add(userMenu); gameMenu.add(createRoomItem); gameMenu.add(enterRoomItem); menuBar.add(gameMenu); this.setJMenuBar(menuBar); exitMenuItem.addActionListener(this); createRoomItem.addActionListener(this); } private void addButton() { panel.add(createRoomButton); panel.add(enterRoomButton); this.getContentPane().add(panel, BorderLayout.SOUTH); // 注册监听 Button createRoomButton.addActionListener(this); } private void addLabel() { welcomeLabel.setFont(new java.awt.Font("welcome", 1, 48)); welcomeLabel.setHorizontalAlignment(SwingConstants.CENTER); this.getContentPane().add(welcomeLabel); } public MainFrame() throws HeadlessException { addMenu(); addButton(); addLabel(); this.setTitle("五子棋"); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private game.GameFrame game; @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exitMenuItem) {//退出 if (JOptionPane.showConfirmDialog(this, "确认要退出游戏?", "退出", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { System.exit(0); } } else if (e.getSource() == createRoomButton || e.getSource() == createRoomItem) {// 创建游戏 if (game == null) game = new game.GameFrame(); game.setVisible(true); } } }
Naccl/gobang-java-swing
src/main/MainFrame.java
706
// 游戏菜单
line_comment
zh-cn
package main; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MainFrame extends JFrame implements ActionListener { private static final int DEFAULT_WIDTH = 600; private static final int DEFAULT_HEIGHT = 400; private JMenuBar menuBar = new JMenuBar(); // 用户菜单 private JMenu userMenu = new JMenu("用户"); private JMenuItem changePasswordMenuItem = new JMenuItem("修改密码"); private JMenuItem exitMenuItem = new JMenuItem("退出游戏"); // 游戏 <SUF> private JMenu gameMenu = new JMenu("游戏"); private JMenuItem createRoomItem = new JMenuItem("创建房间"); private JMenuItem enterRoomItem = new JMenuItem("进入房间"); private JPanel panel = new JPanel(); private JButton createRoomButton = new JButton("创建房间"); private JButton enterRoomButton = new JButton("进入房间"); // 欢迎界面 private JLabel welcomeLabel = new JLabel("五子棋"); private void addMenu() { userMenu.add(changePasswordMenuItem); userMenu.add(exitMenuItem); menuBar.add(userMenu); gameMenu.add(createRoomItem); gameMenu.add(enterRoomItem); menuBar.add(gameMenu); this.setJMenuBar(menuBar); exitMenuItem.addActionListener(this); createRoomItem.addActionListener(this); } private void addButton() { panel.add(createRoomButton); panel.add(enterRoomButton); this.getContentPane().add(panel, BorderLayout.SOUTH); // 注册监听 Button createRoomButton.addActionListener(this); } private void addLabel() { welcomeLabel.setFont(new java.awt.Font("welcome", 1, 48)); welcomeLabel.setHorizontalAlignment(SwingConstants.CENTER); this.getContentPane().add(welcomeLabel); } public MainFrame() throws HeadlessException { addMenu(); addButton(); addLabel(); this.setTitle("五子棋"); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private game.GameFrame game; @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exitMenuItem) {//退出 if (JOptionPane.showConfirmDialog(this, "确认要退出游戏?", "退出", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { System.exit(0); } } else if (e.getSource() == createRoomButton || e.getSource() == createRoomItem) {// 创建游戏 if (game == null) game = new game.GameFrame(); game.setVisible(true); } } }
false
61178_3
package ustcsoft.bean; import java.math.BigDecimal; import java.text.DateFormat; import java.util.Date; public class Teacher { private String teacherID;// 工号 private String teacherName;// 名字 private int time;// 入职时长 private int age;// 年纪 private BigDecimal pay;// 工资 private Date startTime;// 入职时间 private String text;// 备考 @Override public String toString() { // TODO 自动生成的方法存根 return "学号:" + this.getTeacherID() + " " + "姓名:" + this.getTeacherName() + " " + "年龄:" + this.getAge() + " " + "入学时间:" + this.getStartTime() + " " + "备考:" + this.getText() + " " + "工资:" + this.getPay() + " " + "入职时长:" + this.getTime(); } public String getTeacherID() { return teacherID; } public void setTeacherID(String teacherID) { this.teacherID = teacherID; } public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public int getTime() { return time; } public void setTime(Integer time) { this.time = time; } public int getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getPay() { return pay; } public void setPay(BigDecimal pay) { this.pay = pay; } public String getStartTime() { return DateFormat.getDateInstance(DateFormat.FULL).format(startTime);// 格式化时间 } public void setStartTime(Date startTime) { this.startTime = startTime; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
NaiHeKK/JAVA-Study
src/ustcsoft/bean/Teacher.java
538
// 年纪
line_comment
zh-cn
package ustcsoft.bean; import java.math.BigDecimal; import java.text.DateFormat; import java.util.Date; public class Teacher { private String teacherID;// 工号 private String teacherName;// 名字 private int time;// 入职时长 private int age;// 年纪 <SUF> private BigDecimal pay;// 工资 private Date startTime;// 入职时间 private String text;// 备考 @Override public String toString() { // TODO 自动生成的方法存根 return "学号:" + this.getTeacherID() + " " + "姓名:" + this.getTeacherName() + " " + "年龄:" + this.getAge() + " " + "入学时间:" + this.getStartTime() + " " + "备考:" + this.getText() + " " + "工资:" + this.getPay() + " " + "入职时长:" + this.getTime(); } public String getTeacherID() { return teacherID; } public void setTeacherID(String teacherID) { this.teacherID = teacherID; } public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public int getTime() { return time; } public void setTime(Integer time) { this.time = time; } public int getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getPay() { return pay; } public void setPay(BigDecimal pay) { this.pay = pay; } public String getStartTime() { return DateFormat.getDateInstance(DateFormat.FULL).format(startTime);// 格式化时间 } public void setStartTime(Date startTime) { this.startTime = startTime; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
false
44067_4
package com.southernbox.indexbar.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.southernbox.indexbar.R; import com.southernbox.indexbar.adapter.MainAdapter; import com.southernbox.indexbar.entity.Entity; import com.southernbox.indexbar.widget.IndexBar; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by SouthernBox on 2016/10/25 0025. * 主页面 */ public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private MainAdapter mAdapter; private List<Entity> mList = new ArrayList<>(); private IndexBar mIndexBar; private View vFlow; private TextView tvFlowIndex; private LinearLayoutManager layoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initIndexBar(); initData(); initFlowIndex(); } /** * 初始化列表 */ private void initRecyclerView() { mRecyclerView = findViewById(R.id.rv); layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); mAdapter = new MainAdapter(this, mList); mRecyclerView.setAdapter(mAdapter); } /** * 初始化快速索引栏 */ private void initIndexBar() { mIndexBar = findViewById(R.id.indexbar); TextView tvToast = findViewById(R.id.tv_toast); mIndexBar.setSelectedIndexTextView(tvToast); mIndexBar.setOnIndexChangedListener(new IndexBar.OnIndexChangedListener() { @Override public void onIndexChanged(String index) { for (int i = 0; i < mList.size(); i++) { String firstWord = mList.get(i).getFirstWord(); if (index.equals(firstWord)) { // 滚动列表到指定的位置 layoutManager.scrollToPositionWithOffset(i, 0); return; } } } }); } /** * 加载数据 */ @SuppressWarnings("unchecked") private void initData() { Map<String, Object> map = convertSortList(getData()); mList.clear(); mList.addAll((List<Entity>) map.get("sortList")); Object[] keys = (Object[]) map.get("keys"); String[] letters = new String[keys.length]; for (int i = 0; i < keys.length; i++) { letters[i] = keys[i].toString(); } mIndexBar.setIndexs(letters); mAdapter.notifyDataSetChanged(); } /** * 初始化顶部悬浮标签 */ private void initFlowIndex() { vFlow = findViewById(R.id.ll_index); tvFlowIndex = findViewById(R.id.tv_index); mRecyclerView.addOnScrollListener(new mScrollListener()); //设置首项的索引字母 if (mList.size() > 0) { tvFlowIndex.setText(mList.get(0).getFirstWord()); vFlow.setVisibility(View.VISIBLE); } } private class mScrollListener extends RecyclerView.OnScrollListener { private int mFlowHeight; private int mCurrentPosition = -1; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { mFlowHeight = vFlow.getMeasuredHeight(); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); View view = layoutManager.findViewByPosition(firstVisibleItemPosition + 1); if (view != null) { if (view.getTop() <= mFlowHeight && isItem(firstVisibleItemPosition + 1)) { vFlow.setY(view.getTop() - mFlowHeight); } else { vFlow.setY(0); } } if (mCurrentPosition != firstVisibleItemPosition) { mCurrentPosition = firstVisibleItemPosition; tvFlowIndex.setText(mList.get(mCurrentPosition).getFirstWord()); } } /** * @param position 对应项的下标 * @return 是否为标签项 */ private boolean isItem(int position) { return mAdapter.getItemViewType(position) == MainAdapter.VIEW_INDEX; } } /** * 按首字母将数据排序 * * @param list 需要排序的数组 * @return 返回按首字母排序的集合(集合中插入标签项),及所有出现的首字母数组 */ public Map<String, Object> convertSortList(List<Entity> list) { HashMap<String, List<Entity>> map = new HashMap<>(); for (Entity item : list) { String firstWord; if (TextUtils.isEmpty(item.getFirstWord())) { firstWord = "#"; } else { firstWord = item.getFirstWord().toUpperCase(); } if (map.containsKey(firstWord)) { map.get(firstWord).add(item); } else { List<Entity> mList = new ArrayList<>(); mList.add(item); map.put(firstWord, mList); } } Object[] keys = map.keySet().toArray(); Arrays.sort(keys); List<Entity> sortList = new ArrayList<>(); for (Object key : keys) { Entity t = getIndexItem(key.toString()); sortList.add(t); sortList.addAll(map.get(key.toString())); } HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("sortList", sortList); resultMap.put("keys", keys); return resultMap; } private Entity getIndexItem(String firstWord) { Entity entity = new Entity(); entity.setFirstWord(firstWord); entity.setIndex(true); return entity; } private List<Entity> getData() { List<Entity> list = new ArrayList<>(); list.add(new Entity("加内特", "J")); list.add(new Entity("韦德", "W")); list.add(new Entity("詹姆斯", "Z")); list.add(new Entity("安东尼", "A")); list.add(new Entity("科比", "K")); list.add(new Entity("乔丹", "Q")); list.add(new Entity("奥尼尔", "A")); list.add(new Entity("麦格雷迪", "M")); list.add(new Entity("艾弗森", "A")); list.add(new Entity("哈达威", "H")); list.add(new Entity("纳什", "N")); list.add(new Entity("弗朗西斯", "F")); list.add(new Entity("姚明", "Y")); list.add(new Entity("库里", "K")); list.add(new Entity("邓肯", "D")); list.add(new Entity("吉诺比利", "J")); list.add(new Entity("帕克", "P")); list.add(new Entity("杜兰特", "D")); list.add(new Entity("韦伯", "W")); list.add(new Entity("威斯布鲁克", "W")); list.add(new Entity("霍华德", "H")); list.add(new Entity("保罗", "B")); list.add(new Entity("罗斯", "L")); list.add(new Entity("加索尔", "J")); list.add(new Entity("隆多", "L")); list.add(new Entity("诺维斯基", "N")); list.add(new Entity("格里芬", "G")); list.add(new Entity("波什", "B")); list.add(new Entity("伊戈达拉", "Y")); return list; } }
NanBox/IndexBar
app/src/main/java/com/southernbox/indexbar/activity/MainActivity.java
1,961
/** * 加载数据 */
block_comment
zh-cn
package com.southernbox.indexbar.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.southernbox.indexbar.R; import com.southernbox.indexbar.adapter.MainAdapter; import com.southernbox.indexbar.entity.Entity; import com.southernbox.indexbar.widget.IndexBar; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by SouthernBox on 2016/10/25 0025. * 主页面 */ public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private MainAdapter mAdapter; private List<Entity> mList = new ArrayList<>(); private IndexBar mIndexBar; private View vFlow; private TextView tvFlowIndex; private LinearLayoutManager layoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initIndexBar(); initData(); initFlowIndex(); } /** * 初始化列表 */ private void initRecyclerView() { mRecyclerView = findViewById(R.id.rv); layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); mAdapter = new MainAdapter(this, mList); mRecyclerView.setAdapter(mAdapter); } /** * 初始化快速索引栏 */ private void initIndexBar() { mIndexBar = findViewById(R.id.indexbar); TextView tvToast = findViewById(R.id.tv_toast); mIndexBar.setSelectedIndexTextView(tvToast); mIndexBar.setOnIndexChangedListener(new IndexBar.OnIndexChangedListener() { @Override public void onIndexChanged(String index) { for (int i = 0; i < mList.size(); i++) { String firstWord = mList.get(i).getFirstWord(); if (index.equals(firstWord)) { // 滚动列表到指定的位置 layoutManager.scrollToPositionWithOffset(i, 0); return; } } } }); } /** * 加载数 <SUF>*/ @SuppressWarnings("unchecked") private void initData() { Map<String, Object> map = convertSortList(getData()); mList.clear(); mList.addAll((List<Entity>) map.get("sortList")); Object[] keys = (Object[]) map.get("keys"); String[] letters = new String[keys.length]; for (int i = 0; i < keys.length; i++) { letters[i] = keys[i].toString(); } mIndexBar.setIndexs(letters); mAdapter.notifyDataSetChanged(); } /** * 初始化顶部悬浮标签 */ private void initFlowIndex() { vFlow = findViewById(R.id.ll_index); tvFlowIndex = findViewById(R.id.tv_index); mRecyclerView.addOnScrollListener(new mScrollListener()); //设置首项的索引字母 if (mList.size() > 0) { tvFlowIndex.setText(mList.get(0).getFirstWord()); vFlow.setVisibility(View.VISIBLE); } } private class mScrollListener extends RecyclerView.OnScrollListener { private int mFlowHeight; private int mCurrentPosition = -1; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { mFlowHeight = vFlow.getMeasuredHeight(); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); View view = layoutManager.findViewByPosition(firstVisibleItemPosition + 1); if (view != null) { if (view.getTop() <= mFlowHeight && isItem(firstVisibleItemPosition + 1)) { vFlow.setY(view.getTop() - mFlowHeight); } else { vFlow.setY(0); } } if (mCurrentPosition != firstVisibleItemPosition) { mCurrentPosition = firstVisibleItemPosition; tvFlowIndex.setText(mList.get(mCurrentPosition).getFirstWord()); } } /** * @param position 对应项的下标 * @return 是否为标签项 */ private boolean isItem(int position) { return mAdapter.getItemViewType(position) == MainAdapter.VIEW_INDEX; } } /** * 按首字母将数据排序 * * @param list 需要排序的数组 * @return 返回按首字母排序的集合(集合中插入标签项),及所有出现的首字母数组 */ public Map<String, Object> convertSortList(List<Entity> list) { HashMap<String, List<Entity>> map = new HashMap<>(); for (Entity item : list) { String firstWord; if (TextUtils.isEmpty(item.getFirstWord())) { firstWord = "#"; } else { firstWord = item.getFirstWord().toUpperCase(); } if (map.containsKey(firstWord)) { map.get(firstWord).add(item); } else { List<Entity> mList = new ArrayList<>(); mList.add(item); map.put(firstWord, mList); } } Object[] keys = map.keySet().toArray(); Arrays.sort(keys); List<Entity> sortList = new ArrayList<>(); for (Object key : keys) { Entity t = getIndexItem(key.toString()); sortList.add(t); sortList.addAll(map.get(key.toString())); } HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("sortList", sortList); resultMap.put("keys", keys); return resultMap; } private Entity getIndexItem(String firstWord) { Entity entity = new Entity(); entity.setFirstWord(firstWord); entity.setIndex(true); return entity; } private List<Entity> getData() { List<Entity> list = new ArrayList<>(); list.add(new Entity("加内特", "J")); list.add(new Entity("韦德", "W")); list.add(new Entity("詹姆斯", "Z")); list.add(new Entity("安东尼", "A")); list.add(new Entity("科比", "K")); list.add(new Entity("乔丹", "Q")); list.add(new Entity("奥尼尔", "A")); list.add(new Entity("麦格雷迪", "M")); list.add(new Entity("艾弗森", "A")); list.add(new Entity("哈达威", "H")); list.add(new Entity("纳什", "N")); list.add(new Entity("弗朗西斯", "F")); list.add(new Entity("姚明", "Y")); list.add(new Entity("库里", "K")); list.add(new Entity("邓肯", "D")); list.add(new Entity("吉诺比利", "J")); list.add(new Entity("帕克", "P")); list.add(new Entity("杜兰特", "D")); list.add(new Entity("韦伯", "W")); list.add(new Entity("威斯布鲁克", "W")); list.add(new Entity("霍华德", "H")); list.add(new Entity("保罗", "B")); list.add(new Entity("罗斯", "L")); list.add(new Entity("加索尔", "J")); list.add(new Entity("隆多", "L")); list.add(new Entity("诺维斯基", "N")); list.add(new Entity("格里芬", "G")); list.add(new Entity("波什", "B")); list.add(new Entity("伊戈达拉", "Y")); return list; } }
false
49379_0
import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MultiOutPutMapper extends Mapper<LongWritable, Text, IntWritable, Text>{ //将每行的“,”之前的元素作为key,其余值作为value @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub //The function of trim() is to remove spaces in the front and the back of one string. String line = value.toString().trim(); if(null != line && 0 != line.length()){ String[] arr = line.split(","); context.write(new IntWritable(Integer.parseInt(arr[0])), value); //存储的key-value格式, //举例:“1101,thinkpad yoga,联想,windows 8,超级本”将被存储为“1101-1101,thinkpad yoga,联想,windows 8,超级本” } } }
Nana0606/hadoop_example
multi_output/MultiOutPutMapper.java
294
//将每行的“,”之前的元素作为key,其余值作为value
line_comment
zh-cn
import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; public class MultiOutPutMapper extends Mapper<LongWritable, Text, IntWritable, Text>{ //将每 <SUF> @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { // TODO Auto-generated method stub //The function of trim() is to remove spaces in the front and the back of one string. String line = value.toString().trim(); if(null != line && 0 != line.length()){ String[] arr = line.split(","); context.write(new IntWritable(Integer.parseInt(arr[0])), value); //存储的key-value格式, //举例:“1101,thinkpad yoga,联想,windows 8,超级本”将被存储为“1101-1101,thinkpad yoga,联想,windows 8,超级本” } } }
true
7948_0
/** * 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 * * 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花? * 能则返回True,不能则返回False。 * * 示例 1: * * 输入: flowerbed = [1,0,0,0,1], n = 1 * 输出: True * 示例 2: * * 输入: flowerbed = [1,0,0,0,1], n = 2 * 输出: False * 注意: * * 数组内已种好的花不会违反种植规则。 * 输入的数组长度范围为 [1, 20000]。 * n 是非负整数,且不会超过输入数组的大小。 * @author:xzj * @date: 2018/8/6 16:09 */ class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int index = 0; int count = 0; if (flowerbed.length ==1) { if (flowerbed[0] == 0) { return n == 0 || n == 1; }else { return n==0; } } else { while (index < flowerbed.length) { if (index == 0) { if (flowerbed[0] == 0 && flowerbed[1] == 0) { flowerbed[0] = 1; count++; } } else if (index == flowerbed.length - 1) { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0) { flowerbed[index] = 1; count++; } } else { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0 && flowerbed[index + 1] == 0) { flowerbed[index] = 1; count++; } } if(count >=n) return true; index++; } return false; } } }
NanayaHaruki/leetcode
序号/605. Can Place Flowers.java
605
/** * 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 * * 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花? * 能则返回True,不能则返回False。 * * 示例 1: * * 输入: flowerbed = [1,0,0,0,1], n = 1 * 输出: True * 示例 2: * * 输入: flowerbed = [1,0,0,0,1], n = 2 * 输出: False * 注意: * * 数组内已种好的花不会违反种植规则。 * 输入的数组长度范围为 [1, 20000]。 * n 是非负整数,且不会超过输入数组的大小。 * @author:xzj * @date: 2018/8/6 16:09 */
block_comment
zh-cn
/** * 假设你 <SUF>*/ class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int index = 0; int count = 0; if (flowerbed.length ==1) { if (flowerbed[0] == 0) { return n == 0 || n == 1; }else { return n==0; } } else { while (index < flowerbed.length) { if (index == 0) { if (flowerbed[0] == 0 && flowerbed[1] == 0) { flowerbed[0] = 1; count++; } } else if (index == flowerbed.length - 1) { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0) { flowerbed[index] = 1; count++; } } else { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0 && flowerbed[index + 1] == 0) { flowerbed[index] = 1; count++; } } if(count >=n) return true; index++; } return false; } } }
false
34188_2
/** * @auth Nannf * @date 2020/6/17 11:21 * @description: 给定正整数数组 A,A[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i。 * <p> * 一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i - j):景点的评分之和减去它们两者之间的距离。 * <p> * 返回一对观光景点能取得的最高分。 * <p> * 输入:[8,1,5,2,6] * 输出:11 * 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 */ public class Solution_1014 { public static void main(String[] args) { int[] a = new int[]{8, 1, 5, 2, 6}; System.out.println(new Solution_1014().maxScoreSightseeingPair(a)); } public int maxScoreSightseeingPair_Mine(int[] A) { // 先不管,上来先用暴力解法 // 提交后 超出时间限制,需要找出其中多余计算的部分,进行优化 int result = 0; for (int i = 0; i < A.length; i++) { for (int j = i+1; j < A.length; j++) { result = Math.max(result,A[i] + A[j] + i - j); } } return result; } public int maxScoreSightseeingPair(int[] A) { // 先不管,上来先用暴力解法 // 提交后 超出时间限制,需要找出其中多余计算的部分,进行优化 int mx = A[0] + 0; int ans = 0; for (int i = 1; i < A.length; i++) { ans = Math.max(ans,A[i] - i + mx); mx = Math.max(mx, A[i] + i); } return ans; } }
Nannf/LeetCode
Solution/src/Solution_1014.java
568
// 提交后 超出时间限制,需要找出其中多余计算的部分,进行优化
line_comment
zh-cn
/** * @auth Nannf * @date 2020/6/17 11:21 * @description: 给定正整数数组 A,A[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i。 * <p> * 一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i - j):景点的评分之和减去它们两者之间的距离。 * <p> * 返回一对观光景点能取得的最高分。 * <p> * 输入:[8,1,5,2,6] * 输出:11 * 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11 */ public class Solution_1014 { public static void main(String[] args) { int[] a = new int[]{8, 1, 5, 2, 6}; System.out.println(new Solution_1014().maxScoreSightseeingPair(a)); } public int maxScoreSightseeingPair_Mine(int[] A) { // 先不管,上来先用暴力解法 // 提交 <SUF> int result = 0; for (int i = 0; i < A.length; i++) { for (int j = i+1; j < A.length; j++) { result = Math.max(result,A[i] + A[j] + i - j); } } return result; } public int maxScoreSightseeingPair(int[] A) { // 先不管,上来先用暴力解法 // 提交后 超出时间限制,需要找出其中多余计算的部分,进行优化 int mx = A[0] + 0; int ans = 0; for (int i = 1; i < A.length; i++) { ans = Math.max(ans,A[i] - i + mx); mx = Math.max(mx, A[i] + i); } return ans; } }
true
2651_17
package com.yiw.circledemo.utils; import com.yiw.circledemo.bean.CircleItem; import com.yiw.circledemo.bean.CommentItem; import com.yiw.circledemo.bean.FavortItem; import com.yiw.circledemo.bean.PhotoInfo; import com.yiw.circledemo.bean.User; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @ClassName: DatasUtil * @Description: TODO(这里用一句话描述这个类的作用) * @author yiw * @date 2015-12-28 下午4:16:21 * */ public class DatasUtil { public static final String[] CONTENTS = { "", "哈哈,18123456789,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。哈哈,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。哈哈,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。哈哈,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。", //"今天是个好日子,http://www.ChinaAr.com;一个不错的VR网站,18123456789,", //"呵呵,http://www.ChinaAr.com;一个不错的VR网站,18123456789,", //"只有http|https|ftp|svn://开头的网址才能识别为网址,正则表达式写的不太好,如果你又更好的正则表达式请评论告诉我,谢谢!", "VR(Virtual Reality,即虚拟现实,简称VR),是由美国VPL公司创建人拉尼尔(Jaron Lanier)在20世纪80年代初提出的。其具体内涵是:综合利用计算机图形系统和各种现实及控制等接口设备,在计算机上生成的、可交互的三维环境中提供沉浸感觉的技术。其中,计算机生成的、可交互的三维环境称为虚拟环境(即Virtual Environment,简称VE)。虚拟现实技术是一种可以创建和体验虚拟世界的计算机仿真系统的技术。它利用计算机生成一种模拟环境,利用多源信息融合的交互式三维动态视景和实体行为的系统仿真使用户沉浸到该环境中。", //"哈哈哈哈", //"图不错", "我勒个去" }; /*public static final String[] PHOTOS = { "http://f.hiphotos.baidu.com/image/pic/item/faf2b2119313b07e97f760d908d7912396dd8c9c.jpg", "http://g.hiphotos.baidu.com/image/pic/item/4b90f603738da977c76ab6fab451f8198718e39e.jpg", "http://e.hiphotos.baidu.com/image/pic/item/902397dda144ad343de8b756d4a20cf430ad858f.jpg", "http://a.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa0fbc1ebfb68f8c5495ee7b8b.jpg", "http://b.hiphotos.baidu.com/image/pic/item/a71ea8d3fd1f4134e61e0f90211f95cad1c85e36.jpg", "http://c.hiphotos.baidu.com/image/pic/item/7dd98d1001e939011b9c86d07fec54e737d19645.jpg", "http://f.hiphotos.baidu.com/image/pic/item/f11f3a292df5e0fecc3e83ef586034a85edf723d.jpg", "http://cdn.duitang.com/uploads/item/201309/17/20130917111400_CNmTr.thumb.224_0.png", "http://pica.nipic.com/2007-10-17/20071017111345564_2.jpg", "http://pic4.nipic.com/20091101/3672704_160309066949_2.jpg", "http://pic4.nipic.com/20091203/1295091_123813163959_2.jpg", "http://pic31.nipic.com/20130624/8821914_104949466000_2.jpg", "http://pic6.nipic.com/20100330/4592428_113348099353_2.jpg", "http://pic9.nipic.com/20100917/5653289_174356436608_2.jpg", "http://img10.3lian.com/sc6/show02/38/65/386515.jpg", "http://pic1.nipic.com/2008-12-09/200812910493588_2.jpg", "http://pic2.ooopic.com/11/79/98/31bOOOPICb1_1024.jpg" };*/ public static final String[] HEADIMG = { "http://img.wzfzl.cn/uploads/allimg/140820/co140R00Q925-14.jpg", "http://www.feizl.com/upload2007/2014_06/1406272351394618.png", "http://v1.qzone.cc/avatar/201308/30/22/56/5220b2828a477072.jpg%21200x200.jpg", "http://v1.qzone.cc/avatar/201308/22/10/36/521579394f4bb419.jpg!200x200.jpg", "http://v1.qzone.cc/avatar/201408/20/17/23/53f468ff9c337550.jpg!200x200.jpg", "http://cdn.duitang.com/uploads/item/201408/13/20140813122725_8h8Yu.jpeg", "http://img.woyaogexing.com/touxiang/nv/20140212/9ac2117139f1ecd8%21200x200.jpg", "http://p1.qqyou.com/touxiang/uploadpic/2013-3/12/2013031212295986807.jpg"}; public static List<User> users = new ArrayList<User>(); public static List<PhotoInfo> PHOTOS = new ArrayList<>(); /** * 动态id自增长 */ private static int circleId = 0; /** * 点赞id自增长 */ private static int favortId = 0; /** * 评论id自增长 */ private static int commentId = 0; public static final User curUser = new User("0", "自己", HEADIMG[0]); static { User user1 = new User("1", "张三", HEADIMG[1]); User user2 = new User("2", "李四", HEADIMG[2]); User user3 = new User("3", "隔壁老王", HEADIMG[3]); User user4 = new User("4", "赵六", HEADIMG[4]); User user5 = new User("5", "田七", HEADIMG[5]); User user6 = new User("6", "Naoki", HEADIMG[6]); User user7 = new User("7", "这个名字是不是很长,哈哈!因为我是用来测试换行的", HEADIMG[7]); users.add(curUser); users.add(user1); users.add(user2); users.add(user3); users.add(user4); users.add(user5); users.add(user6); users.add(user7); PhotoInfo p1 = new PhotoInfo(); p1.url = "http://f.hiphotos.baidu.com/image/pic/item/faf2b2119313b07e97f760d908d7912396dd8c9c.jpg"; p1.w = 640; p1.h = 792; PhotoInfo p2 = new PhotoInfo(); p2.url = "http://g.hiphotos.baidu.com/image/pic/item/4b90f603738da977c76ab6fab451f8198718e39e.jpg"; p2.w = 640; p2.h = 792; PhotoInfo p3 = new PhotoInfo(); p3.url = "http://e.hiphotos.baidu.com/image/pic/item/902397dda144ad343de8b756d4a20cf430ad858f.jpg"; p3.w = 950; p3.h = 597; PhotoInfo p4 = new PhotoInfo(); p4.url = "http://a.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa0fbc1ebfb68f8c5495ee7b8b.jpg"; p4.w = 533; p4.h = 800; PhotoInfo p5 = new PhotoInfo(); p5.url = "http://b.hiphotos.baidu.com/image/pic/item/a71ea8d3fd1f4134e61e0f90211f95cad1c85e36.jpg"; p5.w = 700; p5.h = 467; PhotoInfo p6 = new PhotoInfo(); p6.url = "http://c.hiphotos.baidu.com/image/pic/item/7dd98d1001e939011b9c86d07fec54e737d19645.jpg"; p6.w = 700; p6.h = 467; PhotoInfo p7 = new PhotoInfo(); p7.url = "http://pica.nipic.com/2007-10-17/20071017111345564_2.jpg"; p7.w = 1024; p7.h = 640; PhotoInfo p8 = new PhotoInfo(); p8.url = "http://pic4.nipic.com/20091101/3672704_160309066949_2.jpg"; p8.w = 1024; p8.h = 768; PhotoInfo p9 = new PhotoInfo(); p9.url = "http://pic4.nipic.com/20091203/1295091_123813163959_2.jpg"; p9.w = 1024; p9.h = 640; PhotoInfo p10 = new PhotoInfo(); p10.url = "http://pic31.nipic.com/20130624/8821914_104949466000_2.jpg"; p10.w = 1024; p10.h = 768; PHOTOS.add(p1); PHOTOS.add(p2); PHOTOS.add(p3); PHOTOS.add(p4); PHOTOS.add(p5); PHOTOS.add(p6); PHOTOS.add(p7); PHOTOS.add(p8); PHOTOS.add(p9); PHOTOS.add(p10); } public static List<CircleItem> createCircleDatas() { List<CircleItem> circleDatas = new ArrayList<CircleItem>(); for (int i = 0; i < 15; i++) { CircleItem item = new CircleItem(); User user = getUser(); item.setId(String.valueOf(circleId++)); item.setUser(user); item.setContent(getContent()); item.setCreateTime("12月24日"); item.setFavorters(createFavortItemList()); item.setComments(createCommentItemList()); int type = getRandomNum(10) % 2; if (type == 0) { item.setType("1");// 链接 item.setLinkImg("http://pics.sc.chinaz.com/Files/pic/icons128/2264/%E8%85%BE%E8%AE%AFQQ%E5%9B%BE%E6%A0%87%E4%B8%8B%E8%BD%BD1.png"); item.setLinkTitle("百度一下,你就知道"); } else if(type == 1){ item.setType("2");// 图片 item.setPhotos(createPhotos()); }else { item.setType("3");// 视频 String videoUrl = "http://yiwcicledemo.s.qupai.me/v/80c81c19-7c02-4dee-baca-c97d9bbd6607.mp4"; String videoImgUrl = "http://yiwcicledemo.s.qupai.me/v/80c81c19-7c02-4dee-baca-c97d9bbd6607.jpg"; item.setVideoUrl(videoUrl); item.setVideoImgUrl(videoImgUrl); } circleDatas.add(item); } return circleDatas; } public static User getUser() { return users.get(getRandomNum(users.size())); } public static String getContent() { return CONTENTS[getRandomNum(CONTENTS.length)]; } public static int getRandomNum(int max) { Random random = new Random(); int result = random.nextInt(max); return result; } public static List<PhotoInfo> createPhotos() { List<PhotoInfo> photos = new ArrayList<PhotoInfo>(); int size = getRandomNum(PHOTOS.size()); if (size > 0) { if (size > 9) { size = 9; } for (int i = 0; i < size; i++) { PhotoInfo photo = PHOTOS.get(getRandomNum(PHOTOS.size())); if (!photos.contains(photo)) { photos.add(photo); } else { i--; } } } return photos; } public static List<FavortItem> createFavortItemList() { int size = getRandomNum(users.size()); List<FavortItem> items = new ArrayList<FavortItem>(); List<String> history = new ArrayList<String>(); if (size > 0) { for (int i = 0; i < size; i++) { FavortItem newItem = createFavortItem(); String userid = newItem.getUser().getId(); if (!history.contains(userid)) { items.add(newItem); history.add(userid); } else { i--; } } } return items; } public static FavortItem createFavortItem() { FavortItem item = new FavortItem(); item.setId(String.valueOf(favortId++)); item.setUser(getUser()); return item; } public static FavortItem createCurUserFavortItem() { FavortItem item = new FavortItem(); item.setId(String.valueOf(favortId++)); item.setUser(curUser); return item; } public static List<CommentItem> createCommentItemList() { List<CommentItem> items = new ArrayList<CommentItem>(); int size = getRandomNum(10); if (size > 0) { for (int i = 0; i < size; i++) { items.add(createComment()); } } return items; } public static CommentItem createComment() { CommentItem item = new CommentItem(); item.setId(String.valueOf(commentId++)); item.setContent("哈哈"); User user = getUser(); item.setUser(user); if (getRandomNum(10) % 2 == 0) { while (true) { User replyUser = getUser(); if (!user.getId().equals(replyUser.getId())) { item.setToReplyUser(replyUser); break; } } } return item; } /** * 创建发布评论 * @return */ public static CommentItem createPublicComment(String content){ CommentItem item = new CommentItem(); item.setId(String.valueOf(commentId++)); item.setContent(content); item.setUser(curUser); return item; } /** * 创建回复评论 * @return */ public static CommentItem createReplyComment(User replyUser, String content){ CommentItem item = new CommentItem(); item.setId(String.valueOf(commentId++)); item.setContent(content); item.setUser(curUser); item.setToReplyUser(replyUser); return item; } public static CircleItem createVideoItem(String videoUrl, String imgUrl){ CircleItem item = new CircleItem(); item.setId(String.valueOf(circleId++)); item.setUser(curUser); //item.setContent(getContent()); item.setCreateTime("12月24日"); //item.setFavorters(createFavortItemList()); //item.setComments(createCommentItemList()); item.setType("3");// 图片 item.setVideoUrl(videoUrl); item.setVideoImgUrl(imgUrl); return item; } }
Naoki2015/CircleDemo
CircleDemo/app/src/main/java/com/yiw/circledemo/utils/DatasUtil.java
4,949
/** * 点赞id自增长 */
block_comment
zh-cn
package com.yiw.circledemo.utils; import com.yiw.circledemo.bean.CircleItem; import com.yiw.circledemo.bean.CommentItem; import com.yiw.circledemo.bean.FavortItem; import com.yiw.circledemo.bean.PhotoInfo; import com.yiw.circledemo.bean.User; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * * @ClassName: DatasUtil * @Description: TODO(这里用一句话描述这个类的作用) * @author yiw * @date 2015-12-28 下午4:16:21 * */ public class DatasUtil { public static final String[] CONTENTS = { "", "哈哈,18123456789,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。哈哈,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。哈哈,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。哈哈,ChinaAr http://www.ChinaAr.com;一个不错的VR网站。", //"今天是个好日子,http://www.ChinaAr.com;一个不错的VR网站,18123456789,", //"呵呵,http://www.ChinaAr.com;一个不错的VR网站,18123456789,", //"只有http|https|ftp|svn://开头的网址才能识别为网址,正则表达式写的不太好,如果你又更好的正则表达式请评论告诉我,谢谢!", "VR(Virtual Reality,即虚拟现实,简称VR),是由美国VPL公司创建人拉尼尔(Jaron Lanier)在20世纪80年代初提出的。其具体内涵是:综合利用计算机图形系统和各种现实及控制等接口设备,在计算机上生成的、可交互的三维环境中提供沉浸感觉的技术。其中,计算机生成的、可交互的三维环境称为虚拟环境(即Virtual Environment,简称VE)。虚拟现实技术是一种可以创建和体验虚拟世界的计算机仿真系统的技术。它利用计算机生成一种模拟环境,利用多源信息融合的交互式三维动态视景和实体行为的系统仿真使用户沉浸到该环境中。", //"哈哈哈哈", //"图不错", "我勒个去" }; /*public static final String[] PHOTOS = { "http://f.hiphotos.baidu.com/image/pic/item/faf2b2119313b07e97f760d908d7912396dd8c9c.jpg", "http://g.hiphotos.baidu.com/image/pic/item/4b90f603738da977c76ab6fab451f8198718e39e.jpg", "http://e.hiphotos.baidu.com/image/pic/item/902397dda144ad343de8b756d4a20cf430ad858f.jpg", "http://a.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa0fbc1ebfb68f8c5495ee7b8b.jpg", "http://b.hiphotos.baidu.com/image/pic/item/a71ea8d3fd1f4134e61e0f90211f95cad1c85e36.jpg", "http://c.hiphotos.baidu.com/image/pic/item/7dd98d1001e939011b9c86d07fec54e737d19645.jpg", "http://f.hiphotos.baidu.com/image/pic/item/f11f3a292df5e0fecc3e83ef586034a85edf723d.jpg", "http://cdn.duitang.com/uploads/item/201309/17/20130917111400_CNmTr.thumb.224_0.png", "http://pica.nipic.com/2007-10-17/20071017111345564_2.jpg", "http://pic4.nipic.com/20091101/3672704_160309066949_2.jpg", "http://pic4.nipic.com/20091203/1295091_123813163959_2.jpg", "http://pic31.nipic.com/20130624/8821914_104949466000_2.jpg", "http://pic6.nipic.com/20100330/4592428_113348099353_2.jpg", "http://pic9.nipic.com/20100917/5653289_174356436608_2.jpg", "http://img10.3lian.com/sc6/show02/38/65/386515.jpg", "http://pic1.nipic.com/2008-12-09/200812910493588_2.jpg", "http://pic2.ooopic.com/11/79/98/31bOOOPICb1_1024.jpg" };*/ public static final String[] HEADIMG = { "http://img.wzfzl.cn/uploads/allimg/140820/co140R00Q925-14.jpg", "http://www.feizl.com/upload2007/2014_06/1406272351394618.png", "http://v1.qzone.cc/avatar/201308/30/22/56/5220b2828a477072.jpg%21200x200.jpg", "http://v1.qzone.cc/avatar/201308/22/10/36/521579394f4bb419.jpg!200x200.jpg", "http://v1.qzone.cc/avatar/201408/20/17/23/53f468ff9c337550.jpg!200x200.jpg", "http://cdn.duitang.com/uploads/item/201408/13/20140813122725_8h8Yu.jpeg", "http://img.woyaogexing.com/touxiang/nv/20140212/9ac2117139f1ecd8%21200x200.jpg", "http://p1.qqyou.com/touxiang/uploadpic/2013-3/12/2013031212295986807.jpg"}; public static List<User> users = new ArrayList<User>(); public static List<PhotoInfo> PHOTOS = new ArrayList<>(); /** * 动态id自增长 */ private static int circleId = 0; /** * 点赞i <SUF>*/ private static int favortId = 0; /** * 评论id自增长 */ private static int commentId = 0; public static final User curUser = new User("0", "自己", HEADIMG[0]); static { User user1 = new User("1", "张三", HEADIMG[1]); User user2 = new User("2", "李四", HEADIMG[2]); User user3 = new User("3", "隔壁老王", HEADIMG[3]); User user4 = new User("4", "赵六", HEADIMG[4]); User user5 = new User("5", "田七", HEADIMG[5]); User user6 = new User("6", "Naoki", HEADIMG[6]); User user7 = new User("7", "这个名字是不是很长,哈哈!因为我是用来测试换行的", HEADIMG[7]); users.add(curUser); users.add(user1); users.add(user2); users.add(user3); users.add(user4); users.add(user5); users.add(user6); users.add(user7); PhotoInfo p1 = new PhotoInfo(); p1.url = "http://f.hiphotos.baidu.com/image/pic/item/faf2b2119313b07e97f760d908d7912396dd8c9c.jpg"; p1.w = 640; p1.h = 792; PhotoInfo p2 = new PhotoInfo(); p2.url = "http://g.hiphotos.baidu.com/image/pic/item/4b90f603738da977c76ab6fab451f8198718e39e.jpg"; p2.w = 640; p2.h = 792; PhotoInfo p3 = new PhotoInfo(); p3.url = "http://e.hiphotos.baidu.com/image/pic/item/902397dda144ad343de8b756d4a20cf430ad858f.jpg"; p3.w = 950; p3.h = 597; PhotoInfo p4 = new PhotoInfo(); p4.url = "http://a.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa0fbc1ebfb68f8c5495ee7b8b.jpg"; p4.w = 533; p4.h = 800; PhotoInfo p5 = new PhotoInfo(); p5.url = "http://b.hiphotos.baidu.com/image/pic/item/a71ea8d3fd1f4134e61e0f90211f95cad1c85e36.jpg"; p5.w = 700; p5.h = 467; PhotoInfo p6 = new PhotoInfo(); p6.url = "http://c.hiphotos.baidu.com/image/pic/item/7dd98d1001e939011b9c86d07fec54e737d19645.jpg"; p6.w = 700; p6.h = 467; PhotoInfo p7 = new PhotoInfo(); p7.url = "http://pica.nipic.com/2007-10-17/20071017111345564_2.jpg"; p7.w = 1024; p7.h = 640; PhotoInfo p8 = new PhotoInfo(); p8.url = "http://pic4.nipic.com/20091101/3672704_160309066949_2.jpg"; p8.w = 1024; p8.h = 768; PhotoInfo p9 = new PhotoInfo(); p9.url = "http://pic4.nipic.com/20091203/1295091_123813163959_2.jpg"; p9.w = 1024; p9.h = 640; PhotoInfo p10 = new PhotoInfo(); p10.url = "http://pic31.nipic.com/20130624/8821914_104949466000_2.jpg"; p10.w = 1024; p10.h = 768; PHOTOS.add(p1); PHOTOS.add(p2); PHOTOS.add(p3); PHOTOS.add(p4); PHOTOS.add(p5); PHOTOS.add(p6); PHOTOS.add(p7); PHOTOS.add(p8); PHOTOS.add(p9); PHOTOS.add(p10); } public static List<CircleItem> createCircleDatas() { List<CircleItem> circleDatas = new ArrayList<CircleItem>(); for (int i = 0; i < 15; i++) { CircleItem item = new CircleItem(); User user = getUser(); item.setId(String.valueOf(circleId++)); item.setUser(user); item.setContent(getContent()); item.setCreateTime("12月24日"); item.setFavorters(createFavortItemList()); item.setComments(createCommentItemList()); int type = getRandomNum(10) % 2; if (type == 0) { item.setType("1");// 链接 item.setLinkImg("http://pics.sc.chinaz.com/Files/pic/icons128/2264/%E8%85%BE%E8%AE%AFQQ%E5%9B%BE%E6%A0%87%E4%B8%8B%E8%BD%BD1.png"); item.setLinkTitle("百度一下,你就知道"); } else if(type == 1){ item.setType("2");// 图片 item.setPhotos(createPhotos()); }else { item.setType("3");// 视频 String videoUrl = "http://yiwcicledemo.s.qupai.me/v/80c81c19-7c02-4dee-baca-c97d9bbd6607.mp4"; String videoImgUrl = "http://yiwcicledemo.s.qupai.me/v/80c81c19-7c02-4dee-baca-c97d9bbd6607.jpg"; item.setVideoUrl(videoUrl); item.setVideoImgUrl(videoImgUrl); } circleDatas.add(item); } return circleDatas; } public static User getUser() { return users.get(getRandomNum(users.size())); } public static String getContent() { return CONTENTS[getRandomNum(CONTENTS.length)]; } public static int getRandomNum(int max) { Random random = new Random(); int result = random.nextInt(max); return result; } public static List<PhotoInfo> createPhotos() { List<PhotoInfo> photos = new ArrayList<PhotoInfo>(); int size = getRandomNum(PHOTOS.size()); if (size > 0) { if (size > 9) { size = 9; } for (int i = 0; i < size; i++) { PhotoInfo photo = PHOTOS.get(getRandomNum(PHOTOS.size())); if (!photos.contains(photo)) { photos.add(photo); } else { i--; } } } return photos; } public static List<FavortItem> createFavortItemList() { int size = getRandomNum(users.size()); List<FavortItem> items = new ArrayList<FavortItem>(); List<String> history = new ArrayList<String>(); if (size > 0) { for (int i = 0; i < size; i++) { FavortItem newItem = createFavortItem(); String userid = newItem.getUser().getId(); if (!history.contains(userid)) { items.add(newItem); history.add(userid); } else { i--; } } } return items; } public static FavortItem createFavortItem() { FavortItem item = new FavortItem(); item.setId(String.valueOf(favortId++)); item.setUser(getUser()); return item; } public static FavortItem createCurUserFavortItem() { FavortItem item = new FavortItem(); item.setId(String.valueOf(favortId++)); item.setUser(curUser); return item; } public static List<CommentItem> createCommentItemList() { List<CommentItem> items = new ArrayList<CommentItem>(); int size = getRandomNum(10); if (size > 0) { for (int i = 0; i < size; i++) { items.add(createComment()); } } return items; } public static CommentItem createComment() { CommentItem item = new CommentItem(); item.setId(String.valueOf(commentId++)); item.setContent("哈哈"); User user = getUser(); item.setUser(user); if (getRandomNum(10) % 2 == 0) { while (true) { User replyUser = getUser(); if (!user.getId().equals(replyUser.getId())) { item.setToReplyUser(replyUser); break; } } } return item; } /** * 创建发布评论 * @return */ public static CommentItem createPublicComment(String content){ CommentItem item = new CommentItem(); item.setId(String.valueOf(commentId++)); item.setContent(content); item.setUser(curUser); return item; } /** * 创建回复评论 * @return */ public static CommentItem createReplyComment(User replyUser, String content){ CommentItem item = new CommentItem(); item.setId(String.valueOf(commentId++)); item.setContent(content); item.setUser(curUser); item.setToReplyUser(replyUser); return item; } public static CircleItem createVideoItem(String videoUrl, String imgUrl){ CircleItem item = new CircleItem(); item.setId(String.valueOf(circleId++)); item.setUser(curUser); //item.setContent(getContent()); item.setCreateTime("12月24日"); //item.setFavorters(createFavortItemList()); //item.setComments(createCommentItemList()); item.setType("3");// 图片 item.setVideoUrl(videoUrl); item.setVideoImgUrl(imgUrl); return item; } }
true
35730_4
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Main { public static void main(String[] args) { if (args.length > 0) { unusedCleaner(args[0]); } } static ArrayList<TypeSource> currents = new ArrayList<>(); static final ArrayList<File> AllFiles = new ArrayList<>(); static String encoding = "utf-8"; static boolean LastIsPath = false; public static void unusedCleaner(String filePath) { int crtLine = 0; ArrayList<TypeSource> files = new ArrayList<>(); try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader( new FileInputStream(file), encoding); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (crtLine == 0) { parsellFiles(lineTxt); } else { if (!parseType(lineTxt)) { String trim = lineTxt.trim(); if (new File(trim).exists()) { for (Iterator<TypeSource> iterator = currents .iterator(); iterator.hasNext();) { TypeSource typeSource = (TypeSource) iterator .next().clone(); typeSource.path = trim; typeSource.xmlTag = typeSource.getXmlTag(); files.add(typeSource); } LastIsPath = true; } } } crtLine++; } read.close(); } else { System.out.println("noFile"); } } catch (Exception e) { System.out.println("Failed"); e.printStackTrace(); } for (Iterator<TypeSource> iterator = files.iterator(); iterator .hasNext();) { TypeSource typeSource = (TypeSource) iterator.next(); System.out.println(typeSource); typeSource.cleanSelf(); } System.out.println("done"); } public static void parsellFiles(String line) { String reg = "Running in:\\s+(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(line); if (matcher.find()) { String path = matcher.group(1); File file = new File(path); scanSourceFiles(file); } } public static boolean parseType(String lineTxt) { // drawable/anim/layout/ String reg = "((drawable)|(anim)|(layout)|(dimen)|(string)|(attr)|(style)|(styleable)|(color)|(id))\\s*:\\s*(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(lineTxt); if (matcher.find()) { if (LastIsPath) { currents.clear(); } LastIsPath = false; TypeSource typeSource = new TypeSource(); typeSource.type = matcher.group(1); typeSource.name = matcher.group(matcher.groupCount()); currents.add(typeSource); return true; } else { return false; } } @SuppressWarnings("unchecked") public static void deleteNodeByName(String path, String tag, String name) { try { SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); Element element = document.getRootElement(); List<Element> list = element.elements("dimen"); for (int i = 0; i < list.size(); i++) { Element ele = list.get(i); String tName = ele.attributeValue("name"); if (tName != null && tName.length() > 0) { if (name.equals(ele.attributeValue("name"))) { element.remove(ele); break; } } } OutputFormat format = new OutputFormat("", false);// XMLWriter xmlWriter = new XMLWriter(new FileWriter(path), format); xmlWriter.write(document); xmlWriter.flush(); } catch (Exception e1) { e1.printStackTrace(); } } public static void scanSourceFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { scanSourceFiles(file); } else { AllFiles.add(file); } } } } static class TypeSource { String type = "";// 类型 String name = "";// xml中的name属性 String xmlTag = "";// xml的tag名 String path = "";// 属于哪个文件 public String getXmlTag() { if ("styleable".equals(type)) { return "declare-styleable"; } else { return type; } } @Override public String toString() { return type + " | " + name + " | " + xmlTag + " | " + path; } /** * 一个一个的单独删,要啥效率啊 */ public void cleanSelf() { try { if (type == null) { return; } if (type.equals("drawable") || type.equals("layout") || type.equals("anim")) { checkAndDeleteFile(); } else if (type.equals("color")) { if (pathMatchesWithType()) { new File(path).delete(); } else { deleteNodeByName(path, xmlTag, name); } } else if (type.equals("id") || type.equals("")) { // do nothing } else { deleteNodeByName(path, xmlTag, name); } } catch (Exception e) { } } public void checkAndDeleteFile() { if (pathMatchesWithType()) { new File(path).delete(); } else { //不放心的话可以跳过,不执行这一块,这种情况很少见,一般是过期的R文件导致 if (type.equals("drawable")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("drawable")) { file.delete(); } } } else if (type.equals("layout")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("layout")) { file.delete(); } } } else if (type.equals("anim")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("anim")) { file.delete(); } } } } } public boolean pathMatchesWithType() { boolean flag = false; File file = new File(path); File parentFile = file.getParentFile(); if (type.equals("drawable")) { flag = parentFile.getName().startsWith("drawable"); } else if (type.equals("layout")) { flag = parentFile.getName().startsWith("layout"); } else if (type.equals("anim")) { flag = parentFile.getName().startsWith("anim"); } else if (type.equals("color")) { flag = parentFile.getName().startsWith("color"); } return flag; } public TypeSource clone() { TypeSource ts = new TypeSource(); ts.type = type; ts.name = name; ts.xmlTag = xmlTag; ts.path = path; return ts; } } }
NashLegend/AndroidResourceCleaner
src/Main.java
2,163
/** * 一个一个的单独删,要啥效率啊 */
block_comment
zh-cn
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Main { public static void main(String[] args) { if (args.length > 0) { unusedCleaner(args[0]); } } static ArrayList<TypeSource> currents = new ArrayList<>(); static final ArrayList<File> AllFiles = new ArrayList<>(); static String encoding = "utf-8"; static boolean LastIsPath = false; public static void unusedCleaner(String filePath) { int crtLine = 0; ArrayList<TypeSource> files = new ArrayList<>(); try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader( new FileInputStream(file), encoding); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (crtLine == 0) { parsellFiles(lineTxt); } else { if (!parseType(lineTxt)) { String trim = lineTxt.trim(); if (new File(trim).exists()) { for (Iterator<TypeSource> iterator = currents .iterator(); iterator.hasNext();) { TypeSource typeSource = (TypeSource) iterator .next().clone(); typeSource.path = trim; typeSource.xmlTag = typeSource.getXmlTag(); files.add(typeSource); } LastIsPath = true; } } } crtLine++; } read.close(); } else { System.out.println("noFile"); } } catch (Exception e) { System.out.println("Failed"); e.printStackTrace(); } for (Iterator<TypeSource> iterator = files.iterator(); iterator .hasNext();) { TypeSource typeSource = (TypeSource) iterator.next(); System.out.println(typeSource); typeSource.cleanSelf(); } System.out.println("done"); } public static void parsellFiles(String line) { String reg = "Running in:\\s+(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(line); if (matcher.find()) { String path = matcher.group(1); File file = new File(path); scanSourceFiles(file); } } public static boolean parseType(String lineTxt) { // drawable/anim/layout/ String reg = "((drawable)|(anim)|(layout)|(dimen)|(string)|(attr)|(style)|(styleable)|(color)|(id))\\s*:\\s*(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(lineTxt); if (matcher.find()) { if (LastIsPath) { currents.clear(); } LastIsPath = false; TypeSource typeSource = new TypeSource(); typeSource.type = matcher.group(1); typeSource.name = matcher.group(matcher.groupCount()); currents.add(typeSource); return true; } else { return false; } } @SuppressWarnings("unchecked") public static void deleteNodeByName(String path, String tag, String name) { try { SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); Element element = document.getRootElement(); List<Element> list = element.elements("dimen"); for (int i = 0; i < list.size(); i++) { Element ele = list.get(i); String tName = ele.attributeValue("name"); if (tName != null && tName.length() > 0) { if (name.equals(ele.attributeValue("name"))) { element.remove(ele); break; } } } OutputFormat format = new OutputFormat("", false);// XMLWriter xmlWriter = new XMLWriter(new FileWriter(path), format); xmlWriter.write(document); xmlWriter.flush(); } catch (Exception e1) { e1.printStackTrace(); } } public static void scanSourceFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { scanSourceFiles(file); } else { AllFiles.add(file); } } } } static class TypeSource { String type = "";// 类型 String name = "";// xml中的name属性 String xmlTag = "";// xml的tag名 String path = "";// 属于哪个文件 public String getXmlTag() { if ("styleable".equals(type)) { return "declare-styleable"; } else { return type; } } @Override public String toString() { return type + " | " + name + " | " + xmlTag + " | " + path; } /** * 一个一 <SUF>*/ public void cleanSelf() { try { if (type == null) { return; } if (type.equals("drawable") || type.equals("layout") || type.equals("anim")) { checkAndDeleteFile(); } else if (type.equals("color")) { if (pathMatchesWithType()) { new File(path).delete(); } else { deleteNodeByName(path, xmlTag, name); } } else if (type.equals("id") || type.equals("")) { // do nothing } else { deleteNodeByName(path, xmlTag, name); } } catch (Exception e) { } } public void checkAndDeleteFile() { if (pathMatchesWithType()) { new File(path).delete(); } else { //不放心的话可以跳过,不执行这一块,这种情况很少见,一般是过期的R文件导致 if (type.equals("drawable")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("drawable")) { file.delete(); } } } else if (type.equals("layout")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("layout")) { file.delete(); } } } else if (type.equals("anim")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("anim")) { file.delete(); } } } } } public boolean pathMatchesWithType() { boolean flag = false; File file = new File(path); File parentFile = file.getParentFile(); if (type.equals("drawable")) { flag = parentFile.getName().startsWith("drawable"); } else if (type.equals("layout")) { flag = parentFile.getName().startsWith("layout"); } else if (type.equals("anim")) { flag = parentFile.getName().startsWith("anim"); } else if (type.equals("color")) { flag = parentFile.getName().startsWith("color"); } return flag; } public TypeSource clone() { TypeSource ts = new TypeSource(); ts.type = type; ts.name = name; ts.xmlTag = xmlTag; ts.path = path; return ts; } } }
false
32088_6
/* * Copyright (C) 2008 The Android Open Source Project * * 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 com.android.launcher2; import android.content.ContentValues; import android.content.Intent; import android.graphics.Bitmap; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * 桌面上的一个小条目,有可能是应用、快捷方式、文件夹、插件 */ class ItemInfo { static final int NO_ID = -1; /** * The id in the settings database for this item 数据库中的id */ long id = NO_ID; /** * 类型,有可能是应用、快捷方式、文件夹、插件 * {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION}, * {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT}, * {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER}, or * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET}. */ int itemType; /** * 放这个item的窗口,对于桌面来说,这个是 * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP} * * 对于“所有程序”界面来说是 {@link #NO_ID} (因为不用保存在数据库里) * * 对于用户文件夹来说是文件夹id */ long container = NO_ID; /** * 所在屏幕index */ int screen = -1; /** * 在屏幕上的x位置 */ int cellX = -1; /** * 在屏幕上的y位置 */ int cellY = -1; /** * 宽度 */ int spanX = 1; /** * 高度 */ int spanY = 1; /** * 最小宽度 */ int minSpanX = 1; /** * 最小高度 */ int minSpanY = 1; /** * 这个item是否需要在数据库中升级 */ boolean requiresDbUpdate = false; /** * 标题 */ CharSequence title; /** * 在拖放操作中的位置 */ int[] dropPos = null; ItemInfo() { } ItemInfo(ItemInfo info) { id = info.id; cellX = info.cellX; cellY = info.cellY; spanX = info.spanX; spanY = info.spanY; screen = info.screen; itemType = info.itemType; container = info.container; // tempdebug: LauncherModel.checkItemInfo(this); } /** * 返回包名,不存在则为空 */ static String getPackageName(Intent intent) { if (intent != null) { String packageName = intent.getPackage(); if (packageName == null && intent.getComponent() != null) { packageName = intent.getComponent().getPackageName(); } if (packageName != null) { return packageName; } } return ""; } /** * 保存数据到数据库 * * @param values */ void onAddToDatabase(ContentValues values) { values.put(LauncherSettings.BaseLauncherColumns.ITEM_TYPE, itemType); values.put(LauncherSettings.Favorites.CONTAINER, container); values.put(LauncherSettings.Favorites.SCREEN, screen); values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); values.put(LauncherSettings.Favorites.SPANX, spanX); values.put(LauncherSettings.Favorites.SPANY, spanY); } /** * 修改坐标 */ void updateValuesWithCoordinates(ContentValues values, int cellX, int cellY) { values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); } static byte[] flattenBitmap(Bitmap bitmap) { // 把图片转换成byte[] int size = bitmap.getWidth() * bitmap.getHeight() * 4; ByteArrayOutputStream out = new ByteArrayOutputStream(size); try { bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); return out.toByteArray(); } catch (IOException e) { Log.w("Favorite", "Could not write icon"); return null; } } static void writeBitmap(ContentValues values, Bitmap bitmap) { if (bitmap != null) { byte[] data = flattenBitmap(bitmap); values.put(LauncherSettings.Favorites.ICON, data); } } /** * It is very important that sub-classes implement this if they contain any * references to the activity (anything in the view hierarchy etc.). If not, * leaks can result since ItemInfo objects persist across rotation and can * hence leak by holding stale references to the old view hierarchy / * activity. * 如果子类持有任何activity的引用,那么一定要引用它,否则可能内存泄漏 */ void unbind() { } @Override public String toString() { return "Item(id=" + this.id + " type=" + this.itemType + " container=" + this.container + " screen=" + screen + " cellX=" + cellX + " cellY=" + cellY + " spanX=" + spanX + " spanY=" + spanY + " dropPos=" + dropPos + ")"; } }
NashLegend/Launcher
src/com/android/launcher2/ItemInfo.java
1,511
/** * 在屏幕上的x位置 */
block_comment
zh-cn
/* * Copyright (C) 2008 The Android Open Source Project * * 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 com.android.launcher2; import android.content.ContentValues; import android.content.Intent; import android.graphics.Bitmap; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * 桌面上的一个小条目,有可能是应用、快捷方式、文件夹、插件 */ class ItemInfo { static final int NO_ID = -1; /** * The id in the settings database for this item 数据库中的id */ long id = NO_ID; /** * 类型,有可能是应用、快捷方式、文件夹、插件 * {@link LauncherSettings.Favorites#ITEM_TYPE_APPLICATION}, * {@link LauncherSettings.Favorites#ITEM_TYPE_SHORTCUT}, * {@link LauncherSettings.Favorites#ITEM_TYPE_FOLDER}, or * {@link LauncherSettings.Favorites#ITEM_TYPE_APPWIDGET}. */ int itemType; /** * 放这个item的窗口,对于桌面来说,这个是 * {@link LauncherSettings.Favorites#CONTAINER_DESKTOP} * * 对于“所有程序”界面来说是 {@link #NO_ID} (因为不用保存在数据库里) * * 对于用户文件夹来说是文件夹id */ long container = NO_ID; /** * 所在屏幕index */ int screen = -1; /** * 在屏幕 <SUF>*/ int cellX = -1; /** * 在屏幕上的y位置 */ int cellY = -1; /** * 宽度 */ int spanX = 1; /** * 高度 */ int spanY = 1; /** * 最小宽度 */ int minSpanX = 1; /** * 最小高度 */ int minSpanY = 1; /** * 这个item是否需要在数据库中升级 */ boolean requiresDbUpdate = false; /** * 标题 */ CharSequence title; /** * 在拖放操作中的位置 */ int[] dropPos = null; ItemInfo() { } ItemInfo(ItemInfo info) { id = info.id; cellX = info.cellX; cellY = info.cellY; spanX = info.spanX; spanY = info.spanY; screen = info.screen; itemType = info.itemType; container = info.container; // tempdebug: LauncherModel.checkItemInfo(this); } /** * 返回包名,不存在则为空 */ static String getPackageName(Intent intent) { if (intent != null) { String packageName = intent.getPackage(); if (packageName == null && intent.getComponent() != null) { packageName = intent.getComponent().getPackageName(); } if (packageName != null) { return packageName; } } return ""; } /** * 保存数据到数据库 * * @param values */ void onAddToDatabase(ContentValues values) { values.put(LauncherSettings.BaseLauncherColumns.ITEM_TYPE, itemType); values.put(LauncherSettings.Favorites.CONTAINER, container); values.put(LauncherSettings.Favorites.SCREEN, screen); values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); values.put(LauncherSettings.Favorites.SPANX, spanX); values.put(LauncherSettings.Favorites.SPANY, spanY); } /** * 修改坐标 */ void updateValuesWithCoordinates(ContentValues values, int cellX, int cellY) { values.put(LauncherSettings.Favorites.CELLX, cellX); values.put(LauncherSettings.Favorites.CELLY, cellY); } static byte[] flattenBitmap(Bitmap bitmap) { // 把图片转换成byte[] int size = bitmap.getWidth() * bitmap.getHeight() * 4; ByteArrayOutputStream out = new ByteArrayOutputStream(size); try { bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); out.flush(); out.close(); return out.toByteArray(); } catch (IOException e) { Log.w("Favorite", "Could not write icon"); return null; } } static void writeBitmap(ContentValues values, Bitmap bitmap) { if (bitmap != null) { byte[] data = flattenBitmap(bitmap); values.put(LauncherSettings.Favorites.ICON, data); } } /** * It is very important that sub-classes implement this if they contain any * references to the activity (anything in the view hierarchy etc.). If not, * leaks can result since ItemInfo objects persist across rotation and can * hence leak by holding stale references to the old view hierarchy / * activity. * 如果子类持有任何activity的引用,那么一定要引用它,否则可能内存泄漏 */ void unbind() { } @Override public String toString() { return "Item(id=" + this.id + " type=" + this.itemType + " container=" + this.container + " screen=" + screen + " cellX=" + cellX + " cellY=" + cellY + " spanX=" + spanX + " spanY=" + spanY + " dropPos=" + dropPos + ")"; } }
true
2279_3
package net.nashlegend.legendexplorer.fragment; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import net.nashlegend.legendexplorer.MainActivity; import net.nashlegend.legendexplorer.consts.FileConst; import net.nashlegend.legendexplorer.utils.FileCategoryHelper; import net.nashlegend.legendexplorer.R; import net.nashlegend.legendutils.Tools.FileUtil; import android.annotation.SuppressLint; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.RelativeLayout; import android.widget.TextView; /** * 分类视图 * * @author NashLegend */ public class CategoriedFragment extends BaseFragment implements Explorable { protected View view; private static ScannerReceiver receiver; private FileListFragment listFragment; private View usedView; private View totalView; private TextView usageText; private RelativeLayout spaceLayout; private static HashMap<Integer, FileCategory> button2Category = new HashMap<Integer, FileCategory>(); static { button2Category.put(R.id.category_music, FileCategory.Music); button2Category.put(R.id.category_video, FileCategory.Video); button2Category.put(R.id.category_picture, FileCategory.Picture); button2Category.put(R.id.category_document, FileCategory.Doc); button2Category.put(R.id.category_zip, FileCategory.Zip); button2Category.put(R.id.category_apk, FileCategory.Apk); } public enum FileCategory { All, Music, Video, Picture, Doc, Zip, Apk, Other } public CategoriedFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(R.layout.layout_file_category, container, false); spaceLayout = (RelativeLayout) view.findViewById(R.id.spaceLayout); usedView = view.findViewById(R.id.view_used); totalView = view.findViewById(R.id.view_total); usageText = (TextView) view.findViewById(R.id.text_usage); setupClick(); updateUI(); registerReceiver(); } else { if (view.getParent() != null) { ((ViewGroup) view.getParent()).removeView(view); } } return view; } public void updateUI() { refreshData(); } public void refreshData() { spaceLayout.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT > 15) { spaceLayout.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { spaceLayout.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { try { StatFs statfs = new StatFs(Environment .getExternalStorageDirectory() .getAbsolutePath()); // 获取SDCard上BLOCK总数 long nTotalBlocks = statfs.getBlockCount(); // 获取SDCard上每个block的SIZE long nBlocSize = statfs.getBlockSize(); // 获取可供程序使用的Block的数量 long nAvailaBlock = statfs.getAvailableBlocks(); // 计算SDCard 总容量大小MB long total = nTotalBlocks * nBlocSize; // 计算 SDCard 剩余大小MB long free = nAvailaBlock * nBlocSize; // 计算 SDCard 剩余大小MB long used = total - free; ViewGroup.LayoutParams params = usedView .getLayoutParams(); params.width = (int) (totalView.getWidth() * used / total); usedView.setLayoutParams(params); usageText.setText(FileUtil.convertStorage(used) + "/" + FileUtil.convertStorage(total)); } catch (IllegalArgumentException e) { } } } }); QueryTask task = new QueryTask(); task.execute(""); } class QueryTask extends AsyncTask<String, Integer, Integer> { @Override protected Integer doInBackground(String... params) { FileCategoryHelper.refreshCategoryInfo(getActivity()); return null; } @Override protected void onPostExecute(Integer result) { for (FileCategory fc : FileCategoryHelper.sCategories) { FileCategoryHelper.CategoryInfo categoryInfo = FileCategoryHelper .getCategoryInfos().get(fc); setCategoryCount(fc, categoryInfo.count); } } } public void setupClick() { setupClick(R.id.category_music); setupClick(R.id.category_video); setupClick(R.id.category_picture); setupClick(R.id.category_document); setupClick(R.id.category_zip); setupClick(R.id.category_apk); } private void setupClick(int id) { View button = view.findViewById(id); button.setOnClickListener(onClickListener); } private static int getCategoryCountId(FileCategory fc) { switch (fc) { case Music: return R.id.category_music_count; case Video: return R.id.category_video_count; case Picture: return R.id.category_picture_count; case Doc: return R.id.category_document_count; case Zip: return R.id.category_zip_count; case Apk: return R.id.category_apk_count; default: break; } return 0; } private void setCategoryCount(FileCategory fc, long count) { int id = getCategoryCountId(fc); if (id == 0) return; setTextView(id, "(" + count + ")"); } private void setTextView(int id, String t) { TextView text = (TextView) view.findViewById(id); text.setText(t); } public void registerReceiver() { receiver = new ScannerReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addDataScheme("file"); getActivity().registerReceiver(receiver, filter); } View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { FileCategory f = button2Category.get(v.getId()); if (f != null) { showCategoryList(f); } } }; public void showCategoryList(FileCategory f) { listFragment = new FileListFragment(); listFragment.setCategory(f); Bundle bundle = new Bundle(); bundle.putInt(FileConst.Extra_Explore_Type, FileConst.Value_Explore_Type_Categories); listFragment.setArguments(bundle); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); transaction.replace(R.id.content_category, listFragment); transaction.commit(); Intent intent = new Intent(); int mask = 0; mask = MainActivity.FlagRefreshListItem | MainActivity.FlagToggleHiddleItem | MainActivity.FlagAddFileItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); } public boolean hideCategoryList() { if (listFragment == null) { return false; } else { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); transaction.remove(listFragment); transaction.commit(); listFragment = null; // frameLayout.setVisibility(View.GONE); Intent intent = new Intent(); int mask = MainActivity.FlagSearchFileItem | MainActivity.FlagToggleViewItem | MainActivity.FlagAddFileItem | MainActivity.FlagToggleHiddleItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); return true; } } private static final int MSG_FILE_CHANGED_TIMER = 100; private Timer timer; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case MSG_FILE_CHANGED_TIMER: updateUI(); break; } super.handleMessage(msg); } }; private boolean inSelectMode; synchronized public void notifyFileChanged() { if (timer != null) { timer.cancel(); } timer = new Timer(); timer.schedule(new TimerTask() { public void run() { timer = null; Message message = new Message(); message.what = MSG_FILE_CHANGED_TIMER; handler.sendMessage(message); } }, 1000); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { try { getActivity().unregisterReceiver(receiver); } catch (Exception e) { } super.onDestroy(); } @Override public boolean doBackAction() { if (inSelectMode) { exitSelectMode(); return true; } if (listFragment != null) { hideCategoryList(); return true; } return false; } @Override public boolean doVeryAction(Intent intent) { String action = intent.getAction(); if (FileConst.Action_FileItem_Long_Click.equals(action)) { change2SelectMode(); } else if (FileConst.Action_FileItem_Unselect.equals(action)) { // selectAllButton.setOnCheckedChangeListener(null); // selectAllButton.setChecked(false); // selectAllButton.setOnCheckedChangeListener(this); } else if (FileConst.Action_File_Operation_Done.equals(action)) { exitSelectMode(); } else if (FileConst.Action_Search_File.equals(action)) { String query = intent .getStringExtra(FileConst.Key_Search_File_Query); searchFile(query); } else if (FileConst.Action_Quit_Search.equals(action)) { searchFile(""); } else if (FileConst.Action_Toggle_View_Mode.equals(action)) { toggleViewMode(); } else if (FileConst.Action_Refresh_FileList.equals(action)) { new Handler().post(new Runnable() { @Override public void run() { refreshFileList(); } }); } else if (FileConst.Action_Copy_File.equals(action)) { copyFile(); } else if (FileConst.Action_Move_File.equals(action)) { moveFile(); } else if (FileConst.Action_Delete_File.equals(action)) { deleteFile(); } else if (FileConst.Action_Rename_File.equals(action)) { renameFile(); } else if (FileConst.Action_Zip_File.equals(action)) { zipFile(); } else if (FileConst.Action_Property_File.equals(action)) { propertyFile(); } return false; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { Intent intent = new Intent(); int mask = 0; if (listFragment == null) { mask = MainActivity.FlagSearchFileItem | MainActivity.FlagToggleViewItem | MainActivity.FlagAddFileItem | MainActivity.FlagToggleHiddleItem; } else { mask = MainActivity.FlagRefreshListItem | MainActivity.FlagToggleHiddleItem | MainActivity.FlagAddFileItem; } intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); } } public void deleteFile() { if (listFragment != null) { listFragment.deleteFile(); } } public void moveFile() { if (listFragment != null) { listFragment.moveFile(); } } public void copyFile() { if (listFragment != null) { listFragment.copyFile(); } } /** * 调用系统扫描方法起不到什么作用,真的。除非发生如下情况: 1.所有app在修改、删除、添加、移动文件时都更新content. * 2.手动扫描全盘,但是慢 */ public void refreshFileList() { // Intent.ACTION_MEDIA_MOUNTED not allow after API19 // getActivity().sendBroadcast(new Intent( // Intent.ACTION_MEDIA_MOUNTED, // Uri.parse("file://" + Environment.getExternalStorageDirectory()))); // getActivity().sendBroadcast(new // Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mediaMountUri)); // no use,it won't scan all files // MediaScannerConnection.scanFile(getActivity(), // new String[] { Environment.getExternalStorageDirectory() // .getAbsolutePath() }, null, // new MediaScannerConnection.OnScanCompletedListener() { // // @Override // public void onScanCompleted(String path, Uri uri) { // // } // }); refreshData(); if (listFragment != null) { listFragment.refreshFileList(); } } public void toggleViewMode() { if (listFragment != null) { listFragment.toggleViewMode(); } } public void searchFile(String query) { if (listFragment != null) { listFragment.searchFile(query); } } private void exitSelectMode() { if (listFragment != null) { // selectAllButton.setVisibility(View.GONE); inSelectMode = false; listFragment.exitSelectMode(); Intent intent = new Intent(); int mask = 0; mask = MainActivity.FlagRefreshListItem | MainActivity.FlagToggleHiddleItem | MainActivity.FlagAddFileItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); } } private void change2SelectMode() { if (listFragment != null) { // selectAllButton.setVisibility(View.VISIBLE); inSelectMode = true; listFragment.change2SelectMode(); Intent intent = new Intent(); int mask = 0; mask = MainActivity.FlagFavorItem | MainActivity.FlagUnzipFileItem | MainActivity.FlagZipFileItem | MainActivity.FlagRenameFileItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_Operation_ActionBar); getActivity().sendBroadcast(intent); } } public class ScannerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { notifyFileChanged(); } } } /** * 彻底地扫描全盘 * * @author NashLegend */ class ScanTask extends AsyncTask<String, Integer, Boolean> { ArrayList<String> paths = new ArrayList<String>(); public void scanFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file2 = files[i]; scanFile(file2); } } } else { String suffix = FileUtil.getFileSuffix(file); if (suffix.length() > 0 && isArrayContains(suffix)) { paths.add(file.getAbsolutePath()); } } } private boolean isArrayContains(String suffix) { // 事实上无需扫描媒体文件,如果后缀是媒体文件但是却没有被MediaScanner扫描到,说明这可能是一个私有的文件 // 比如在Android/data/com.xx.xxx/image里面有文件是不会想要被放进媒体库的,所以不使用下列数组 // String[] strs = { "mp3", "jpg", "jpeg", "bmp", "gif", "png", // "mp4","avi", "rmvk", "mkv", "wmv", "apk", "txt", "doc", "docx", // "xls", "xlsx", "ppt", "pptx", "pdf", "zip", "rar", "7z" }; // 有良心的app在使用doc类型的文件时,也会将其扫描的,没有加入库的可能也是私有的,所以不使用下列数组 // String[] strs = { "apk", "txt", "doc", "docx", "xls", "xlsx", // "ppt", "pptx", "pdf", "zip", "rar", "7z" }; // 事实上需要扫描的只有下面几个,但是如果所有app厂商足够细心的话,下面几个也不需要的 // 可以分别以mime取得下面的文件,分别为: // application/vnd.android.package-archive、text/plain、application/zip // 当然,不能信任他们 String[] strs = { "apk", "txt", "zip" }; if (strs == null || suffix == null) { return false; } for (int i = 0; i < strs.length; i++) { if (suffix.equals(strs[i])) { return true; } } return false; } @Override protected Boolean doInBackground(String... params) { scanFile(Environment.getExternalStorageDirectory()); String[] pathStrings = new String[paths.size()]; for (int i = 0; i < paths.size(); i++) { pathStrings[i] = paths.get(i); } MediaScannerConnection.scanFile(getActivity(), pathStrings, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { Log.i("scan", path); } }); return null; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); } } @Override public void toggleShowHidden() { // do nothing } @Override public void renameFile() { // TODO } @Override public void zipFile() { // do nothing } @Override public void addNewFile() { // do nothing if (listFragment != null) { listFragment.addNewFile(); } } @Override public void propertyFile() { if (listFragment != null) { listFragment.propertyFile(); } } }
NashLegend/LegendExplorer
src/net/nashlegend/legendexplorer/fragment/CategoriedFragment.java
4,614
// 获取可供程序使用的Block的数量
line_comment
zh-cn
package net.nashlegend.legendexplorer.fragment; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Timer; import java.util.TimerTask; import net.nashlegend.legendexplorer.MainActivity; import net.nashlegend.legendexplorer.consts.FileConst; import net.nashlegend.legendexplorer.utils.FileCategoryHelper; import net.nashlegend.legendexplorer.R; import net.nashlegend.legendutils.Tools.FileUtil; import android.annotation.SuppressLint; import android.app.FragmentTransaction; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.RelativeLayout; import android.widget.TextView; /** * 分类视图 * * @author NashLegend */ public class CategoriedFragment extends BaseFragment implements Explorable { protected View view; private static ScannerReceiver receiver; private FileListFragment listFragment; private View usedView; private View totalView; private TextView usageText; private RelativeLayout spaceLayout; private static HashMap<Integer, FileCategory> button2Category = new HashMap<Integer, FileCategory>(); static { button2Category.put(R.id.category_music, FileCategory.Music); button2Category.put(R.id.category_video, FileCategory.Video); button2Category.put(R.id.category_picture, FileCategory.Picture); button2Category.put(R.id.category_document, FileCategory.Doc); button2Category.put(R.id.category_zip, FileCategory.Zip); button2Category.put(R.id.category_apk, FileCategory.Apk); } public enum FileCategory { All, Music, Video, Picture, Doc, Zip, Apk, Other } public CategoriedFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(R.layout.layout_file_category, container, false); spaceLayout = (RelativeLayout) view.findViewById(R.id.spaceLayout); usedView = view.findViewById(R.id.view_used); totalView = view.findViewById(R.id.view_total); usageText = (TextView) view.findViewById(R.id.text_usage); setupClick(); updateUI(); registerReceiver(); } else { if (view.getParent() != null) { ((ViewGroup) view.getParent()).removeView(view); } } return view; } public void updateUI() { refreshData(); } public void refreshData() { spaceLayout.getViewTreeObserver().addOnGlobalLayoutListener( new OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @SuppressLint("NewApi") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT > 15) { spaceLayout.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { spaceLayout.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { try { StatFs statfs = new StatFs(Environment .getExternalStorageDirectory() .getAbsolutePath()); // 获取SDCard上BLOCK总数 long nTotalBlocks = statfs.getBlockCount(); // 获取SDCard上每个block的SIZE long nBlocSize = statfs.getBlockSize(); // 获取 <SUF> long nAvailaBlock = statfs.getAvailableBlocks(); // 计算SDCard 总容量大小MB long total = nTotalBlocks * nBlocSize; // 计算 SDCard 剩余大小MB long free = nAvailaBlock * nBlocSize; // 计算 SDCard 剩余大小MB long used = total - free; ViewGroup.LayoutParams params = usedView .getLayoutParams(); params.width = (int) (totalView.getWidth() * used / total); usedView.setLayoutParams(params); usageText.setText(FileUtil.convertStorage(used) + "/" + FileUtil.convertStorage(total)); } catch (IllegalArgumentException e) { } } } }); QueryTask task = new QueryTask(); task.execute(""); } class QueryTask extends AsyncTask<String, Integer, Integer> { @Override protected Integer doInBackground(String... params) { FileCategoryHelper.refreshCategoryInfo(getActivity()); return null; } @Override protected void onPostExecute(Integer result) { for (FileCategory fc : FileCategoryHelper.sCategories) { FileCategoryHelper.CategoryInfo categoryInfo = FileCategoryHelper .getCategoryInfos().get(fc); setCategoryCount(fc, categoryInfo.count); } } } public void setupClick() { setupClick(R.id.category_music); setupClick(R.id.category_video); setupClick(R.id.category_picture); setupClick(R.id.category_document); setupClick(R.id.category_zip); setupClick(R.id.category_apk); } private void setupClick(int id) { View button = view.findViewById(id); button.setOnClickListener(onClickListener); } private static int getCategoryCountId(FileCategory fc) { switch (fc) { case Music: return R.id.category_music_count; case Video: return R.id.category_video_count; case Picture: return R.id.category_picture_count; case Doc: return R.id.category_document_count; case Zip: return R.id.category_zip_count; case Apk: return R.id.category_apk_count; default: break; } return 0; } private void setCategoryCount(FileCategory fc, long count) { int id = getCategoryCountId(fc); if (id == 0) return; setTextView(id, "(" + count + ")"); } private void setTextView(int id, String t) { TextView text = (TextView) view.findViewById(id); text.setText(t); } public void registerReceiver() { receiver = new ScannerReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_MEDIA_MOUNTED); filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED); filter.addDataScheme("file"); getActivity().registerReceiver(receiver, filter); } View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View v) { FileCategory f = button2Category.get(v.getId()); if (f != null) { showCategoryList(f); } } }; public void showCategoryList(FileCategory f) { listFragment = new FileListFragment(); listFragment.setCategory(f); Bundle bundle = new Bundle(); bundle.putInt(FileConst.Extra_Explore_Type, FileConst.Value_Explore_Type_Categories); listFragment.setArguments(bundle); FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); transaction.replace(R.id.content_category, listFragment); transaction.commit(); Intent intent = new Intent(); int mask = 0; mask = MainActivity.FlagRefreshListItem | MainActivity.FlagToggleHiddleItem | MainActivity.FlagAddFileItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); } public boolean hideCategoryList() { if (listFragment == null) { return false; } else { FragmentTransaction transaction = getFragmentManager() .beginTransaction(); transaction .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE); transaction.remove(listFragment); transaction.commit(); listFragment = null; // frameLayout.setVisibility(View.GONE); Intent intent = new Intent(); int mask = MainActivity.FlagSearchFileItem | MainActivity.FlagToggleViewItem | MainActivity.FlagAddFileItem | MainActivity.FlagToggleHiddleItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); return true; } } private static final int MSG_FILE_CHANGED_TIMER = 100; private Timer timer; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case MSG_FILE_CHANGED_TIMER: updateUI(); break; } super.handleMessage(msg); } }; private boolean inSelectMode; synchronized public void notifyFileChanged() { if (timer != null) { timer.cancel(); } timer = new Timer(); timer.schedule(new TimerTask() { public void run() { timer = null; Message message = new Message(); message.what = MSG_FILE_CHANGED_TIMER; handler.sendMessage(message); } }, 1000); } @Override public void onStop() { super.onStop(); } @Override public void onDestroy() { try { getActivity().unregisterReceiver(receiver); } catch (Exception e) { } super.onDestroy(); } @Override public boolean doBackAction() { if (inSelectMode) { exitSelectMode(); return true; } if (listFragment != null) { hideCategoryList(); return true; } return false; } @Override public boolean doVeryAction(Intent intent) { String action = intent.getAction(); if (FileConst.Action_FileItem_Long_Click.equals(action)) { change2SelectMode(); } else if (FileConst.Action_FileItem_Unselect.equals(action)) { // selectAllButton.setOnCheckedChangeListener(null); // selectAllButton.setChecked(false); // selectAllButton.setOnCheckedChangeListener(this); } else if (FileConst.Action_File_Operation_Done.equals(action)) { exitSelectMode(); } else if (FileConst.Action_Search_File.equals(action)) { String query = intent .getStringExtra(FileConst.Key_Search_File_Query); searchFile(query); } else if (FileConst.Action_Quit_Search.equals(action)) { searchFile(""); } else if (FileConst.Action_Toggle_View_Mode.equals(action)) { toggleViewMode(); } else if (FileConst.Action_Refresh_FileList.equals(action)) { new Handler().post(new Runnable() { @Override public void run() { refreshFileList(); } }); } else if (FileConst.Action_Copy_File.equals(action)) { copyFile(); } else if (FileConst.Action_Move_File.equals(action)) { moveFile(); } else if (FileConst.Action_Delete_File.equals(action)) { deleteFile(); } else if (FileConst.Action_Rename_File.equals(action)) { renameFile(); } else if (FileConst.Action_Zip_File.equals(action)) { zipFile(); } else if (FileConst.Action_Property_File.equals(action)) { propertyFile(); } return false; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser) { Intent intent = new Intent(); int mask = 0; if (listFragment == null) { mask = MainActivity.FlagSearchFileItem | MainActivity.FlagToggleViewItem | MainActivity.FlagAddFileItem | MainActivity.FlagToggleHiddleItem; } else { mask = MainActivity.FlagRefreshListItem | MainActivity.FlagToggleHiddleItem | MainActivity.FlagAddFileItem; } intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); } } public void deleteFile() { if (listFragment != null) { listFragment.deleteFile(); } } public void moveFile() { if (listFragment != null) { listFragment.moveFile(); } } public void copyFile() { if (listFragment != null) { listFragment.copyFile(); } } /** * 调用系统扫描方法起不到什么作用,真的。除非发生如下情况: 1.所有app在修改、删除、添加、移动文件时都更新content. * 2.手动扫描全盘,但是慢 */ public void refreshFileList() { // Intent.ACTION_MEDIA_MOUNTED not allow after API19 // getActivity().sendBroadcast(new Intent( // Intent.ACTION_MEDIA_MOUNTED, // Uri.parse("file://" + Environment.getExternalStorageDirectory()))); // getActivity().sendBroadcast(new // Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, mediaMountUri)); // no use,it won't scan all files // MediaScannerConnection.scanFile(getActivity(), // new String[] { Environment.getExternalStorageDirectory() // .getAbsolutePath() }, null, // new MediaScannerConnection.OnScanCompletedListener() { // // @Override // public void onScanCompleted(String path, Uri uri) { // // } // }); refreshData(); if (listFragment != null) { listFragment.refreshFileList(); } } public void toggleViewMode() { if (listFragment != null) { listFragment.toggleViewMode(); } } public void searchFile(String query) { if (listFragment != null) { listFragment.searchFile(query); } } private void exitSelectMode() { if (listFragment != null) { // selectAllButton.setVisibility(View.GONE); inSelectMode = false; listFragment.exitSelectMode(); Intent intent = new Intent(); int mask = 0; mask = MainActivity.FlagRefreshListItem | MainActivity.FlagToggleHiddleItem | MainActivity.FlagAddFileItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_View_ActionBar); getActivity().sendBroadcast(intent); } } private void change2SelectMode() { if (listFragment != null) { // selectAllButton.setVisibility(View.VISIBLE); inSelectMode = true; listFragment.change2SelectMode(); Intent intent = new Intent(); int mask = 0; mask = MainActivity.FlagFavorItem | MainActivity.FlagUnzipFileItem | MainActivity.FlagZipFileItem | MainActivity.FlagRenameFileItem; intent.putExtra(FileConst.Extra_Menu_Mask, mask); intent.setAction(FileConst.Action_Set_File_Operation_ActionBar); getActivity().sendBroadcast(intent); } } public class ScannerReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_MEDIA_MOUNTED) || action.equals(Intent.ACTION_MEDIA_UNMOUNTED)) { notifyFileChanged(); } } } /** * 彻底地扫描全盘 * * @author NashLegend */ class ScanTask extends AsyncTask<String, Integer, Boolean> { ArrayList<String> paths = new ArrayList<String>(); public void scanFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file2 = files[i]; scanFile(file2); } } } else { String suffix = FileUtil.getFileSuffix(file); if (suffix.length() > 0 && isArrayContains(suffix)) { paths.add(file.getAbsolutePath()); } } } private boolean isArrayContains(String suffix) { // 事实上无需扫描媒体文件,如果后缀是媒体文件但是却没有被MediaScanner扫描到,说明这可能是一个私有的文件 // 比如在Android/data/com.xx.xxx/image里面有文件是不会想要被放进媒体库的,所以不使用下列数组 // String[] strs = { "mp3", "jpg", "jpeg", "bmp", "gif", "png", // "mp4","avi", "rmvk", "mkv", "wmv", "apk", "txt", "doc", "docx", // "xls", "xlsx", "ppt", "pptx", "pdf", "zip", "rar", "7z" }; // 有良心的app在使用doc类型的文件时,也会将其扫描的,没有加入库的可能也是私有的,所以不使用下列数组 // String[] strs = { "apk", "txt", "doc", "docx", "xls", "xlsx", // "ppt", "pptx", "pdf", "zip", "rar", "7z" }; // 事实上需要扫描的只有下面几个,但是如果所有app厂商足够细心的话,下面几个也不需要的 // 可以分别以mime取得下面的文件,分别为: // application/vnd.android.package-archive、text/plain、application/zip // 当然,不能信任他们 String[] strs = { "apk", "txt", "zip" }; if (strs == null || suffix == null) { return false; } for (int i = 0; i < strs.length; i++) { if (suffix.equals(strs[i])) { return true; } } return false; } @Override protected Boolean doInBackground(String... params) { scanFile(Environment.getExternalStorageDirectory()); String[] pathStrings = new String[paths.size()]; for (int i = 0; i < paths.size(); i++) { pathStrings[i] = paths.get(i); } MediaScannerConnection.scanFile(getActivity(), pathStrings, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { Log.i("scan", path); } }); return null; } @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); } } @Override public void toggleShowHidden() { // do nothing } @Override public void renameFile() { // TODO } @Override public void zipFile() { // do nothing } @Override public void addNewFile() { // do nothing if (listFragment != null) { listFragment.addNewFile(); } } @Override public void propertyFile() { if (listFragment != null) { listFragment.propertyFile(); } } }
true
33115_0
package net.nashlegend.legendutils.BuildIn; import java.util.ArrayList; import net.nashlegend.legendutils.Tools.DisplayUtil; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class WPLoading extends RelativeLayout { private int size = 10; private int delay = 300; private int duration = 3200; private String color = "#0000ff"; private AnimatorSet animatorSet = new AnimatorSet(); public WPLoading(Context context) { super(context); LayoutParams params0 = new LayoutParams( DisplayUtil.getScreenWidth(context), size); View view = new View(context); view.setLayoutParams(params0); addView(view); } public void startAnimate() { LayoutParams params = new LayoutParams(size, size); animatorSet = new AnimatorSet(); ArrayList<Animator> animators = new ArrayList<Animator>(); for (int i = 0; i < 5; i++) { View view = new View(getContext()); view.setBackgroundColor(Color.parseColor(color)); addView(view); view.setLayoutParams(params); view.setX(-size); ObjectAnimator headAnimator = ObjectAnimator.ofFloat(view, "x", view.getX(), DisplayUtil.getScreenWidth(getContext())); headAnimator.setDuration(duration); headAnimator .setInterpolator(new DecelerateAccelerateStopInterpolator()); headAnimator.setStartDelay(delay * i); headAnimator.setRepeatCount(-1); animators.add(headAnimator); } animatorSet.playTogether(animators); animatorSet.start(); } public WPLoading(Context context, AttributeSet attrs) { super(context, attrs); } public WPLoading(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void cancel() { animatorSet.end(); } // 先减速,再加速,再停止一会儿 class DecelerateAccelerateStopInterpolator implements android.view.animation.Interpolator { private float mFactor = 1.0f; private float tailFactor = 0.6f; public DecelerateAccelerateStopInterpolator() { } public DecelerateAccelerateStopInterpolator(float factor) { mFactor = factor; } public float getInterpolation(float x) { float result; if (x > tailFactor) { result = 1; } else if (x > tailFactor / 2) { result = (float) Math.pow( (x - tailFactor / 2) * 2 / tailFactor, 2 * mFactor) / 2 + 0.5f; } else { result = (float) (1.0f - Math.pow((tailFactor - 2 * x) / tailFactor, 2 * mFactor)) / 2; } return result; } } }
NashLegend/LegendUtils
src/net/nashlegend/legendutils/BuildIn/WPLoading.java
859
// 先减速,再加速,再停止一会儿
line_comment
zh-cn
package net.nashlegend.legendutils.BuildIn; import java.util.ArrayList; import net.nashlegend.legendutils.Tools.DisplayUtil; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class WPLoading extends RelativeLayout { private int size = 10; private int delay = 300; private int duration = 3200; private String color = "#0000ff"; private AnimatorSet animatorSet = new AnimatorSet(); public WPLoading(Context context) { super(context); LayoutParams params0 = new LayoutParams( DisplayUtil.getScreenWidth(context), size); View view = new View(context); view.setLayoutParams(params0); addView(view); } public void startAnimate() { LayoutParams params = new LayoutParams(size, size); animatorSet = new AnimatorSet(); ArrayList<Animator> animators = new ArrayList<Animator>(); for (int i = 0; i < 5; i++) { View view = new View(getContext()); view.setBackgroundColor(Color.parseColor(color)); addView(view); view.setLayoutParams(params); view.setX(-size); ObjectAnimator headAnimator = ObjectAnimator.ofFloat(view, "x", view.getX(), DisplayUtil.getScreenWidth(getContext())); headAnimator.setDuration(duration); headAnimator .setInterpolator(new DecelerateAccelerateStopInterpolator()); headAnimator.setStartDelay(delay * i); headAnimator.setRepeatCount(-1); animators.add(headAnimator); } animatorSet.playTogether(animators); animatorSet.start(); } public WPLoading(Context context, AttributeSet attrs) { super(context, attrs); } public WPLoading(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void cancel() { animatorSet.end(); } // 先减 <SUF> class DecelerateAccelerateStopInterpolator implements android.view.animation.Interpolator { private float mFactor = 1.0f; private float tailFactor = 0.6f; public DecelerateAccelerateStopInterpolator() { } public DecelerateAccelerateStopInterpolator(float factor) { mFactor = factor; } public float getInterpolation(float x) { float result; if (x > tailFactor) { result = 1; } else if (x > tailFactor / 2) { result = (float) Math.pow( (x - tailFactor / 2) * 2 / tailFactor, 2 * mFactor) / 2 + 0.5f; } else { result = (float) (1.0f - Math.pow((tailFactor - 2 * x) / tailFactor, 2 * mFactor)) / 2; } return result; } } }
false
42550_3
package net.nashlegend.sourcewall.model; import android.os.Parcel; /** * Created by NashLegend on 2014/10/31 0031 */ public class SubItem extends AceModel { public static final int Type_Group = -1;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Collections = 0;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Single_Channel = 1;//单项 public static final int Type_Private_Channel = 2;//私人频道,我的小组 public static final int Type_Subject_Channel = 3;//科学人学科频道 public static final int Section_Article = 0; public static final int Section_Post = 1; public static final int Section_Question = 2; public static final int Section_Favor = 3; private int section;//分组 比如科学人、小组、问答 private int type;//类型,比如Type_Collections,Type_Single_Channel private String name = "";//名字 比如Geek笑点低 private String value = "";//id 比如63 public SubItem(int section, int type, String name, String value) { setSection(section); setType(type); setName(name); setValue(value); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { if (name == null) { name = ""; } return name; } public void setName(String name) { this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getSection() { return section; } public void setSection(int section) { this.section = section; } @Override public boolean equals(Object o) { if (o != null && o instanceof SubItem) { SubItem sb = (SubItem) o; return sb.getName().equals(getName()) && sb.getSection() == getSection() && sb.getType() == getType() && sb.getValue().equals(getValue()); } return false; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.section); dest.writeInt(this.type); dest.writeString(this.name); dest.writeString(this.value); } protected SubItem(Parcel in) { this.section = in.readInt(); this.type = in.readInt(); this.name = in.readString(); this.value = in.readString(); } public static final Creator<SubItem> CREATOR = new Creator<SubItem>() { @Override public SubItem createFromParcel(Parcel source) { return new SubItem(source); } @Override public SubItem[] newArray(int size) { return new SubItem[size]; } }; }
NashLegend/SourceWall
app/src/main/java/net/nashlegend/sourcewall/model/SubItem.java
753
//私人频道,我的小组
line_comment
zh-cn
package net.nashlegend.sourcewall.model; import android.os.Parcel; /** * Created by NashLegend on 2014/10/31 0031 */ public class SubItem extends AceModel { public static final int Type_Group = -1;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Collections = 0;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Single_Channel = 1;//单项 public static final int Type_Private_Channel = 2;//私人 <SUF> public static final int Type_Subject_Channel = 3;//科学人学科频道 public static final int Section_Article = 0; public static final int Section_Post = 1; public static final int Section_Question = 2; public static final int Section_Favor = 3; private int section;//分组 比如科学人、小组、问答 private int type;//类型,比如Type_Collections,Type_Single_Channel private String name = "";//名字 比如Geek笑点低 private String value = "";//id 比如63 public SubItem(int section, int type, String name, String value) { setSection(section); setType(type); setName(name); setValue(value); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { if (name == null) { name = ""; } return name; } public void setName(String name) { this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getSection() { return section; } public void setSection(int section) { this.section = section; } @Override public boolean equals(Object o) { if (o != null && o instanceof SubItem) { SubItem sb = (SubItem) o; return sb.getName().equals(getName()) && sb.getSection() == getSection() && sb.getType() == getType() && sb.getValue().equals(getValue()); } return false; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.section); dest.writeInt(this.type); dest.writeString(this.name); dest.writeString(this.value); } protected SubItem(Parcel in) { this.section = in.readInt(); this.type = in.readInt(); this.name = in.readString(); this.value = in.readString(); } public static final Creator<SubItem> CREATOR = new Creator<SubItem>() { @Override public SubItem createFromParcel(Parcel source) { return new SubItem(source); } @Override public SubItem[] newArray(int size) { return new SubItem[size]; } }; }
false
36426_5
/** * */ package com.carryondown.app.util; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.amap.api.services.core.AMapException; public class ToastUtil { public static void show(Context context, String info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void show(Context context, int info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void showerror(Context context, int rCode){ try { switch (rCode) { //服务错误码 case 1001: throw new AMapException(AMapException.AMAP_SIGNATURE_ERROR); case 1002: throw new AMapException(AMapException.AMAP_INVALID_USER_KEY); case 1003: throw new AMapException(AMapException.AMAP_SERVICE_NOT_AVAILBALE); case 1004: throw new AMapException(AMapException.AMAP_DAILY_QUERY_OVER_LIMIT); case 1005: throw new AMapException(AMapException.AMAP_ACCESS_TOO_FREQUENT); case 1006: throw new AMapException(AMapException.AMAP_INVALID_USER_IP); case 1007: throw new AMapException(AMapException.AMAP_INVALID_USER_DOMAIN); case 1008: throw new AMapException(AMapException.AMAP_INVALID_USER_SCODE); case 1009: throw new AMapException(AMapException.AMAP_USERKEY_PLAT_NOMATCH); case 1010: throw new AMapException(AMapException.AMAP_IP_QUERY_OVER_LIMIT); case 1011: throw new AMapException(AMapException.AMAP_NOT_SUPPORT_HTTPS); case 1012: throw new AMapException(AMapException.AMAP_INSUFFICIENT_PRIVILEGES); case 1013: throw new AMapException(AMapException.AMAP_USER_KEY_RECYCLED); case 1100: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_ERROR); case 1101: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_DATA_ERROR); case 1102: throw new AMapException(AMapException.AMAP_ENGINE_CONNECT_TIMEOUT); case 1103: throw new AMapException(AMapException.AMAP_ENGINE_RETURN_TIMEOUT); case 1200: throw new AMapException(AMapException.AMAP_SERVICE_INVALID_PARAMS); case 1201: throw new AMapException(AMapException.AMAP_SERVICE_MISSING_REQUIRED_PARAMS); case 1202: throw new AMapException(AMapException.AMAP_SERVICE_ILLEGAL_REQUEST); case 1203: throw new AMapException(AMapException.AMAP_SERVICE_UNKNOWN_ERROR); //sdk返回错误 case 1800: throw new AMapException(AMapException.AMAP_CLIENT_ERRORCODE_MISSSING); case 1801: throw new AMapException(AMapException.AMAP_CLIENT_ERROR_PROTOCOL); case 1802: throw new AMapException(AMapException.AMAP_CLIENT_SOCKET_TIMEOUT_EXCEPTION); case 1803: throw new AMapException(AMapException.AMAP_CLIENT_URL_EXCEPTION); case 1804: throw new AMapException("网络异常,请检查您的网络是否连接"); // throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWHOST_EXCEPTION); case 1806: throw new AMapException(AMapException.AMAP_CLIENT_NETWORK_EXCEPTION); case 1900: throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWN_ERROR); case 1901: throw new AMapException(AMapException.AMAP_CLIENT_INVALID_PARAMETER); case 1902: throw new AMapException(AMapException.AMAP_CLIENT_IO_EXCEPTION); case 1903: throw new AMapException(AMapException.AMAP_CLIENT_NULLPOINT_EXCEPTION); //云图和附近错误码 case 2000: throw new AMapException(AMapException.AMAP_SERVICE_TABLEID_NOT_EXIST); case 2001: throw new AMapException(AMapException.AMAP_ID_NOT_EXIST); case 2002: throw new AMapException(AMapException.AMAP_SERVICE_MAINTENANCE); case 2003: throw new AMapException(AMapException.AMAP_ENGINE_TABLEID_NOT_EXIST); case 2100: throw new AMapException(AMapException.AMAP_NEARBY_INVALID_USERID); case 2101: throw new AMapException(AMapException.AMAP_NEARBY_KEY_NOT_BIND); case 2200: throw new AMapException(AMapException.AMAP_CLIENT_UPLOADAUTO_STARTED_ERROR); case 2201: throw new AMapException(AMapException.AMAP_CLIENT_USERID_ILLEGAL); case 2202: throw new AMapException(AMapException.AMAP_CLIENT_NEARBY_NULL_RESULT); case 2203: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_TOO_FREQUENT); case 2204: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_LOCATION_ERROR); //路径规划 case 3000: throw new AMapException(AMapException.AMAP_ROUTE_OUT_OF_SERVICE); case 3001: throw new AMapException(AMapException.AMAP_ROUTE_NO_ROADS_NEARBY); case 3002: throw new AMapException(AMapException.AMAP_ROUTE_FAIL); case 3003: throw new AMapException(AMapException.AMAP_OVER_DIRECTION_RANGE); //短传分享 case 4000: throw new AMapException(AMapException.AMAP_SHARE_LICENSE_IS_EXPIRED); case 4001: throw new AMapException(AMapException.AMAP_SHARE_FAILURE); default: Toast.makeText(context,"查询失败:"+rCode , Toast.LENGTH_LONG).show(); logError("查询失败", rCode); break; } } catch (Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); logError(e.getMessage(), rCode); } } private static void logError(String info, int errorCode) { print(LINE);//start print(" 错误信息 "); print(LINE);//title print(info); print("错误码: " + errorCode); print(" "); print("如果需要更多信息,请根据错误码到以下地址进行查询"); print(" http://lbs.amap.com/api/android-sdk/guide/map-tools/error-code/"); print("如若仍无法解决问题,请将全部log信息提交到工单系统,多谢合作"); print(LINE);//end } //log public static final String TAG = "AMAP_ERROR"; static final String LINE_CHAR="="; static final String BOARD_CHAR="|"; static final int LENGTH = 80; static String LINE; static{ StringBuilder sb = new StringBuilder(); for(int i = 0;i<LENGTH;i++){ sb .append(LINE_CHAR); } LINE = sb.toString(); } private static void printLog(String s){ if(s.length()<LENGTH-2){ StringBuilder sb = new StringBuilder(); sb.append(BOARD_CHAR).append(s); for(int i = 0 ;i <LENGTH-2-s.length();i++){ sb.append(" "); } sb.append(BOARD_CHAR); print(sb.toString()); }else{ String line = s.substring(0,LENGTH-2); print(BOARD_CHAR+line+BOARD_CHAR); printLog(s.substring(LENGTH-2)); } } private static void print(String s) { Log.i(TAG,s); } }
NativeMonkey/ofo
app/src/main/java/com/carryondown/app/util/ToastUtil.java
2,112
//短传分享
line_comment
zh-cn
/** * */ package com.carryondown.app.util; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.amap.api.services.core.AMapException; public class ToastUtil { public static void show(Context context, String info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void show(Context context, int info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void showerror(Context context, int rCode){ try { switch (rCode) { //服务错误码 case 1001: throw new AMapException(AMapException.AMAP_SIGNATURE_ERROR); case 1002: throw new AMapException(AMapException.AMAP_INVALID_USER_KEY); case 1003: throw new AMapException(AMapException.AMAP_SERVICE_NOT_AVAILBALE); case 1004: throw new AMapException(AMapException.AMAP_DAILY_QUERY_OVER_LIMIT); case 1005: throw new AMapException(AMapException.AMAP_ACCESS_TOO_FREQUENT); case 1006: throw new AMapException(AMapException.AMAP_INVALID_USER_IP); case 1007: throw new AMapException(AMapException.AMAP_INVALID_USER_DOMAIN); case 1008: throw new AMapException(AMapException.AMAP_INVALID_USER_SCODE); case 1009: throw new AMapException(AMapException.AMAP_USERKEY_PLAT_NOMATCH); case 1010: throw new AMapException(AMapException.AMAP_IP_QUERY_OVER_LIMIT); case 1011: throw new AMapException(AMapException.AMAP_NOT_SUPPORT_HTTPS); case 1012: throw new AMapException(AMapException.AMAP_INSUFFICIENT_PRIVILEGES); case 1013: throw new AMapException(AMapException.AMAP_USER_KEY_RECYCLED); case 1100: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_ERROR); case 1101: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_DATA_ERROR); case 1102: throw new AMapException(AMapException.AMAP_ENGINE_CONNECT_TIMEOUT); case 1103: throw new AMapException(AMapException.AMAP_ENGINE_RETURN_TIMEOUT); case 1200: throw new AMapException(AMapException.AMAP_SERVICE_INVALID_PARAMS); case 1201: throw new AMapException(AMapException.AMAP_SERVICE_MISSING_REQUIRED_PARAMS); case 1202: throw new AMapException(AMapException.AMAP_SERVICE_ILLEGAL_REQUEST); case 1203: throw new AMapException(AMapException.AMAP_SERVICE_UNKNOWN_ERROR); //sdk返回错误 case 1800: throw new AMapException(AMapException.AMAP_CLIENT_ERRORCODE_MISSSING); case 1801: throw new AMapException(AMapException.AMAP_CLIENT_ERROR_PROTOCOL); case 1802: throw new AMapException(AMapException.AMAP_CLIENT_SOCKET_TIMEOUT_EXCEPTION); case 1803: throw new AMapException(AMapException.AMAP_CLIENT_URL_EXCEPTION); case 1804: throw new AMapException("网络异常,请检查您的网络是否连接"); // throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWHOST_EXCEPTION); case 1806: throw new AMapException(AMapException.AMAP_CLIENT_NETWORK_EXCEPTION); case 1900: throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWN_ERROR); case 1901: throw new AMapException(AMapException.AMAP_CLIENT_INVALID_PARAMETER); case 1902: throw new AMapException(AMapException.AMAP_CLIENT_IO_EXCEPTION); case 1903: throw new AMapException(AMapException.AMAP_CLIENT_NULLPOINT_EXCEPTION); //云图和附近错误码 case 2000: throw new AMapException(AMapException.AMAP_SERVICE_TABLEID_NOT_EXIST); case 2001: throw new AMapException(AMapException.AMAP_ID_NOT_EXIST); case 2002: throw new AMapException(AMapException.AMAP_SERVICE_MAINTENANCE); case 2003: throw new AMapException(AMapException.AMAP_ENGINE_TABLEID_NOT_EXIST); case 2100: throw new AMapException(AMapException.AMAP_NEARBY_INVALID_USERID); case 2101: throw new AMapException(AMapException.AMAP_NEARBY_KEY_NOT_BIND); case 2200: throw new AMapException(AMapException.AMAP_CLIENT_UPLOADAUTO_STARTED_ERROR); case 2201: throw new AMapException(AMapException.AMAP_CLIENT_USERID_ILLEGAL); case 2202: throw new AMapException(AMapException.AMAP_CLIENT_NEARBY_NULL_RESULT); case 2203: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_TOO_FREQUENT); case 2204: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_LOCATION_ERROR); //路径规划 case 3000: throw new AMapException(AMapException.AMAP_ROUTE_OUT_OF_SERVICE); case 3001: throw new AMapException(AMapException.AMAP_ROUTE_NO_ROADS_NEARBY); case 3002: throw new AMapException(AMapException.AMAP_ROUTE_FAIL); case 3003: throw new AMapException(AMapException.AMAP_OVER_DIRECTION_RANGE); //短传 <SUF> case 4000: throw new AMapException(AMapException.AMAP_SHARE_LICENSE_IS_EXPIRED); case 4001: throw new AMapException(AMapException.AMAP_SHARE_FAILURE); default: Toast.makeText(context,"查询失败:"+rCode , Toast.LENGTH_LONG).show(); logError("查询失败", rCode); break; } } catch (Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); logError(e.getMessage(), rCode); } } private static void logError(String info, int errorCode) { print(LINE);//start print(" 错误信息 "); print(LINE);//title print(info); print("错误码: " + errorCode); print(" "); print("如果需要更多信息,请根据错误码到以下地址进行查询"); print(" http://lbs.amap.com/api/android-sdk/guide/map-tools/error-code/"); print("如若仍无法解决问题,请将全部log信息提交到工单系统,多谢合作"); print(LINE);//end } //log public static final String TAG = "AMAP_ERROR"; static final String LINE_CHAR="="; static final String BOARD_CHAR="|"; static final int LENGTH = 80; static String LINE; static{ StringBuilder sb = new StringBuilder(); for(int i = 0;i<LENGTH;i++){ sb .append(LINE_CHAR); } LINE = sb.toString(); } private static void printLog(String s){ if(s.length()<LENGTH-2){ StringBuilder sb = new StringBuilder(); sb.append(BOARD_CHAR).append(s); for(int i = 0 ;i <LENGTH-2-s.length();i++){ sb.append(" "); } sb.append(BOARD_CHAR); print(sb.toString()); }else{ String line = s.substring(0,LENGTH-2); print(BOARD_CHAR+line+BOARD_CHAR); printLog(s.substring(LENGTH-2)); } } private static void print(String s) { Log.i(TAG,s); } }
false
51191_6
package com.nt.backtrack; import java.util.*; /** * @author Enzo * @date : 2024/2/29 */ public class Permutation { // 回溯实现 public List<List<Integer>> permute(int[] nums) { // 定义保存结果的list List<List<Integer>> result = new ArrayList<>(); // 用一个int[8] 数组保存一组解 List<Integer> solution = new ArrayList<>(); // 从0位置开始填充数 backtrack1(nums, result, solution, 0); return result; } // 定义一个辅助集合 保存已经用过的数 Set<Integer> filledNums = new HashSet(); // 实现一个回溯方法 方便递归调用 private void backtrack1(int[] nums, List<List<Integer>> result, List<Integer> solution, int i) { int n = nums.length; // 手下们判断退出递归调用的场景 if (i >= n) { result.add(new ArrayList<>(solution)); }else { // 需要对i位置选填数填入 遍历数组中所有值 取没有用的数进行填充 for (int j = 0; j < n; j++) { if (!filledNums.contains(nums)){ //没用过直接填入 solution.add(nums[j]); filledNums.add(nums[j]); // 递归调用处理下一个位置 backtrack1(nums, result, solution, i + 1); // 回溯 回退状态 solution.remove(i); filledNums.remove(nums[j]); } } } } // 空间优化 public List<List<Integer>> permute1(int[] nums){ // 定义保存结果的List ArrayList<List<Integer>> result = new ArrayList<>(); // 用一个ArrayList保存一组解 ArrayList<Integer> solution = new ArrayList<>(); // 把nums复制到solution for (int num: nums) solution.add(num); // 从0位置开始填充数 backtrack(result, solution, 0); return result; } public void backtrack(List<List<Integer>> result, List<Integer> solution, int i){ int n = solution.size(); // 首先判断退出递归调用的场景 if (i >= n){ result.add(new ArrayList<>(solution)); } else { // 需要对i位置选数填入,遍历数组中所有数,取没有用过的数进行填充 for (int j = i; j < n; j++){ Collections.swap(solution, i, j); // 递归调用,处理后面的位置 backtrack(result, solution, i + 1); // 回溯 Collections.swap(solution, i, j); } } } public static void main(String[] args) { int[] nums = {1,2,3}; Permutation permutation = new Permutation(); List<List<Integer>> result = permutation.permute(nums); for (List<Integer> solution: result){ for (Integer num: solution){ System.out.print(num + "\t"); } System.out.println(); } } }
Natvel/algorithm
src/main/java/com/nt/backtrack/Permutation.java
761
// 实现一个回溯方法 方便递归调用
line_comment
zh-cn
package com.nt.backtrack; import java.util.*; /** * @author Enzo * @date : 2024/2/29 */ public class Permutation { // 回溯实现 public List<List<Integer>> permute(int[] nums) { // 定义保存结果的list List<List<Integer>> result = new ArrayList<>(); // 用一个int[8] 数组保存一组解 List<Integer> solution = new ArrayList<>(); // 从0位置开始填充数 backtrack1(nums, result, solution, 0); return result; } // 定义一个辅助集合 保存已经用过的数 Set<Integer> filledNums = new HashSet(); // 实现 <SUF> private void backtrack1(int[] nums, List<List<Integer>> result, List<Integer> solution, int i) { int n = nums.length; // 手下们判断退出递归调用的场景 if (i >= n) { result.add(new ArrayList<>(solution)); }else { // 需要对i位置选填数填入 遍历数组中所有值 取没有用的数进行填充 for (int j = 0; j < n; j++) { if (!filledNums.contains(nums)){ //没用过直接填入 solution.add(nums[j]); filledNums.add(nums[j]); // 递归调用处理下一个位置 backtrack1(nums, result, solution, i + 1); // 回溯 回退状态 solution.remove(i); filledNums.remove(nums[j]); } } } } // 空间优化 public List<List<Integer>> permute1(int[] nums){ // 定义保存结果的List ArrayList<List<Integer>> result = new ArrayList<>(); // 用一个ArrayList保存一组解 ArrayList<Integer> solution = new ArrayList<>(); // 把nums复制到solution for (int num: nums) solution.add(num); // 从0位置开始填充数 backtrack(result, solution, 0); return result; } public void backtrack(List<List<Integer>> result, List<Integer> solution, int i){ int n = solution.size(); // 首先判断退出递归调用的场景 if (i >= n){ result.add(new ArrayList<>(solution)); } else { // 需要对i位置选数填入,遍历数组中所有数,取没有用过的数进行填充 for (int j = i; j < n; j++){ Collections.swap(solution, i, j); // 递归调用,处理后面的位置 backtrack(result, solution, i + 1); // 回溯 Collections.swap(solution, i, j); } } } public static void main(String[] args) { int[] nums = {1,2,3}; Permutation permutation = new Permutation(); List<List<Integer>> result = permutation.permute(nums); for (List<Integer> solution: result){ for (Integer num: solution){ System.out.print(num + "\t"); } System.out.println(); } } }
true
18697_11
/** * 获取一个字符串 pattern 的部分匹配表 * * @param patternStr 用于模式匹配字符串 * @return 存储部分匹配表的每个子串的最长公共前后缀的 next数组 */ public static int[] kmpNext(String patternStr) { //将 patternStr 转为 字符数组形式 char[] patternArr = patternStr.toCharArray(); //预先创建一个next数组,用于存储部分匹配表的每个子串的最长公共前后缀 int[] next = new int[patternStr.length()]; /* 从第一个字符(对应索引为0)开始的子串,如果子串的长度为1,那么肯定最长公共前后缀为0 因为这唯一的一个字符既是第一个字符,又是最后一个字符,所以前后缀都不存在 -> 最长公共前后缀为0 */ next[0] = 0; /* len有两个作用: 1. 用于记录当前子串的最长公共前后缀长度 2. 同时知道当前子串的最长公共前后缀的前缀字符串对应索引 [0,len-1] /当前子串最长公共前缀字符串的下一个字符的索引 <-- 可以拿示例分析一下 */ int len = 0; //从第二个字符开始遍历,求索引在 [0,i] 的子串的最长公共前后缀长度 int i = 1; while (i < patternArr.length) { /* 1.已经知道了上一个子串 对应索引[0,i-1] 的最长公共前后缀长度为 len 的前缀字符串是 索引[0,len-1],对应相等的后缀字符串是 索引[i-len,i-1] 2.因此我们可以以 上一个子串的最长公共前后缀字符串 作为拼接参考 比较一下 patternArr[len] 与 patternArr[i] 是否相等 */ if (patternArr[len] == patternArr[i]) { /* 1.如果相等即 patternArr[len]==patternArr[i], 那么就可以确定当前子串的最长公共前后缀的 前缀字符串是 索引[0,len] ,对应相等的后缀字符串是 索引[i-len,i] 2.由于是拼接操作,那么当前子串的最长公共前后缀长度只需要在上一个子串的最长公共前后缀长度的基础上 +1 即可 即 next[i] = next[i-1] + 1 , 3.由于 len 是记录的子串的最长公共前后缀长度,对于当前我们所在的代码位置而言 len 还是记录的上一个子串的最长公共前后缀长度,因此: next[i] = next[i-1] + 1 等价于 next[i] = ++len */ // 等价于 next[i] = next[i-1] + 1 next[i] = ++len; //既然找到了索引在[0,i]的子串的最长公共前后缀字符串长度,那就 i+1 去判断以下一个字符结尾的子串的最长公共前后缀长度 i++; }else { /* 1.如果不相等 patternArr[len]!=patternArr[i] 我们想要求当前子串 对应索引[0,i] 的最长公共前后缀长度 我们就不能以 上一个子串的最长公共前后缀:前缀字符串pre 后缀字符串post (毫无疑问pre==post) 作为拼接参考 2.但可以思考一下: pre的最长公共前缀字符串: 索引 [ 0 , next[len-1] ) 是等于 post的最长公共后缀字符串:索引 [ i-next[len-1] , i ) 则我们 就以 pre的最长公共前缀字符串/post的最长公共后缀字符串 作为拼接参考 去判断 pre的最长公共前缀字符串的下一个字符patternArr[next[len-1]] 是否等于 post的最长公共后缀字符串的下一个字符patternArr[i] 3.在第 1,2 步分析的基础上 我们可以在判断出 patternArr[len]!=patternArr[i] 后, 不去执行第二步:patternArr[next[len-1]] 是否等于 patternArr[i], 可以先修改len的值:len = next[len-1],len就成了 pre的最长公共前缀字符串长度/post的最长公共后缀字符串长度, 修改完之后,再去判断下一个字符 是否相等,即 判断 patternArr[len] 是否等于 patternArr[i] 仔细观察,这不又是在判断 这个循环中 if-else 语句吗 4.关于 len 这个值,在循环开始时我们解释的是:上一个子串的最长公共前后缀字符串的长度 但实际上我们在这里改为 len = next[len-1] 表示上一个子串的最长公共前后缀字符串的最长公共前后缀字符串的长度 是没有问题的,等价于上一个子串的较小的公共前后缀字符串。 既然进入了 else 语句说明字符不相等,就不能以 上一个子串的最长公共前后缀字符串 作为 拼接参考,就应当去缩小参考范围。 */ if(len==0) { /* len为0说明上一个子串已经没有了公共前后缀字符串 则我们没有继续寻找的必要 --> 索引在[0, i]的当前子串的最长公共前后缀字符串长度就是0 */ next[i] = len; //继续寻找下一个字符串的最长公共前后缀字符串长度 i++; }else{ len = next[len - 1]; } } } return next; }
Ncu-uu/ACM-Training
算法/kmp/kmp.java
1,431
/* len为0说明上一个子串已经没有了公共前后缀字符串 则我们没有继续寻找的必要 --> 索引在[0, i]的当前子串的最长公共前后缀字符串长度就是0 */
block_comment
zh-cn
/** * 获取一个字符串 pattern 的部分匹配表 * * @param patternStr 用于模式匹配字符串 * @return 存储部分匹配表的每个子串的最长公共前后缀的 next数组 */ public static int[] kmpNext(String patternStr) { //将 patternStr 转为 字符数组形式 char[] patternArr = patternStr.toCharArray(); //预先创建一个next数组,用于存储部分匹配表的每个子串的最长公共前后缀 int[] next = new int[patternStr.length()]; /* 从第一个字符(对应索引为0)开始的子串,如果子串的长度为1,那么肯定最长公共前后缀为0 因为这唯一的一个字符既是第一个字符,又是最后一个字符,所以前后缀都不存在 -> 最长公共前后缀为0 */ next[0] = 0; /* len有两个作用: 1. 用于记录当前子串的最长公共前后缀长度 2. 同时知道当前子串的最长公共前后缀的前缀字符串对应索引 [0,len-1] /当前子串最长公共前缀字符串的下一个字符的索引 <-- 可以拿示例分析一下 */ int len = 0; //从第二个字符开始遍历,求索引在 [0,i] 的子串的最长公共前后缀长度 int i = 1; while (i < patternArr.length) { /* 1.已经知道了上一个子串 对应索引[0,i-1] 的最长公共前后缀长度为 len 的前缀字符串是 索引[0,len-1],对应相等的后缀字符串是 索引[i-len,i-1] 2.因此我们可以以 上一个子串的最长公共前后缀字符串 作为拼接参考 比较一下 patternArr[len] 与 patternArr[i] 是否相等 */ if (patternArr[len] == patternArr[i]) { /* 1.如果相等即 patternArr[len]==patternArr[i], 那么就可以确定当前子串的最长公共前后缀的 前缀字符串是 索引[0,len] ,对应相等的后缀字符串是 索引[i-len,i] 2.由于是拼接操作,那么当前子串的最长公共前后缀长度只需要在上一个子串的最长公共前后缀长度的基础上 +1 即可 即 next[i] = next[i-1] + 1 , 3.由于 len 是记录的子串的最长公共前后缀长度,对于当前我们所在的代码位置而言 len 还是记录的上一个子串的最长公共前后缀长度,因此: next[i] = next[i-1] + 1 等价于 next[i] = ++len */ // 等价于 next[i] = next[i-1] + 1 next[i] = ++len; //既然找到了索引在[0,i]的子串的最长公共前后缀字符串长度,那就 i+1 去判断以下一个字符结尾的子串的最长公共前后缀长度 i++; }else { /* 1.如果不相等 patternArr[len]!=patternArr[i] 我们想要求当前子串 对应索引[0,i] 的最长公共前后缀长度 我们就不能以 上一个子串的最长公共前后缀:前缀字符串pre 后缀字符串post (毫无疑问pre==post) 作为拼接参考 2.但可以思考一下: pre的最长公共前缀字符串: 索引 [ 0 , next[len-1] ) 是等于 post的最长公共后缀字符串:索引 [ i-next[len-1] , i ) 则我们 就以 pre的最长公共前缀字符串/post的最长公共后缀字符串 作为拼接参考 去判断 pre的最长公共前缀字符串的下一个字符patternArr[next[len-1]] 是否等于 post的最长公共后缀字符串的下一个字符patternArr[i] 3.在第 1,2 步分析的基础上 我们可以在判断出 patternArr[len]!=patternArr[i] 后, 不去执行第二步:patternArr[next[len-1]] 是否等于 patternArr[i], 可以先修改len的值:len = next[len-1],len就成了 pre的最长公共前缀字符串长度/post的最长公共后缀字符串长度, 修改完之后,再去判断下一个字符 是否相等,即 判断 patternArr[len] 是否等于 patternArr[i] 仔细观察,这不又是在判断 这个循环中 if-else 语句吗 4.关于 len 这个值,在循环开始时我们解释的是:上一个子串的最长公共前后缀字符串的长度 但实际上我们在这里改为 len = next[len-1] 表示上一个子串的最长公共前后缀字符串的最长公共前后缀字符串的长度 是没有问题的,等价于上一个子串的较小的公共前后缀字符串。 既然进入了 else 语句说明字符不相等,就不能以 上一个子串的最长公共前后缀字符串 作为 拼接参考,就应当去缩小参考范围。 */ if(len==0) { /* len <SUF>*/ next[i] = len; //继续寻找下一个字符串的最长公共前后缀字符串长度 i++; }else{ len = next[len - 1]; } } } return next; }
true
10201_0
package com.design.structural.decorator; /** * 你眼中的女神 */ public class YourGirl extends AbstractGirl { @Override protected String feature() { return "是一个女生"; } @Override protected String getDesc() { return "漂亮"; } }
NealLemon/design_patterns
src/main/java/com/design/structural/decorator/YourGirl.java
73
/** * 你眼中的女神 */
block_comment
zh-cn
package com.design.structural.decorator; /** * 你眼中 <SUF>*/ public class YourGirl extends AbstractGirl { @Override protected String feature() { return "是一个女生"; } @Override protected String getDesc() { return "漂亮"; } }
false
51169_1
/** * -*- coding: utf-8 -*- * * @Time : 2021/3/14 23:30 * @Author : NekoSilverfox * @FileName: template * @Software: IntelliJ IDEA * @Versions: v0.1 * @Github :https://github.com/NekoSilverFox */ import java.util.ArrayList; import java.util.Iterator; public class template { public static void main(String[] args) { show02(); } /* 创建集合对象,使用泛型 好处: 1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型 2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错) 弊端: 泛型是什么类型,只能存储什么类型的数据 */ private static void show02() { ArrayList<String> list = new ArrayList<>(); list.add("abc"); //list.add(1);//add(java.lang.String)in ArrayList cannot be applied to (int) //使用迭代器遍历list集合 Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s + "->" + s.length()); } } /* 创建集合对象,不使用泛型 好处: 集合不使用泛型,默认的类型就是Object类型,【可以存储任意类型的数据】 弊端: 不安全,会引发异常 */ private static void show01() { ArrayList list = new ArrayList(); list.add("abc"); list.add(1); //使用迭代器遍历list集合 //获取迭代器 Iterator it = list.iterator(); //使用迭代器中的方法hasNext和next遍历集合 while (it.hasNext()) { //取出元素也是Object类型 Object obj = it.next(); System.out.println(obj); //想要使用String类特有的方法,length获取字符串的长度;不能使用 多态 Object obj = "abc"; //需要向下转型 //会抛出ClassCastException类型转换异常,不能把Integer类型转换为String类型 String s = (String) obj; System.out.println(s.length()); } } }
NekoSilverFox/Java
190 - OOP_泛型编程/src/template.java
551
/* 创建集合对象,使用泛型 好处: 1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型 2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错) 弊端: 泛型是什么类型,只能存储什么类型的数据 */
block_comment
zh-cn
/** * -*- coding: utf-8 -*- * * @Time : 2021/3/14 23:30 * @Author : NekoSilverfox * @FileName: template * @Software: IntelliJ IDEA * @Versions: v0.1 * @Github :https://github.com/NekoSilverFox */ import java.util.ArrayList; import java.util.Iterator; public class template { public static void main(String[] args) { show02(); } /* 创建集 <SUF>*/ private static void show02() { ArrayList<String> list = new ArrayList<>(); list.add("abc"); //list.add(1);//add(java.lang.String)in ArrayList cannot be applied to (int) //使用迭代器遍历list集合 Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s + "->" + s.length()); } } /* 创建集合对象,不使用泛型 好处: 集合不使用泛型,默认的类型就是Object类型,【可以存储任意类型的数据】 弊端: 不安全,会引发异常 */ private static void show01() { ArrayList list = new ArrayList(); list.add("abc"); list.add(1); //使用迭代器遍历list集合 //获取迭代器 Iterator it = list.iterator(); //使用迭代器中的方法hasNext和next遍历集合 while (it.hasNext()) { //取出元素也是Object类型 Object obj = it.next(); System.out.println(obj); //想要使用String类特有的方法,length获取字符串的长度;不能使用 多态 Object obj = "abc"; //需要向下转型 //会抛出ClassCastException类型转换异常,不能把Integer类型转换为String类型 String s = (String) obj; System.out.println(s.length()); } } }
false
59127_5
package Reader; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.library.DicLibrary; import org.ansj.splitWord.analysis.DicAnalysis; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import javax.security.auth.login.AppConfigurationEntry; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; public class NovelRead { public static class ReaderMapper extends Mapper<LongWritable, Text, TextPair, IntWritable> { @Override protected void setup(Context context) throws IOException, InterruptedException { /** * 读取用户自定义字典 */ Configuration conf = context.getConfiguration(); String nameFile = context.getConfiguration().get("nameFile"); // System.out.print("--------" + nameFile); /*BufferedReader in = new BufferedReader(new InputStreamReader(FileSystem.get(context.getConfiguration()).open(new Path(nameFile)))); */ // StringBuffer buffer = new StringBuffer(); FileSystem fs = FileSystem.get(URI.create(nameFile), conf); FSDataInputStream fsr = fs.open(new Path(nameFile)); BufferedReader in = new BufferedReader(new InputStreamReader(fsr)); String name; while ((name = in.readLine()) != null) { DicLibrary.insert(DicLibrary.DEFAULT, name); } fsr.close(); in.close(); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { /** * key : offset * value : 一行文件内容 * * 读取小说内容,分词得到小说人物姓名,传出任意姓名对 * * key : <name1,name2> * value : 1 * **/ String data = value.toString(); Result res = DicAnalysis.parse(data); // 得到分词结果 List<Term> terms = res.getTerms(); List<String> nameList = new ArrayList<String>(); // 提取分词内容中的姓名 for (int i = 0; i < terms.size(); i++) { String word = terms.get(i).toString(); String wordNature = terms.get(i).getNatureStr(); if (wordNature.equals(DicLibrary.DEFAULT_NATURE)) { // 存储符合用户自定义词典中的内容 String name = word.substring(0, word.length()-11); if (name.equals("哈利波特") || name.equals("哈利·波特")) name = "哈利"; else if (name.equals("赫敏·简·格兰杰") || name.equals("赫敏·格兰杰") || name.equals("赫敏格兰杰")) name = "赫敏"; else if (name.equals("罗恩·比利尔斯·韦斯莱")) name = "罗恩"; nameList.add(name); } } // 两两不相同姓名对之间进行统计 int length = nameList.size(); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (!(nameList.get(i).equals(nameList.get(j)))) context.write(new TextPair(nameList.get(i), nameList.get(j)), new IntWritable(1)); } } } } public static class ReaderCombiner extends Reducer<TextPair, IntWritable, TextPair, IntWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * 合并重复姓名对 * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(key, new IntWritable(cnt)); } } public static class ReaderReducer extends Reducer<TextPair, IntWritable, Text, NullWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * key : <name1,name2> * values : times1,times2,... * * 统计同一个姓名对总共出现次数 * * key : name1,name2,times * value : null * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(new Text(key.toString() + "," + Integer.toString(cnt)), NullWritable.get()); } } }
NellyZhou/HadoopLab
CODE/src/main/java/Reader/NovelRead.java
1,227
// 得到分词结果
line_comment
zh-cn
package Reader; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.library.DicLibrary; import org.ansj.splitWord.analysis.DicAnalysis; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import javax.security.auth.login.AppConfigurationEntry; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; public class NovelRead { public static class ReaderMapper extends Mapper<LongWritable, Text, TextPair, IntWritable> { @Override protected void setup(Context context) throws IOException, InterruptedException { /** * 读取用户自定义字典 */ Configuration conf = context.getConfiguration(); String nameFile = context.getConfiguration().get("nameFile"); // System.out.print("--------" + nameFile); /*BufferedReader in = new BufferedReader(new InputStreamReader(FileSystem.get(context.getConfiguration()).open(new Path(nameFile)))); */ // StringBuffer buffer = new StringBuffer(); FileSystem fs = FileSystem.get(URI.create(nameFile), conf); FSDataInputStream fsr = fs.open(new Path(nameFile)); BufferedReader in = new BufferedReader(new InputStreamReader(fsr)); String name; while ((name = in.readLine()) != null) { DicLibrary.insert(DicLibrary.DEFAULT, name); } fsr.close(); in.close(); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { /** * key : offset * value : 一行文件内容 * * 读取小说内容,分词得到小说人物姓名,传出任意姓名对 * * key : <name1,name2> * value : 1 * **/ String data = value.toString(); Result res = DicAnalysis.parse(data); // 得到 <SUF> List<Term> terms = res.getTerms(); List<String> nameList = new ArrayList<String>(); // 提取分词内容中的姓名 for (int i = 0; i < terms.size(); i++) { String word = terms.get(i).toString(); String wordNature = terms.get(i).getNatureStr(); if (wordNature.equals(DicLibrary.DEFAULT_NATURE)) { // 存储符合用户自定义词典中的内容 String name = word.substring(0, word.length()-11); if (name.equals("哈利波特") || name.equals("哈利·波特")) name = "哈利"; else if (name.equals("赫敏·简·格兰杰") || name.equals("赫敏·格兰杰") || name.equals("赫敏格兰杰")) name = "赫敏"; else if (name.equals("罗恩·比利尔斯·韦斯莱")) name = "罗恩"; nameList.add(name); } } // 两两不相同姓名对之间进行统计 int length = nameList.size(); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (!(nameList.get(i).equals(nameList.get(j)))) context.write(new TextPair(nameList.get(i), nameList.get(j)), new IntWritable(1)); } } } } public static class ReaderCombiner extends Reducer<TextPair, IntWritable, TextPair, IntWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * 合并重复姓名对 * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(key, new IntWritable(cnt)); } } public static class ReaderReducer extends Reducer<TextPair, IntWritable, Text, NullWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * key : <name1,name2> * values : times1,times2,... * * 统计同一个姓名对总共出现次数 * * key : name1,name2,times * value : null * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(new Text(key.toString() + "," + Integer.toString(cnt)), NullWritable.get()); } } }
false
46491_47
package io.neoterm.framework; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import io.neoterm.App; import io.neoterm.framework.database.*; import io.neoterm.framework.database.bean.TableInfo; import io.neoterm.framework.reflection.Reflect; import io.neoterm.utils.NLog; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; /** * @author Lody, Kiva * <p> * 基于<b>DTO(DataToObject)</b>映射的数据库操纵模型. * 通过少量可选的注解,即可构造数据模型. * 增删查改异常轻松. * @version 1.4 */ public class NeoTermDatabase { /** * 缓存创建的数据库,以便防止数据库冲突. */ private static final Map<String, NeoTermDatabase> DAO_MAP = new HashMap<>(); /** * 数据库配置 */ private NeoTermSQLiteConfig neoTermSQLiteConfig; /** * 内部操纵的数据库执行类 */ private SQLiteDatabase db; /** * 默认构造器 * * @param config */ private NeoTermDatabase(NeoTermSQLiteConfig config) { this.neoTermSQLiteConfig = config; String saveDir = config.getSaveDir(); if (saveDir != null && saveDir.trim().length() > 0) { this.db = createDataBaseFileOnSDCard(saveDir, config.getDatabaseName()); } else { this.db = new SQLiteDataBaseHelper(App.Companion.get() .getApplicationContext() .getApplicationContext(), config) .getWritableDatabase(); } } /** * 根据配置取得用于操纵数据库的WeLikeDao实例 * * @param config * @return */ public static NeoTermDatabase instance(NeoTermSQLiteConfig config) { if (config.getDatabaseName() == null) { throw new IllegalArgumentException("DBName is null in SqLiteConfig."); } NeoTermDatabase dao = DAO_MAP.get(config.getDatabaseName()); if (dao == null) { dao = new NeoTermDatabase(config); synchronized (DAO_MAP) { DAO_MAP.put(config.getDatabaseName(), dao); } } else {//更换配置 dao.applyConfig(config); } return dao; } /** * 根据默认配置取得操纵数据库的WeLikeDao实例 * * @return */ public static NeoTermDatabase instance() { return instance(NeoTermSQLiteConfig.DEFAULT_CONFIG); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbName * @return */ public static NeoTermDatabase instance(String dbName) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseName(dbName); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbVersion * @return */ public static NeoTermDatabase instance(int dbVersion) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseVersion(dbVersion); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param listener * @return */ public static NeoTermDatabase instance(OnDatabaseUpgradedListener listener) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setOnDatabaseUpgradedListener(listener); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbName * @param dbVersion * @return */ public static NeoTermDatabase instance(String dbName, int dbVersion) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseName(dbName); config.setDatabaseVersion(dbVersion); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbName * @param dbVersion * @param listener * @return */ public static NeoTermDatabase instance(String dbName, int dbVersion, OnDatabaseUpgradedListener listener) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseName(dbName); config.setDatabaseVersion(dbVersion); config.setOnDatabaseUpgradedListener(listener); return instance(config); } /** * 配置为新的参数(不改变数据库名). * * @param config */ private void applyConfig(NeoTermSQLiteConfig config) { this.neoTermSQLiteConfig.debugMode = config.debugMode; this.neoTermSQLiteConfig.setOnDatabaseUpgradedListener(config.getOnDatabaseUpgradedListener()); } public void release() { DAO_MAP.clear(); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.d("缓存的DAO已经全部清除,将不占用内存."); } } /** * 在SD卡的指定目录上创建数据库文件 * * @param sdcardPath sd卡路径 * @param dbFileName 数据库文件名 * @return */ private SQLiteDatabase createDataBaseFileOnSDCard(String sdcardPath, String dbFileName) { File dbFile = new File(sdcardPath, dbFileName); if (!dbFile.exists()) { try { if (dbFile.createNewFile()) { return SQLiteDatabase.openOrCreateDatabase(dbFile, null); } } catch (IOException e) { throw new RuntimeException("无法在 " + dbFile.getAbsolutePath() + "创建DB文件."); } } else { //数据库文件已经存在,无需再次创建. return SQLiteDatabase.openOrCreateDatabase(dbFile, null); } return null; } /** * 如果表不存在,需要创建它. * * @param clazz */ private void createTableIfNeed(Class<?> clazz) { TableInfo tableInfo = TableHelper.from(clazz); if (tableInfo.isCreate) { return; } if (!isTableExist(tableInfo)) { String sql = SQLStatementHelper.createTable(tableInfo); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(sql); } db.execSQL(sql); Method afterTableCreateMethod = tableInfo.afterTableCreateMethod; if (afterTableCreateMethod != null) { //如果afterTableMethod存在,就调用它 try { afterTableCreateMethod.invoke(null, this); } catch (Throwable ignore) { ignore.printStackTrace(); } } } } /** * 判断表是否存在? * * @param table 需要盘的的表 * @return */ private boolean isTableExist(TableInfo table) { String sql = "SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name ='" + table.tableName + "' "; try (Cursor cursor = db.rawQuery(sql, null)) { if (cursor != null && cursor.moveToNext()) { int count = cursor.getInt(0); if (count > 0) { return true; } } } catch (Throwable ignore) { ignore.printStackTrace(); } return false; } /** * 删除全部的表 */ public void dropAllTable() { try (Cursor cursor = db.rawQuery( "SELECT name FROM sqlite_master WHERE type ='table'", null)) { if (cursor != null) { cursor.moveToFirst(); while (cursor.moveToNext()) { try { dropTable(cursor.getString(0)); } catch (SQLException ignore) { ignore.printStackTrace(); } } } } } /** * 取得数据库中的表的数量 * * @return 表的数量 */ public int tableCount() { try (Cursor cursor = db.rawQuery( "SELECT name FROM sqlite_master WHERE type ='table'", null)) { return cursor == null ? 0 : cursor.getCount(); } } /** * 取得数据库中的所有表名组成的List. * * @return */ public List<String> getTableList() { try (Cursor cursor = db.rawQuery( "SELECT name FROM sqlite_master WHERE type ='table'", null)) { List<String> tableList = new ArrayList<>(); if (cursor != null) { cursor.moveToFirst(); while (cursor.moveToNext()) { tableList.add(cursor.getString(0)); } } return tableList; } } /** * 删除一张表 * * @param beanClass 表所对应的类 */ public void dropTable(Class<?> beanClass) { TableInfo tableInfo = TableHelper.from(beanClass); dropTable(tableInfo.tableName); tableInfo.isCreate = false; } /** * 删除一张表 * * @param tableName 表名 */ public void dropTable(String tableName) { String statement = "DROP TABLE IF EXISTS " + tableName; if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } db.execSQL(statement); TableInfo tableInfo = TableHelper.findTableInfoByName(tableName); if (tableInfo != null) { tableInfo.isCreate = false; } } /** * 存储一个Bean. * * @param bean * @return */ public <T> NeoTermDatabase saveBean(T bean) { createTableIfNeed(bean.getClass()); String statement = SQLStatementHelper.insertIntoTable(bean); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } db.execSQL(statement); return this; } /** * 存储多个Bean. * * @param beans * @return */ public NeoTermDatabase saveBeans(Object[] beans) { for (Object o : beans) { saveBean(o); } return this; } /** * 存储多个Bean. * * @param beans * @return */ public <T> NeoTermDatabase saveBeans(List<T> beans) { for (Object o : beans) { saveBean(o); } return this; } /** * 寻找Bean对应的全部数据 * * @param clazz * @param <T> * @return */ public <T> List<T> findAll(Class<?> clazz) { createTableIfNeed(clazz); TableInfo tableInfo = TableHelper.from(clazz); String statement = SQLStatementHelper.selectTable(tableInfo.tableName); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } List<T> list = new ArrayList<T>(); try (Cursor cursor = db.rawQuery(statement, null)) { if (cursor == null) { // DO NOT RETURN NULL // null checks are ugly! return Collections.emptyList(); } while (cursor.moveToNext()) { T object = Reflect.on(clazz).create().get(); if (tableInfo.containID) { DatabaseDataType dataType = SQLTypeParser.getDataType(tableInfo.primaryField); String idFieldName = tableInfo.primaryField.getName(); ValueHelper.setKeyValue(cursor, object, tableInfo.primaryField, dataType, cursor.getColumnIndex(idFieldName)); } for (Field field : tableInfo.fieldToDataTypeMap.keySet()) { DatabaseDataType dataType = tableInfo.fieldToDataTypeMap.get(field); ValueHelper.setKeyValue(cursor, object, field, dataType, cursor.getColumnIndex(field.getName())); } list.add(object); } return list; } } /** * 根据where语句寻找Bean * * @param clazz * @param <T> * @return */ public <T> List<T> findBeanByWhere(Class<?> clazz, String where) { createTableIfNeed(clazz); TableInfo tableInfo = TableHelper.from(clazz); String statement = SQLStatementHelper.findByWhere(tableInfo, where); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } List<T> list = new ArrayList<>(); try (Cursor cursor = db.rawQuery(statement, null)) { if (cursor == null) { // DO NOT RETURN NULL // null checks are ugly! return Collections.emptyList(); } while (cursor.moveToNext()) { T object = Reflect.on(clazz).create().get(); if (tableInfo.containID) { DatabaseDataType dataType = SQLTypeParser.getDataType(tableInfo.primaryField); String idFieldName = tableInfo.primaryField.getName(); ValueHelper.setKeyValue(cursor, object, tableInfo.primaryField, dataType, cursor.getColumnIndex(idFieldName)); } for (Field field : tableInfo.fieldToDataTypeMap.keySet()) { DatabaseDataType dataType = tableInfo.fieldToDataTypeMap.get(field); ValueHelper.setKeyValue(cursor, object, field, dataType, cursor.getColumnIndex(field.getName())); } list.add(object); } return list; } } public <T> T findOneBeanByWhere(Class<?> clazz, String where) { List<T> list = findBeanByWhere(clazz, where); if (!list.isEmpty()) { return list.get(0); } return null; } /** * 根据where语句删除Bean * * @param clazz * @return */ public NeoTermDatabase deleteBeanByWhere(Class<?> clazz, String where) { createTableIfNeed(clazz); TableInfo tableInfo = TableHelper.from(clazz); String statement = SQLStatementHelper.deleteByWhere(tableInfo, where); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } try { db.execSQL(statement); } catch (SQLException ignore) { ignore.printStackTrace(); } return this; } /** * 删除指定ID的bean * * @param tableClass * @param id * @return 删除的Bean */ public NeoTermDatabase deleteBeanByID(Class<?> tableClass, Object id) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); DatabaseDataType dataType = SQLTypeParser.getDataType(id.getClass()); if (dataType != null && tableInfo.primaryField != null) { //判断ID类型是否与数据类型匹配 boolean match = SQLTypeParser.matchType(tableInfo.primaryField, dataType); if (!match) {//不匹配,抛出异常 throw new IllegalArgumentException("类型 " + id.getClass().getName() + " 不是主键的类型,主键的类型应该为 " + tableInfo.primaryField.getType().getName()); } } String idValue = ValueHelper.valueToString(dataType, id); String statement = SQLStatementHelper.deleteByWhere(tableInfo, tableInfo.primaryField == null ? "_id" : tableInfo.primaryField.getName() + " = " + idValue); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } try { db.execSQL(statement); } catch (SQLException ignore) { ignore.printStackTrace(); //删除失败 } return this; } /** * 根据给定的where更新数据 * * @param tableClass * @param where * @param bean * @return */ public NeoTermDatabase updateByWhere(Class<?> tableClass, String where, Object bean) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); String statement = SQLStatementHelper.updateByWhere(tableInfo, bean, where); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.d(statement); } db.execSQL(statement); return this; } /** * 根据给定的id更新数据 * * @param tableClass * @param id * @param bean * @return */ public NeoTermDatabase updateByID(Class<?> tableClass, Object id, Object bean) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); StringBuilder subStatement = new StringBuilder(); if (tableInfo.containID) { subStatement.append(tableInfo.primaryField.getName()).append(" = ").append(ValueHelper.valueToString(SQLTypeParser.getDataType(tableInfo.primaryField), id)); } else { subStatement.append("_id = ").append((int) id); } updateByWhere(tableClass, subStatement.toString(), bean); return this; } /** * 根据ID查找Bean * * @param tableClass * @param id * @param <T> * @return */ public <T> T findBeanByID(Class<?> tableClass, Object id) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); DatabaseDataType dataType = SQLTypeParser.getDataType(id.getClass()); if (dataType == null) { return null; } // 判断ID类型是否与数据类型匹配 boolean match = SQLTypeParser.matchType(tableInfo.primaryField, dataType) || tableInfo.primaryField == null; if (!match) {// 不匹配,抛出异常 throw new IllegalArgumentException("Type " + id.getClass().getName() + " is not the primary key, expecting " + tableInfo.primaryField.getType().getName()); } String idValue = ValueHelper.valueToString(dataType, id); String statement = SQLStatementHelper.findByWhere(tableInfo, tableInfo.primaryField == null ? "_id" : tableInfo.primaryField.getName() + " = " + idValue); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } try (Cursor cursor = db.rawQuery(statement, null)) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); T bean = Reflect.on(tableClass).create().get(); for (Field field : tableInfo.fieldToDataTypeMap.keySet()) { DatabaseDataType fieldType = tableInfo.fieldToDataTypeMap.get(field); ValueHelper.setKeyValue(cursor, bean, field, fieldType, cursor.getColumnIndex(field.getName())); } try { Reflect.on(bean).set(tableInfo.containID ? tableInfo.primaryField.getName() : "_id", id); } catch (Throwable ignore) { // 我们允许Bean没有id字段,因此此异常可以忽略 } return bean; } return null; } } /** * 通过 VACUUM 命令压缩数据库 */ public void vacuum() { db.execSQL("VACUUM"); } /** * 调用本方法会释放当前数据库占用的内存, * 调用后请确保你不会在接下来的代码中继续用到本实例. */ public void destroy() { DAO_MAP.remove(this); this.neoTermSQLiteConfig = null; this.db = null; } /** * 取得内部操纵的SqliteDatabase. * * @return */ public SQLiteDatabase getDatabase() { return db; } /** * 内部数据库监听器,负责派发接口. */ private class SQLiteDataBaseHelper extends SQLiteOpenHelper { private final OnDatabaseUpgradedListener onDatabaseUpgradedListener; private final boolean defaultDropAllTables; public SQLiteDataBaseHelper(Context context, NeoTermSQLiteConfig config) { super(context, config.getDatabaseName(), null, config.getDatabaseVersion()); this.onDatabaseUpgradedListener = config.getOnDatabaseUpgradedListener(); this.defaultDropAllTables = config.isDefaultDropAllTables(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (onDatabaseUpgradedListener != null) { onDatabaseUpgradedListener.onDatabaseUpgraded(db, oldVersion, newVersion); } else if (defaultDropAllTables) { // 干掉所有的表 dropAllTable(); } } } }
NeoTerrm/NeoTerm
app/src/main/java/io/neoterm/framework/NeoTermDatabase.java
4,782
/** * 内部数据库监听器,负责派发接口. */
block_comment
zh-cn
package io.neoterm.framework; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import io.neoterm.App; import io.neoterm.framework.database.*; import io.neoterm.framework.database.bean.TableInfo; import io.neoterm.framework.reflection.Reflect; import io.neoterm.utils.NLog; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; /** * @author Lody, Kiva * <p> * 基于<b>DTO(DataToObject)</b>映射的数据库操纵模型. * 通过少量可选的注解,即可构造数据模型. * 增删查改异常轻松. * @version 1.4 */ public class NeoTermDatabase { /** * 缓存创建的数据库,以便防止数据库冲突. */ private static final Map<String, NeoTermDatabase> DAO_MAP = new HashMap<>(); /** * 数据库配置 */ private NeoTermSQLiteConfig neoTermSQLiteConfig; /** * 内部操纵的数据库执行类 */ private SQLiteDatabase db; /** * 默认构造器 * * @param config */ private NeoTermDatabase(NeoTermSQLiteConfig config) { this.neoTermSQLiteConfig = config; String saveDir = config.getSaveDir(); if (saveDir != null && saveDir.trim().length() > 0) { this.db = createDataBaseFileOnSDCard(saveDir, config.getDatabaseName()); } else { this.db = new SQLiteDataBaseHelper(App.Companion.get() .getApplicationContext() .getApplicationContext(), config) .getWritableDatabase(); } } /** * 根据配置取得用于操纵数据库的WeLikeDao实例 * * @param config * @return */ public static NeoTermDatabase instance(NeoTermSQLiteConfig config) { if (config.getDatabaseName() == null) { throw new IllegalArgumentException("DBName is null in SqLiteConfig."); } NeoTermDatabase dao = DAO_MAP.get(config.getDatabaseName()); if (dao == null) { dao = new NeoTermDatabase(config); synchronized (DAO_MAP) { DAO_MAP.put(config.getDatabaseName(), dao); } } else {//更换配置 dao.applyConfig(config); } return dao; } /** * 根据默认配置取得操纵数据库的WeLikeDao实例 * * @return */ public static NeoTermDatabase instance() { return instance(NeoTermSQLiteConfig.DEFAULT_CONFIG); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbName * @return */ public static NeoTermDatabase instance(String dbName) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseName(dbName); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbVersion * @return */ public static NeoTermDatabase instance(int dbVersion) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseVersion(dbVersion); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param listener * @return */ public static NeoTermDatabase instance(OnDatabaseUpgradedListener listener) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setOnDatabaseUpgradedListener(listener); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbName * @param dbVersion * @return */ public static NeoTermDatabase instance(String dbName, int dbVersion) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseName(dbName); config.setDatabaseVersion(dbVersion); return instance(config); } /** * 取得操纵数据库的WeLikeDao实例 * * @param dbName * @param dbVersion * @param listener * @return */ public static NeoTermDatabase instance(String dbName, int dbVersion, OnDatabaseUpgradedListener listener) { NeoTermSQLiteConfig config = new NeoTermSQLiteConfig(); config.setDatabaseName(dbName); config.setDatabaseVersion(dbVersion); config.setOnDatabaseUpgradedListener(listener); return instance(config); } /** * 配置为新的参数(不改变数据库名). * * @param config */ private void applyConfig(NeoTermSQLiteConfig config) { this.neoTermSQLiteConfig.debugMode = config.debugMode; this.neoTermSQLiteConfig.setOnDatabaseUpgradedListener(config.getOnDatabaseUpgradedListener()); } public void release() { DAO_MAP.clear(); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.d("缓存的DAO已经全部清除,将不占用内存."); } } /** * 在SD卡的指定目录上创建数据库文件 * * @param sdcardPath sd卡路径 * @param dbFileName 数据库文件名 * @return */ private SQLiteDatabase createDataBaseFileOnSDCard(String sdcardPath, String dbFileName) { File dbFile = new File(sdcardPath, dbFileName); if (!dbFile.exists()) { try { if (dbFile.createNewFile()) { return SQLiteDatabase.openOrCreateDatabase(dbFile, null); } } catch (IOException e) { throw new RuntimeException("无法在 " + dbFile.getAbsolutePath() + "创建DB文件."); } } else { //数据库文件已经存在,无需再次创建. return SQLiteDatabase.openOrCreateDatabase(dbFile, null); } return null; } /** * 如果表不存在,需要创建它. * * @param clazz */ private void createTableIfNeed(Class<?> clazz) { TableInfo tableInfo = TableHelper.from(clazz); if (tableInfo.isCreate) { return; } if (!isTableExist(tableInfo)) { String sql = SQLStatementHelper.createTable(tableInfo); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(sql); } db.execSQL(sql); Method afterTableCreateMethod = tableInfo.afterTableCreateMethod; if (afterTableCreateMethod != null) { //如果afterTableMethod存在,就调用它 try { afterTableCreateMethod.invoke(null, this); } catch (Throwable ignore) { ignore.printStackTrace(); } } } } /** * 判断表是否存在? * * @param table 需要盘的的表 * @return */ private boolean isTableExist(TableInfo table) { String sql = "SELECT COUNT(*) AS c FROM sqlite_master WHERE type ='table' AND name ='" + table.tableName + "' "; try (Cursor cursor = db.rawQuery(sql, null)) { if (cursor != null && cursor.moveToNext()) { int count = cursor.getInt(0); if (count > 0) { return true; } } } catch (Throwable ignore) { ignore.printStackTrace(); } return false; } /** * 删除全部的表 */ public void dropAllTable() { try (Cursor cursor = db.rawQuery( "SELECT name FROM sqlite_master WHERE type ='table'", null)) { if (cursor != null) { cursor.moveToFirst(); while (cursor.moveToNext()) { try { dropTable(cursor.getString(0)); } catch (SQLException ignore) { ignore.printStackTrace(); } } } } } /** * 取得数据库中的表的数量 * * @return 表的数量 */ public int tableCount() { try (Cursor cursor = db.rawQuery( "SELECT name FROM sqlite_master WHERE type ='table'", null)) { return cursor == null ? 0 : cursor.getCount(); } } /** * 取得数据库中的所有表名组成的List. * * @return */ public List<String> getTableList() { try (Cursor cursor = db.rawQuery( "SELECT name FROM sqlite_master WHERE type ='table'", null)) { List<String> tableList = new ArrayList<>(); if (cursor != null) { cursor.moveToFirst(); while (cursor.moveToNext()) { tableList.add(cursor.getString(0)); } } return tableList; } } /** * 删除一张表 * * @param beanClass 表所对应的类 */ public void dropTable(Class<?> beanClass) { TableInfo tableInfo = TableHelper.from(beanClass); dropTable(tableInfo.tableName); tableInfo.isCreate = false; } /** * 删除一张表 * * @param tableName 表名 */ public void dropTable(String tableName) { String statement = "DROP TABLE IF EXISTS " + tableName; if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } db.execSQL(statement); TableInfo tableInfo = TableHelper.findTableInfoByName(tableName); if (tableInfo != null) { tableInfo.isCreate = false; } } /** * 存储一个Bean. * * @param bean * @return */ public <T> NeoTermDatabase saveBean(T bean) { createTableIfNeed(bean.getClass()); String statement = SQLStatementHelper.insertIntoTable(bean); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } db.execSQL(statement); return this; } /** * 存储多个Bean. * * @param beans * @return */ public NeoTermDatabase saveBeans(Object[] beans) { for (Object o : beans) { saveBean(o); } return this; } /** * 存储多个Bean. * * @param beans * @return */ public <T> NeoTermDatabase saveBeans(List<T> beans) { for (Object o : beans) { saveBean(o); } return this; } /** * 寻找Bean对应的全部数据 * * @param clazz * @param <T> * @return */ public <T> List<T> findAll(Class<?> clazz) { createTableIfNeed(clazz); TableInfo tableInfo = TableHelper.from(clazz); String statement = SQLStatementHelper.selectTable(tableInfo.tableName); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } List<T> list = new ArrayList<T>(); try (Cursor cursor = db.rawQuery(statement, null)) { if (cursor == null) { // DO NOT RETURN NULL // null checks are ugly! return Collections.emptyList(); } while (cursor.moveToNext()) { T object = Reflect.on(clazz).create().get(); if (tableInfo.containID) { DatabaseDataType dataType = SQLTypeParser.getDataType(tableInfo.primaryField); String idFieldName = tableInfo.primaryField.getName(); ValueHelper.setKeyValue(cursor, object, tableInfo.primaryField, dataType, cursor.getColumnIndex(idFieldName)); } for (Field field : tableInfo.fieldToDataTypeMap.keySet()) { DatabaseDataType dataType = tableInfo.fieldToDataTypeMap.get(field); ValueHelper.setKeyValue(cursor, object, field, dataType, cursor.getColumnIndex(field.getName())); } list.add(object); } return list; } } /** * 根据where语句寻找Bean * * @param clazz * @param <T> * @return */ public <T> List<T> findBeanByWhere(Class<?> clazz, String where) { createTableIfNeed(clazz); TableInfo tableInfo = TableHelper.from(clazz); String statement = SQLStatementHelper.findByWhere(tableInfo, where); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } List<T> list = new ArrayList<>(); try (Cursor cursor = db.rawQuery(statement, null)) { if (cursor == null) { // DO NOT RETURN NULL // null checks are ugly! return Collections.emptyList(); } while (cursor.moveToNext()) { T object = Reflect.on(clazz).create().get(); if (tableInfo.containID) { DatabaseDataType dataType = SQLTypeParser.getDataType(tableInfo.primaryField); String idFieldName = tableInfo.primaryField.getName(); ValueHelper.setKeyValue(cursor, object, tableInfo.primaryField, dataType, cursor.getColumnIndex(idFieldName)); } for (Field field : tableInfo.fieldToDataTypeMap.keySet()) { DatabaseDataType dataType = tableInfo.fieldToDataTypeMap.get(field); ValueHelper.setKeyValue(cursor, object, field, dataType, cursor.getColumnIndex(field.getName())); } list.add(object); } return list; } } public <T> T findOneBeanByWhere(Class<?> clazz, String where) { List<T> list = findBeanByWhere(clazz, where); if (!list.isEmpty()) { return list.get(0); } return null; } /** * 根据where语句删除Bean * * @param clazz * @return */ public NeoTermDatabase deleteBeanByWhere(Class<?> clazz, String where) { createTableIfNeed(clazz); TableInfo tableInfo = TableHelper.from(clazz); String statement = SQLStatementHelper.deleteByWhere(tableInfo, where); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } try { db.execSQL(statement); } catch (SQLException ignore) { ignore.printStackTrace(); } return this; } /** * 删除指定ID的bean * * @param tableClass * @param id * @return 删除的Bean */ public NeoTermDatabase deleteBeanByID(Class<?> tableClass, Object id) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); DatabaseDataType dataType = SQLTypeParser.getDataType(id.getClass()); if (dataType != null && tableInfo.primaryField != null) { //判断ID类型是否与数据类型匹配 boolean match = SQLTypeParser.matchType(tableInfo.primaryField, dataType); if (!match) {//不匹配,抛出异常 throw new IllegalArgumentException("类型 " + id.getClass().getName() + " 不是主键的类型,主键的类型应该为 " + tableInfo.primaryField.getType().getName()); } } String idValue = ValueHelper.valueToString(dataType, id); String statement = SQLStatementHelper.deleteByWhere(tableInfo, tableInfo.primaryField == null ? "_id" : tableInfo.primaryField.getName() + " = " + idValue); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } try { db.execSQL(statement); } catch (SQLException ignore) { ignore.printStackTrace(); //删除失败 } return this; } /** * 根据给定的where更新数据 * * @param tableClass * @param where * @param bean * @return */ public NeoTermDatabase updateByWhere(Class<?> tableClass, String where, Object bean) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); String statement = SQLStatementHelper.updateByWhere(tableInfo, bean, where); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.d(statement); } db.execSQL(statement); return this; } /** * 根据给定的id更新数据 * * @param tableClass * @param id * @param bean * @return */ public NeoTermDatabase updateByID(Class<?> tableClass, Object id, Object bean) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); StringBuilder subStatement = new StringBuilder(); if (tableInfo.containID) { subStatement.append(tableInfo.primaryField.getName()).append(" = ").append(ValueHelper.valueToString(SQLTypeParser.getDataType(tableInfo.primaryField), id)); } else { subStatement.append("_id = ").append((int) id); } updateByWhere(tableClass, subStatement.toString(), bean); return this; } /** * 根据ID查找Bean * * @param tableClass * @param id * @param <T> * @return */ public <T> T findBeanByID(Class<?> tableClass, Object id) { createTableIfNeed(tableClass); TableInfo tableInfo = TableHelper.from(tableClass); DatabaseDataType dataType = SQLTypeParser.getDataType(id.getClass()); if (dataType == null) { return null; } // 判断ID类型是否与数据类型匹配 boolean match = SQLTypeParser.matchType(tableInfo.primaryField, dataType) || tableInfo.primaryField == null; if (!match) {// 不匹配,抛出异常 throw new IllegalArgumentException("Type " + id.getClass().getName() + " is not the primary key, expecting " + tableInfo.primaryField.getType().getName()); } String idValue = ValueHelper.valueToString(dataType, id); String statement = SQLStatementHelper.findByWhere(tableInfo, tableInfo.primaryField == null ? "_id" : tableInfo.primaryField.getName() + " = " + idValue); if (neoTermSQLiteConfig.debugMode) { NLog.INSTANCE.w(statement); } try (Cursor cursor = db.rawQuery(statement, null)) { if (cursor != null && cursor.getCount() > 0) { cursor.moveToFirst(); T bean = Reflect.on(tableClass).create().get(); for (Field field : tableInfo.fieldToDataTypeMap.keySet()) { DatabaseDataType fieldType = tableInfo.fieldToDataTypeMap.get(field); ValueHelper.setKeyValue(cursor, bean, field, fieldType, cursor.getColumnIndex(field.getName())); } try { Reflect.on(bean).set(tableInfo.containID ? tableInfo.primaryField.getName() : "_id", id); } catch (Throwable ignore) { // 我们允许Bean没有id字段,因此此异常可以忽略 } return bean; } return null; } } /** * 通过 VACUUM 命令压缩数据库 */ public void vacuum() { db.execSQL("VACUUM"); } /** * 调用本方法会释放当前数据库占用的内存, * 调用后请确保你不会在接下来的代码中继续用到本实例. */ public void destroy() { DAO_MAP.remove(this); this.neoTermSQLiteConfig = null; this.db = null; } /** * 取得内部操纵的SqliteDatabase. * * @return */ public SQLiteDatabase getDatabase() { return db; } /** * 内部数 <SUF>*/ private class SQLiteDataBaseHelper extends SQLiteOpenHelper { private final OnDatabaseUpgradedListener onDatabaseUpgradedListener; private final boolean defaultDropAllTables; public SQLiteDataBaseHelper(Context context, NeoTermSQLiteConfig config) { super(context, config.getDatabaseName(), null, config.getDatabaseVersion()); this.onDatabaseUpgradedListener = config.getOnDatabaseUpgradedListener(); this.defaultDropAllTables = config.isDefaultDropAllTables(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (onDatabaseUpgradedListener != null) { onDatabaseUpgradedListener.onDatabaseUpgraded(db, oldVersion, newVersion); } else if (defaultDropAllTables) { // 干掉所有的表 dropAllTable(); } } } }
true
62783_5
package com.nepxion.zxing.core; /** * <p>Title: Nepxion Zxing</p> * <p>Description: Nepxion Zxing QR Code</p> * <p>Copyright: Copyright (c) 2017-2050</p> * <p>Company: Nepxion</p> * @author Haojun Ren * @version 1.0 */ import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.nepxion.zxing.entity.ZxingEntity; import com.nepxion.zxing.exception.ZxingException; import com.nepxion.zxing.util.ZxingUtil; /** * 相关参数说明 * text 二维码/条形码内容。二维码可以是文字,也可以是URL,条形码必须是数字 * format 二维码/条形码图片格式,例如jpg,png * encoding 二维码/条形码内容编码,例如UTF-8 * correctionLevel 二维码/条形码容错等级,例如ErrorCorrectionLevel.H(30%纠正率),ErrorCorrectionLevel.Q(25%纠正率),ErrorCorrectionLevel.M(15%纠正率),ErrorCorrectionLevel.L(7%纠正率)。纠正率越高,扫描速度越慢 * width 二维码/条形码图片宽度 * height 二维码/条形码图片高度 * margin 二维码/条形码图片白边大小,取值范围0~4 * foregroundColor 二维码/条形码图片前景色。格式如0xFF000000 * backgroundColor 二维码/条形码图片背景色。格式如0xFFFFFFFF * deleteWhiteBorder 二维码图片白边去除。当图片面积较小时候,可以利用该方法扩大二维码/条形码的显示面积 * logoFile 二维码Logo图片的文件,File对象。显示在二维码中间的Logo图片,其在二维码中的尺寸最大为100x100左右,否则会覆盖二维码导致最后不能被识别 * logoBytes 二维码Logo图片的字节数组。方便于使用者在外部传入,当logoBytes不为null的时候,使用logoBytes做为Logo图片渲染,当为null的时候采用上面的logoFile做为Logo图片渲染 * outputFile 二维码/条形码图片的导出文件,File对象 */ public class ZxingEncoder { private static final Logger LOG = LoggerFactory.getLogger(ZxingEncoder.class); public InputStream encodeForInputStream(ZxingEntity zxingEntity) { byte[] bytes = encodeForBytes(zxingEntity); return new ByteArrayInputStream(bytes); } public byte[] encodeForBytes(ZxingEntity zxingEntity) { BarcodeFormat barcodeFormat = zxingEntity.getBarcodeFormat(); String text = zxingEntity.getText(); String format = zxingEntity.getFormat(); String encoding = zxingEntity.getEncoding(); ErrorCorrectionLevel correctionLevel = zxingEntity.getCorrectionLevel(); int width = zxingEntity.getWidth(); int height = zxingEntity.getHeight(); int margin = zxingEntity.getMargin(); int foregroundColor = zxingEntity.getForegroundColor(); int backgroundColor = zxingEntity.getBackgroundColor(); boolean deleteWhiteBorder = zxingEntity.isDeleteWhiteBorder(); boolean hasLogo = zxingEntity.hasLogo(); if (barcodeFormat == null) { throw new ZxingException("Barcode format is null"); } if (StringUtils.isEmpty(text)) { throw new ZxingException("Text is null or empty"); } if (StringUtils.isEmpty(format)) { throw new ZxingException("Format is null or empty"); } if (StringUtils.isEmpty(encoding)) { throw new ZxingException("Encoding is null or empty"); } if (correctionLevel == null) { throw new ZxingException("Correction level is null"); } if (width <= 0) { throw new ZxingException("Invalid width=" + width); } if (height <= 0) { throw new ZxingException("Invalid height=" + height); } if (margin < 0 || margin > 4) { throw new ZxingException("Invalid margin=" + margin + ", it must be [0, 4]"); } ByteArrayOutputStream outputStream = null; try { Map<EncodeHintType, Object> hints = createHints(encoding, correctionLevel, margin); MultiFormatWriter formatWriter = new MultiFormatWriter(); MatrixToImageConfig imageConfig = new MatrixToImageConfig(foregroundColor, backgroundColor); BitMatrix bitMatrix = formatWriter.encode(text, barcodeFormat, width, height, hints); // 删除二维码四周的白边 if (barcodeFormat == BarcodeFormat.QR_CODE && deleteWhiteBorder) { bitMatrix = deleteWhiteBorder(bitMatrix); } outputStream = new ByteArrayOutputStream(); // 先输出Logo if (barcodeFormat == BarcodeFormat.QR_CODE && hasLogo) { BufferedImage logoImage = createLogoImage(bitMatrix, foregroundColor, backgroundColor, zxingEntity); if (!ImageIO.write(logoImage, format, outputStream)) { throw new ZxingException("Failed to write logo image"); } } // 再输出二维码/条形码 MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream, imageConfig); return outputStream.toByteArray(); } catch (WriterException e) { LOG.error("Encode stream error", e); throw new ZxingException("Encode stream error", e); } catch (IOException e) { LOG.error("Encode stream error", e); throw new ZxingException("Encode stream error", e); } finally { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } } } public File encodeForFile(ZxingEntity zxingEntity) { BarcodeFormat barcodeFormat = zxingEntity.getBarcodeFormat(); String text = zxingEntity.getText(); String format = zxingEntity.getFormat(); String encoding = zxingEntity.getEncoding(); ErrorCorrectionLevel correctionLevel = zxingEntity.getCorrectionLevel(); int width = zxingEntity.getWidth(); int height = zxingEntity.getHeight(); int margin = zxingEntity.getMargin(); int foregroundColor = zxingEntity.getForegroundColor(); int backgroundColor = zxingEntity.getBackgroundColor(); boolean deleteWhiteBorder = zxingEntity.isDeleteWhiteBorder(); boolean hasLogo = zxingEntity.hasLogo(); File outputFile = zxingEntity.getOutputFile(); if (barcodeFormat == null) { throw new ZxingException("Barcode format is null"); } if (StringUtils.isEmpty(text)) { throw new ZxingException("Text is null or empty"); } if (StringUtils.isEmpty(format)) { throw new ZxingException("Format is null or empty"); } if (StringUtils.isEmpty(encoding)) { throw new ZxingException("Encoding is null or empty"); } if (correctionLevel == null) { throw new ZxingException("Correction level is null"); } if (width <= 0) { throw new ZxingException("Invalid width=" + width); } if (height <= 0) { throw new ZxingException("Invalid height=" + height); } if (margin < 0 || margin > 4) { throw new ZxingException("Invalid margin=" + margin + ", it must be [0, 4]"); } if (outputFile == null) { throw new ZxingException("Output file is null"); } try { Map<EncodeHintType, Object> hints = createHints(encoding, correctionLevel, margin); MultiFormatWriter formatWriter = new MultiFormatWriter(); MatrixToImageConfig imageConfig = new MatrixToImageConfig(foregroundColor, backgroundColor); BitMatrix bitMatrix = formatWriter.encode(text, barcodeFormat, width, height, hints); // 删除二维码四周的白边 if (barcodeFormat == BarcodeFormat.QR_CODE && deleteWhiteBorder) { bitMatrix = deleteWhiteBorder(bitMatrix); } ZxingUtil.createDirectory(outputFile); // 先输出二维码/条形码 MatrixToImageWriter.writeToPath(bitMatrix, format, outputFile.toPath(), imageConfig); // 再输出Logo if (barcodeFormat == BarcodeFormat.QR_CODE && hasLogo) { BufferedImage logoImage = createLogoImage(bitMatrix, foregroundColor, backgroundColor, zxingEntity); if (!ImageIO.write(logoImage, format, outputFile)) { throw new ZxingException("Failed to write logo image"); } } } catch (WriterException e) { LOG.error("Encode file=[{}] error", outputFile.getPath(), e); throw new ZxingException("Encode file=[" + outputFile.getPath() + "] error", e); } catch (IOException e) { LOG.error("Encode file=[{}] error", outputFile.getPath(), e); throw new ZxingException("Encode file=[" + outputFile.getPath() + "] error", e); } return outputFile; } private BitMatrix deleteWhiteBorder(BitMatrix bitMatrix) { int[] rectangle = bitMatrix.getEnclosingRectangle(); int width = rectangle[2] + 1; int height = rectangle[3] + 1; BitMatrix matrix = new BitMatrix(width, height); matrix.clear(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (bitMatrix.get(i + rectangle[0], j + rectangle[1])) matrix.set(i, j); } } return matrix; } private BufferedImage createLogoImage(BitMatrix bitMatrix, int foregroundColor, int backgroundColor, ZxingEntity zxingEntity) throws IOException { BufferedImage image = createBufferedImage(bitMatrix, foregroundColor, backgroundColor); Graphics2D g2d = image.createGraphics(); int ratioWidth = image.getWidth() * 2 / 10; int ratioHeight = image.getHeight() * 2 / 10; if (ratioWidth > 100) { LOG.warn("Ratio width=[{}] for logo image is more than 100", ratioWidth); } if (ratioHeight > 100) { LOG.warn("Ratio height=[{}] for logo image is more than 100", ratioHeight); } // 载入Logo File logoFile = zxingEntity.getLogoFile(); InputStream logoInputStream = zxingEntity.getLogoInputStream(); Image logoImage = null; if (logoInputStream != null) { logoImage = ImageIO.read(logoInputStream); } else { logoImage = ImageIO.read(logoFile); } int logoWidth = logoImage.getWidth(null) > ratioWidth ? ratioWidth : logoImage.getWidth(null); int logoHeight = logoImage.getHeight(null) > ratioHeight ? ratioHeight : logoImage.getHeight(null); int x = (image.getWidth() - logoWidth) / 2; int y = (image.getHeight() - logoHeight) / 2; g2d.drawImage(logoImage, x, y, logoWidth, logoHeight, null); // g2d.drawImage(logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH), x, y, null); g2d.setColor(Color.black); g2d.setBackground(Color.WHITE); g2d.dispose(); logoImage.flush(); return image; } private BufferedImage createBufferedImage(BitMatrix bitMatrix, int foregroundColor, int backgroundColor) { int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? foregroundColor : backgroundColor); } } return image; } private Map<EncodeHintType, Object> createHints(String encoding, ErrorCorrectionLevel correctionLevel, int margin) { Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, encoding); // 设置编码 hints.put(EncodeHintType.ERROR_CORRECTION, correctionLevel); // 指定纠错等级 hints.put(EncodeHintType.MARGIN, margin); //设置白边 return hints; } }
Nepxion/Zxing
src/main/java/com/nepxion/zxing/core/ZxingEncoder.java
3,193
// 删除二维码四周的白边
line_comment
zh-cn
package com.nepxion.zxing.core; /** * <p>Title: Nepxion Zxing</p> * <p>Description: Nepxion Zxing QR Code</p> * <p>Copyright: Copyright (c) 2017-2050</p> * <p>Company: Nepxion</p> * @author Haojun Ren * @version 1.0 */ import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.WriterException; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import com.nepxion.zxing.entity.ZxingEntity; import com.nepxion.zxing.exception.ZxingException; import com.nepxion.zxing.util.ZxingUtil; /** * 相关参数说明 * text 二维码/条形码内容。二维码可以是文字,也可以是URL,条形码必须是数字 * format 二维码/条形码图片格式,例如jpg,png * encoding 二维码/条形码内容编码,例如UTF-8 * correctionLevel 二维码/条形码容错等级,例如ErrorCorrectionLevel.H(30%纠正率),ErrorCorrectionLevel.Q(25%纠正率),ErrorCorrectionLevel.M(15%纠正率),ErrorCorrectionLevel.L(7%纠正率)。纠正率越高,扫描速度越慢 * width 二维码/条形码图片宽度 * height 二维码/条形码图片高度 * margin 二维码/条形码图片白边大小,取值范围0~4 * foregroundColor 二维码/条形码图片前景色。格式如0xFF000000 * backgroundColor 二维码/条形码图片背景色。格式如0xFFFFFFFF * deleteWhiteBorder 二维码图片白边去除。当图片面积较小时候,可以利用该方法扩大二维码/条形码的显示面积 * logoFile 二维码Logo图片的文件,File对象。显示在二维码中间的Logo图片,其在二维码中的尺寸最大为100x100左右,否则会覆盖二维码导致最后不能被识别 * logoBytes 二维码Logo图片的字节数组。方便于使用者在外部传入,当logoBytes不为null的时候,使用logoBytes做为Logo图片渲染,当为null的时候采用上面的logoFile做为Logo图片渲染 * outputFile 二维码/条形码图片的导出文件,File对象 */ public class ZxingEncoder { private static final Logger LOG = LoggerFactory.getLogger(ZxingEncoder.class); public InputStream encodeForInputStream(ZxingEntity zxingEntity) { byte[] bytes = encodeForBytes(zxingEntity); return new ByteArrayInputStream(bytes); } public byte[] encodeForBytes(ZxingEntity zxingEntity) { BarcodeFormat barcodeFormat = zxingEntity.getBarcodeFormat(); String text = zxingEntity.getText(); String format = zxingEntity.getFormat(); String encoding = zxingEntity.getEncoding(); ErrorCorrectionLevel correctionLevel = zxingEntity.getCorrectionLevel(); int width = zxingEntity.getWidth(); int height = zxingEntity.getHeight(); int margin = zxingEntity.getMargin(); int foregroundColor = zxingEntity.getForegroundColor(); int backgroundColor = zxingEntity.getBackgroundColor(); boolean deleteWhiteBorder = zxingEntity.isDeleteWhiteBorder(); boolean hasLogo = zxingEntity.hasLogo(); if (barcodeFormat == null) { throw new ZxingException("Barcode format is null"); } if (StringUtils.isEmpty(text)) { throw new ZxingException("Text is null or empty"); } if (StringUtils.isEmpty(format)) { throw new ZxingException("Format is null or empty"); } if (StringUtils.isEmpty(encoding)) { throw new ZxingException("Encoding is null or empty"); } if (correctionLevel == null) { throw new ZxingException("Correction level is null"); } if (width <= 0) { throw new ZxingException("Invalid width=" + width); } if (height <= 0) { throw new ZxingException("Invalid height=" + height); } if (margin < 0 || margin > 4) { throw new ZxingException("Invalid margin=" + margin + ", it must be [0, 4]"); } ByteArrayOutputStream outputStream = null; try { Map<EncodeHintType, Object> hints = createHints(encoding, correctionLevel, margin); MultiFormatWriter formatWriter = new MultiFormatWriter(); MatrixToImageConfig imageConfig = new MatrixToImageConfig(foregroundColor, backgroundColor); BitMatrix bitMatrix = formatWriter.encode(text, barcodeFormat, width, height, hints); // 删除二维码四周的白边 if (barcodeFormat == BarcodeFormat.QR_CODE && deleteWhiteBorder) { bitMatrix = deleteWhiteBorder(bitMatrix); } outputStream = new ByteArrayOutputStream(); // 先输出Logo if (barcodeFormat == BarcodeFormat.QR_CODE && hasLogo) { BufferedImage logoImage = createLogoImage(bitMatrix, foregroundColor, backgroundColor, zxingEntity); if (!ImageIO.write(logoImage, format, outputStream)) { throw new ZxingException("Failed to write logo image"); } } // 再输出二维码/条形码 MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream, imageConfig); return outputStream.toByteArray(); } catch (WriterException e) { LOG.error("Encode stream error", e); throw new ZxingException("Encode stream error", e); } catch (IOException e) { LOG.error("Encode stream error", e); throw new ZxingException("Encode stream error", e); } finally { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } } } public File encodeForFile(ZxingEntity zxingEntity) { BarcodeFormat barcodeFormat = zxingEntity.getBarcodeFormat(); String text = zxingEntity.getText(); String format = zxingEntity.getFormat(); String encoding = zxingEntity.getEncoding(); ErrorCorrectionLevel correctionLevel = zxingEntity.getCorrectionLevel(); int width = zxingEntity.getWidth(); int height = zxingEntity.getHeight(); int margin = zxingEntity.getMargin(); int foregroundColor = zxingEntity.getForegroundColor(); int backgroundColor = zxingEntity.getBackgroundColor(); boolean deleteWhiteBorder = zxingEntity.isDeleteWhiteBorder(); boolean hasLogo = zxingEntity.hasLogo(); File outputFile = zxingEntity.getOutputFile(); if (barcodeFormat == null) { throw new ZxingException("Barcode format is null"); } if (StringUtils.isEmpty(text)) { throw new ZxingException("Text is null or empty"); } if (StringUtils.isEmpty(format)) { throw new ZxingException("Format is null or empty"); } if (StringUtils.isEmpty(encoding)) { throw new ZxingException("Encoding is null or empty"); } if (correctionLevel == null) { throw new ZxingException("Correction level is null"); } if (width <= 0) { throw new ZxingException("Invalid width=" + width); } if (height <= 0) { throw new ZxingException("Invalid height=" + height); } if (margin < 0 || margin > 4) { throw new ZxingException("Invalid margin=" + margin + ", it must be [0, 4]"); } if (outputFile == null) { throw new ZxingException("Output file is null"); } try { Map<EncodeHintType, Object> hints = createHints(encoding, correctionLevel, margin); MultiFormatWriter formatWriter = new MultiFormatWriter(); MatrixToImageConfig imageConfig = new MatrixToImageConfig(foregroundColor, backgroundColor); BitMatrix bitMatrix = formatWriter.encode(text, barcodeFormat, width, height, hints); // 删除 <SUF> if (barcodeFormat == BarcodeFormat.QR_CODE && deleteWhiteBorder) { bitMatrix = deleteWhiteBorder(bitMatrix); } ZxingUtil.createDirectory(outputFile); // 先输出二维码/条形码 MatrixToImageWriter.writeToPath(bitMatrix, format, outputFile.toPath(), imageConfig); // 再输出Logo if (barcodeFormat == BarcodeFormat.QR_CODE && hasLogo) { BufferedImage logoImage = createLogoImage(bitMatrix, foregroundColor, backgroundColor, zxingEntity); if (!ImageIO.write(logoImage, format, outputFile)) { throw new ZxingException("Failed to write logo image"); } } } catch (WriterException e) { LOG.error("Encode file=[{}] error", outputFile.getPath(), e); throw new ZxingException("Encode file=[" + outputFile.getPath() + "] error", e); } catch (IOException e) { LOG.error("Encode file=[{}] error", outputFile.getPath(), e); throw new ZxingException("Encode file=[" + outputFile.getPath() + "] error", e); } return outputFile; } private BitMatrix deleteWhiteBorder(BitMatrix bitMatrix) { int[] rectangle = bitMatrix.getEnclosingRectangle(); int width = rectangle[2] + 1; int height = rectangle[3] + 1; BitMatrix matrix = new BitMatrix(width, height); matrix.clear(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (bitMatrix.get(i + rectangle[0], j + rectangle[1])) matrix.set(i, j); } } return matrix; } private BufferedImage createLogoImage(BitMatrix bitMatrix, int foregroundColor, int backgroundColor, ZxingEntity zxingEntity) throws IOException { BufferedImage image = createBufferedImage(bitMatrix, foregroundColor, backgroundColor); Graphics2D g2d = image.createGraphics(); int ratioWidth = image.getWidth() * 2 / 10; int ratioHeight = image.getHeight() * 2 / 10; if (ratioWidth > 100) { LOG.warn("Ratio width=[{}] for logo image is more than 100", ratioWidth); } if (ratioHeight > 100) { LOG.warn("Ratio height=[{}] for logo image is more than 100", ratioHeight); } // 载入Logo File logoFile = zxingEntity.getLogoFile(); InputStream logoInputStream = zxingEntity.getLogoInputStream(); Image logoImage = null; if (logoInputStream != null) { logoImage = ImageIO.read(logoInputStream); } else { logoImage = ImageIO.read(logoFile); } int logoWidth = logoImage.getWidth(null) > ratioWidth ? ratioWidth : logoImage.getWidth(null); int logoHeight = logoImage.getHeight(null) > ratioHeight ? ratioHeight : logoImage.getHeight(null); int x = (image.getWidth() - logoWidth) / 2; int y = (image.getHeight() - logoHeight) / 2; g2d.drawImage(logoImage, x, y, logoWidth, logoHeight, null); // g2d.drawImage(logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH), x, y, null); g2d.setColor(Color.black); g2d.setBackground(Color.WHITE); g2d.dispose(); logoImage.flush(); return image; } private BufferedImage createBufferedImage(BitMatrix bitMatrix, int foregroundColor, int backgroundColor) { int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? foregroundColor : backgroundColor); } } return image; } private Map<EncodeHintType, Object> createHints(String encoding, ErrorCorrectionLevel correctionLevel, int margin) { Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(); hints.put(EncodeHintType.CHARACTER_SET, encoding); // 设置编码 hints.put(EncodeHintType.ERROR_CORRECTION, correctionLevel); // 指定纠错等级 hints.put(EncodeHintType.MARGIN, margin); //设置白边 return hints; } }
true
34405_22
package com.herewhite.sdk; import com.herewhite.sdk.domain.CameraBound; import com.herewhite.sdk.domain.MemberInformation; import com.herewhite.sdk.domain.Region; import com.herewhite.sdk.domain.WhiteObject; import java.util.concurrent.TimeUnit; // Created by buhe on 2018/8/11. /** * `RoomParams` 类,用于配置实时房间的参数。 * * @note `RoomParams` 类中所有的方法都必须在 `joinRoom` 前调用;成功加入房间后,调用该类中的任何方法都不会生效。 */ public class RoomParams extends WhiteObject { private String uuid; private String roomToken; private String uid; /** * 设置数据中心。 * * @note * - 该方法设置的数据中心必须与要加入的互动白板实时房间所在数据中心一致,否则无法加入房间。 * - 该方法与 `WhiteSdkConfiguration` 类中的 {@link WhiteSdkConfiguration#setRegion(Region) setRegion} 方法作用相同,两个方法只需要调用其中的一个。如果同时调用,该方法会覆盖 `WhiteSdkConfiguration` 类中的 {@link WhiteSdkConfiguration#setRegion(Region) setRegion}。 * * @param region 数据中心,详见 {@link com.herewhite.sdk.domain.Region Region}。 */ public void setRegion(Region region) { this.region = region; } /** * 获取设置的数据中心。 * * @return 设置的数据中心,详见 {@link com.herewhite.sdk.domain.Region Region}。 */ public Region getRegion() { return region; } private Region region; private CameraBound cameraBound; /** * 重连时,最大重连尝试时间,单位:毫秒,默认 45 秒。 */ private long timeout = 45000; /** * 获取用户是否以互动模式加入白板房间。 * * @return 用户是否以互动模式加入白板房间: * - `true`:以互动模式加入白板房间,即具有读写权限。 * - `false`:以订阅模式加入白板房间,即具有只读权限。 */ public boolean isWritable() { return isWritable; } /** * 设置用户是否以互动模式加入白板房间。 * <p> * 用户可以以以下模式加入互动白板实时房间: * - 互动模式:对白板具有读写权限,会出现在房间的成员列表中,对其他用户可见。 * - 订阅模式:对白板具有只读权限,不会出现在房间的成员列表中,对其他用户不可见。 * * @param writable 用户是否以互动模式加入白板房间: * - `true`:(默认)以互动模式加入白板房间。 * - `false`:以订阅模式加入白板房间。 */ public void setWritable(boolean writable) { isWritable = writable; } private boolean isWritable = true; /** * 获取是否关闭橡皮擦擦除图片功能。 * * @return 是否关闭橡皮擦擦除图片功能: * - `true`:橡皮擦不可以擦除图片。 * - `false`:橡皮擦可以擦除图片。 */ public boolean getDisableEraseImage() { return disableEraseImage; } /** * 设置是否关闭橡皮擦擦除图片功能。 * <p> * 默认情况下,橡皮擦可以擦除白板上的所有内容,包括图片。你可以调用 `setDisableEraseImage(true)` 设置橡皮擦不能擦除图片。 * * @param disableEraseImage 是否关闭橡皮擦擦除图片功能: * - `true`:橡皮擦不可以擦除图片。 * - `false`:(默认)橡皮擦可以擦除图片。 */ public void setDisableEraseImage(boolean disableEraseImage) { this.disableEraseImage = disableEraseImage; } /** * 设置加入房间的超时时间。 * * @param timeout 超时时长,默认值为 45000 毫秒。 * @param timeUnit 时长单位,默认值为毫秒 (`MILLISECONDS`),取值详见 [TimeUnit](https://www.android-doc.com/reference/java/util/concurrent/TimeUnit.html)。 */ public void setTimeout(long timeout, TimeUnit timeUnit) { this.timeout = TimeUnit.MILLISECONDS.convert(timeout, timeUnit); } private boolean disableEraseImage = false; /** * 获取是否禁止白板工具响应用户输入。 * * @return 是否禁止白板工具响应用户输入: * - `true`:禁止白板工具响应用户输入。 * - `false`:允许白板工具响应用户输入。 */ public boolean isDisableDeviceInputs() { return disableDeviceInputs; } /** * 开启/禁止白板工具响应用户输入。 * * @since 2.5.0 * * @param disableDeviceInputs 是否禁止白板工具响应用户输入: * - `true`:禁止白板工具响应用户输入。 * - `false`:(默认)允许白板工具响应用户输入。 */ public void setDisableDeviceInputs(boolean disableDeviceInputs) { this.disableDeviceInputs = disableDeviceInputs; } /** * 获取是否禁止白板响应用户的操作。 * * @return 是否禁止白板响应用户的操作。 * - `true`:禁止白板响应用户的操作。 * - `false`:允许白板响应用户的操作。 */ public boolean isDisableOperations() { return disableOperations; } /** * 允许/禁止白板响应用户任何操作。 * * @since 2.5.0 * * @deprecated 该方法已废弃。请使用 {@link #setDisableDeviceInputs(boolean) setDisableDeviceInputs} 和 {@link #setDisableCameraTransform(boolean) setDisableCameraTransform}。 * <p> * 禁止白板响应用户任何操作后,用户无法使用白板工具输入内容,也无法对白板进行视角缩放和视角移动。 * * @param disableOperations 是否禁止白板响应用户的操作: * - `true`:禁止白板响应用户的操作。 * - `false`:(默认)允许白板响应用户的操作。 */ public void setDisableOperations(boolean disableOperations) { this.disableCameraTransform = disableOperations; this.disableDeviceInputs = disableOperations; this.disableOperations = disableOperations; } /** * 获取是否关闭贝塞尔曲线优化。 * * @return 是否关闭贝塞尔曲线优化: * - `true`: 关闭贝塞尔曲线优化。 * - `false`: 开启贝塞尔曲线优化。 */ public boolean isDisableBezier() { return disableBezier; } /** * 设置是否关闭贝塞尔曲线优化。 * * @since 2.5.0 * * @param disableBezier 是否关闭贝塞尔曲线优化: * - `true`: 关闭贝塞尔曲线优化。 * - `false`: (默认)开启贝塞尔曲线优化。 * */ public void setDisableBezier(boolean disableBezier) { this.disableBezier = disableBezier; } private boolean disableDeviceInputs = false; private boolean disableOperations = false; /** * 获取是否禁止本地用户操作白板视角。 * * @return 是否禁止本地用户操作白板视角: * - `true`:禁止本地用户操作白板视角。 * - `false`:允许本地用户操作白板视角。 */ public boolean isDisableCameraTransform() { return disableCameraTransform; } /** * 禁止/允许本地用户操作白板的视角,包括缩放和移动视角。 * * @param disableCameraTransform 是否禁止本地用户操作白板视角: * - `true`:禁止本地用户操作白板视角。 * - `false`:(默认)允许本地用户操作白板视角。 */ public void setDisableCameraTransform(boolean disableCameraTransform) { this.disableCameraTransform = disableCameraTransform; } private boolean disableCameraTransform = false; private boolean disableBezier = false; /** * 获取是否关闭新铅笔工具。 * * @return 是否关闭新铅笔工具: * - `true`: 关闭新铅笔工具。 * - `false`: 开启新铅笔工具。 */ public boolean isDisableNewPencil() { return disableNewPencil; } /** * 关闭/开启新铅笔工具。 * * @since 2.12.2 * * @note * - 在 2.12.2 版本中,`setDisableNewPencil` 的默认值为 `false`,自 2.12.3 版本起,`setDisableNewPencil` 的默认值改为 `true`。 * - 为正常显示笔迹,在开启新铅笔工具前,请确保该房间内的所有用户使用如下 SDK: * - Android SDK 2.12.3 版或之后 * - iOS SDK 2.12.3 版或之后 * - Web SDK 2.12.5 版或之后 * * @param disableNewPencil 是否关闭新铅笔工具: * - `true`: (默认)关闭新铅笔工具。关闭后,SDK 对铅笔工具(`pencil`)应用旧版笔迹平滑算法。 * - `false`: 开启新铅笔工具。开启后,SDK 对铅笔工具应用新版笔迹平滑算法,使书写笔迹更加流畅自然,并带有笔锋效果。 */ public void setDisableNewPencil(boolean disableNewPencil) { this.disableNewPencil = disableNewPencil; } private boolean disableNewPencil = true; /** * 获取视角边界。 * * @return 视角边界。 */ public CameraBound getCameraBound() { return cameraBound; } /** * 设置本地用户的视角边界。 * * @since 2.5.0 * * @param cameraBound 视角边界,详见 {@link com.herewhite.sdk.domain.CameraBound CameraBound}。 */ public void setCameraBound(CameraBound cameraBound) { this.cameraBound = cameraBound; } /** * 获取自定义用户信息。 * * @return 自定义用户信息。 */ public Object getUserPayload() { return userPayload; } /** * 自定义用户信息。 * * @since 2.0.0 * * 你可以在 `userPayload` 中传入自定义的用户信息,例如用户ID,昵称和头像,然后调用此方法将信息发送给应用程序。 * * @note * 为确保传入的 `userPayload` 格式正确,必须为 {@link com.herewhite.sdk.domain.WhiteObject WhiteObject} 的子类。 * * @param userPayload 自定义的用户信息,必须为 key-value 结构,例如,`"avatar", "https://example.com/user.png")`。 */ public void setUserPayload(Object userPayload) { this.userPayload = userPayload; } private Object userPayload; /** * 初始化房间配置参数。 * * @param uuid 房间 UUID, 即房间唯一标识符。传入的房间 UUID 必须和生成 Room Token 时填入的房间 UUID 一致。 * @param roomToken 用于鉴权的 Room Token。 * @param uid 自从 v2.15.0。用户唯一标识符,字符串格式,长度不能超过 1024 字节。如果你使用 2.15.0 及之后版本的 SDK,必须传入该参数。 * 请确保同一房间内每个用户 `uid` 的唯一性。 */ public RoomParams(String uuid, String roomToken, String uid) { this(uuid, roomToken, uid, (Object) null); } /** * 初始化房间配置参数并传入用户信息。 * * @deprecated 该方法已经废弃。请使用 {@link RoomParams(String uuid, String roomToken, String uid, Object userPayload) RoomParams}[3/3]。 * * @param uuid 房间 UUID, 即房间唯一标识符。传入的房间 UUID 必须和生成 Room Token 时填入的房间 UUID 一致。 * @param roomToken 用于鉴权的 Room Token。 * @param uid 自从 v2.15.0。用户唯一标识符,字符串格式,长度不能超过 1024 字节。如果你使用 2.15.0 及之后版本的 SDK,必须传入该参数。 * 请确保同一房间内每个用户 `uid` 的唯一性。 * @param memberInfo 自定义用户信息,详见 {@link com.herewhite.sdk.domain.MemberInformation MemberInformation}。 * */ @Deprecated public RoomParams(String uuid, String roomToken, String uid, MemberInformation memberInfo) { this(uuid, roomToken, uid, (Object) memberInfo); } /** * 初始化房间配置参数并传入自定义的用户信息。 * * @since 2.0.0 * * @param uuid 房间 UUID, 即房间唯一标识符。传入的房间 UUID 必须和生成 Room Token 时填入的房间 UUID 一致。 * @param roomToken 用于鉴权的 Room Token。 * @param uid 自从 v2.15.0。用户唯一标识符,字符串格式,长度不能超过 1024 字节。如果你使用 2.15.0 及之后版本的 SDK,必须传入该参数。 * 请确保同一房间内每个用户 `uid` 的唯一性。 * @param userPayload 自定义用户信息,必须为 {@link com.herewhite.sdk.domain.WhiteObject WhiteObject} 子类。 */ public RoomParams(String uuid, String roomToken, String uid, Object userPayload) { this.uuid = uuid; this.roomToken = roomToken; this.uid = uid; this.userPayload = userPayload; } /** * 获取自定义的用户信息。 * * @deprecated 该方法已废弃。请使用 {@link #getUserPayload() getUserPayload}。 * * @return 自定义用户信息,详见 {@link com.herewhite.sdk.domain.MemberInformation MemberInformation}。 */ @Deprecated public MemberInformation getMemberInfo() { if (userPayload instanceof MemberInformation) { return (MemberInformation) userPayload; } return null; } /** * 自定义用户信息。 * * @deprecated 该方法已废弃。请使用 {@link #getUserPayload() getUserPayload}。 * * @param memberInfo 用户信息,详见 {@link com.herewhite.sdk.domain.MemberInformation MemberInformation}。 */ @Deprecated public void setMemberInfo(MemberInformation memberInfo) { this.userPayload = memberInfo; } /** * 获取房间 UUID。 * * @return 房间 UUID,即房间的唯一标识符。 */ public String getUuid() { return uuid; } /** * 设置房间 UUID。 * * @param uuid 房间 UUID,即房间的唯一标识符。 */ public void setUuid(String uuid) { this.uuid = uuid; } /** * 获取 Room Token。 * * @return Room Token。 */ public String getRoomToken() { return roomToken; } /** * 设置 Room Token。 * * @param roomToken 用于鉴权的 Room Token。生成该 Room Token 的房间 UUID 必须和上面传入的房间 UUID 一致。 */ public void setRoomToken(String roomToken) { this.roomToken = roomToken; } /** * 开启全链路加速功能。 * * Agora 互动白板服务集成了 [Agora 全链路加速(FPA)服务](https://docs.agora.io/cn/global-accelerator/agora_ga_overview?platform=All%20Platforms)。 * 集成 Agora Whiteboard SDK 后,你只需调用 `setUseNativeWebSocket(true)`,即可在互动白板应用中开启全链路加速服务,提升传输质量。 * * @param nativeWebSocket 是否开启全链路加速: * - `true`:开启全链路加速。 * - `false`:(默认)关闭全链路加速。 */ public void setUseNativeWebSocket(boolean nativeWebSocket) { this.nativeWebSocket = nativeWebSocket; } /** * 获取是否开启全链路加速功能。 * * @return 是否开启全链路加速功能: * - `true`:开启。 * - `false`:关闭。 */ public boolean isUseNativeWebSocket() { return nativeWebSocket; } /** * 获取浮动条功能是否已开启。 * * @return 浮动条功能是否已开启: * - `true`:开启。 * - `false`:关闭。 */ public boolean isUsingFloatBar() { return floatBar; } /** * 设置是否开启开启浮动条功能。 * * @param floatBar 是否开启浮动条: * - `true`:开启浮动条功能。 * - `false`:(默认)关闭浮动条功能。 */ public void setUsingFloatBar(boolean floatBar) { this.floatBar = floatBar; } private boolean floatBar = false; /** * 获取白板请求 modules 数据的地址。 * @return 方法调用成功时返回 modules 地址。 */ public String getModulesOrigin() { return modulesOrigin; } /** * 设置白板请求 modules 数据的地址。 * 配置后不会请求白板默认地址。 * @param modulesOrigin modules 地址。示例 https://modules.example.com。 */ public void setModulesOrigin(String modulesOrigin) { this.modulesOrigin = modulesOrigin; private String modulesOrigin; } }
Nero-Hu/Whiteboard-Android-doc
CN/sdk/RoomParams.java
4,434
/** * 获取自定义用户信息。 * * @return 自定义用户信息。 */
block_comment
zh-cn
package com.herewhite.sdk; import com.herewhite.sdk.domain.CameraBound; import com.herewhite.sdk.domain.MemberInformation; import com.herewhite.sdk.domain.Region; import com.herewhite.sdk.domain.WhiteObject; import java.util.concurrent.TimeUnit; // Created by buhe on 2018/8/11. /** * `RoomParams` 类,用于配置实时房间的参数。 * * @note `RoomParams` 类中所有的方法都必须在 `joinRoom` 前调用;成功加入房间后,调用该类中的任何方法都不会生效。 */ public class RoomParams extends WhiteObject { private String uuid; private String roomToken; private String uid; /** * 设置数据中心。 * * @note * - 该方法设置的数据中心必须与要加入的互动白板实时房间所在数据中心一致,否则无法加入房间。 * - 该方法与 `WhiteSdkConfiguration` 类中的 {@link WhiteSdkConfiguration#setRegion(Region) setRegion} 方法作用相同,两个方法只需要调用其中的一个。如果同时调用,该方法会覆盖 `WhiteSdkConfiguration` 类中的 {@link WhiteSdkConfiguration#setRegion(Region) setRegion}。 * * @param region 数据中心,详见 {@link com.herewhite.sdk.domain.Region Region}。 */ public void setRegion(Region region) { this.region = region; } /** * 获取设置的数据中心。 * * @return 设置的数据中心,详见 {@link com.herewhite.sdk.domain.Region Region}。 */ public Region getRegion() { return region; } private Region region; private CameraBound cameraBound; /** * 重连时,最大重连尝试时间,单位:毫秒,默认 45 秒。 */ private long timeout = 45000; /** * 获取用户是否以互动模式加入白板房间。 * * @return 用户是否以互动模式加入白板房间: * - `true`:以互动模式加入白板房间,即具有读写权限。 * - `false`:以订阅模式加入白板房间,即具有只读权限。 */ public boolean isWritable() { return isWritable; } /** * 设置用户是否以互动模式加入白板房间。 * <p> * 用户可以以以下模式加入互动白板实时房间: * - 互动模式:对白板具有读写权限,会出现在房间的成员列表中,对其他用户可见。 * - 订阅模式:对白板具有只读权限,不会出现在房间的成员列表中,对其他用户不可见。 * * @param writable 用户是否以互动模式加入白板房间: * - `true`:(默认)以互动模式加入白板房间。 * - `false`:以订阅模式加入白板房间。 */ public void setWritable(boolean writable) { isWritable = writable; } private boolean isWritable = true; /** * 获取是否关闭橡皮擦擦除图片功能。 * * @return 是否关闭橡皮擦擦除图片功能: * - `true`:橡皮擦不可以擦除图片。 * - `false`:橡皮擦可以擦除图片。 */ public boolean getDisableEraseImage() { return disableEraseImage; } /** * 设置是否关闭橡皮擦擦除图片功能。 * <p> * 默认情况下,橡皮擦可以擦除白板上的所有内容,包括图片。你可以调用 `setDisableEraseImage(true)` 设置橡皮擦不能擦除图片。 * * @param disableEraseImage 是否关闭橡皮擦擦除图片功能: * - `true`:橡皮擦不可以擦除图片。 * - `false`:(默认)橡皮擦可以擦除图片。 */ public void setDisableEraseImage(boolean disableEraseImage) { this.disableEraseImage = disableEraseImage; } /** * 设置加入房间的超时时间。 * * @param timeout 超时时长,默认值为 45000 毫秒。 * @param timeUnit 时长单位,默认值为毫秒 (`MILLISECONDS`),取值详见 [TimeUnit](https://www.android-doc.com/reference/java/util/concurrent/TimeUnit.html)。 */ public void setTimeout(long timeout, TimeUnit timeUnit) { this.timeout = TimeUnit.MILLISECONDS.convert(timeout, timeUnit); } private boolean disableEraseImage = false; /** * 获取是否禁止白板工具响应用户输入。 * * @return 是否禁止白板工具响应用户输入: * - `true`:禁止白板工具响应用户输入。 * - `false`:允许白板工具响应用户输入。 */ public boolean isDisableDeviceInputs() { return disableDeviceInputs; } /** * 开启/禁止白板工具响应用户输入。 * * @since 2.5.0 * * @param disableDeviceInputs 是否禁止白板工具响应用户输入: * - `true`:禁止白板工具响应用户输入。 * - `false`:(默认)允许白板工具响应用户输入。 */ public void setDisableDeviceInputs(boolean disableDeviceInputs) { this.disableDeviceInputs = disableDeviceInputs; } /** * 获取是否禁止白板响应用户的操作。 * * @return 是否禁止白板响应用户的操作。 * - `true`:禁止白板响应用户的操作。 * - `false`:允许白板响应用户的操作。 */ public boolean isDisableOperations() { return disableOperations; } /** * 允许/禁止白板响应用户任何操作。 * * @since 2.5.0 * * @deprecated 该方法已废弃。请使用 {@link #setDisableDeviceInputs(boolean) setDisableDeviceInputs} 和 {@link #setDisableCameraTransform(boolean) setDisableCameraTransform}。 * <p> * 禁止白板响应用户任何操作后,用户无法使用白板工具输入内容,也无法对白板进行视角缩放和视角移动。 * * @param disableOperations 是否禁止白板响应用户的操作: * - `true`:禁止白板响应用户的操作。 * - `false`:(默认)允许白板响应用户的操作。 */ public void setDisableOperations(boolean disableOperations) { this.disableCameraTransform = disableOperations; this.disableDeviceInputs = disableOperations; this.disableOperations = disableOperations; } /** * 获取是否关闭贝塞尔曲线优化。 * * @return 是否关闭贝塞尔曲线优化: * - `true`: 关闭贝塞尔曲线优化。 * - `false`: 开启贝塞尔曲线优化。 */ public boolean isDisableBezier() { return disableBezier; } /** * 设置是否关闭贝塞尔曲线优化。 * * @since 2.5.0 * * @param disableBezier 是否关闭贝塞尔曲线优化: * - `true`: 关闭贝塞尔曲线优化。 * - `false`: (默认)开启贝塞尔曲线优化。 * */ public void setDisableBezier(boolean disableBezier) { this.disableBezier = disableBezier; } private boolean disableDeviceInputs = false; private boolean disableOperations = false; /** * 获取是否禁止本地用户操作白板视角。 * * @return 是否禁止本地用户操作白板视角: * - `true`:禁止本地用户操作白板视角。 * - `false`:允许本地用户操作白板视角。 */ public boolean isDisableCameraTransform() { return disableCameraTransform; } /** * 禁止/允许本地用户操作白板的视角,包括缩放和移动视角。 * * @param disableCameraTransform 是否禁止本地用户操作白板视角: * - `true`:禁止本地用户操作白板视角。 * - `false`:(默认)允许本地用户操作白板视角。 */ public void setDisableCameraTransform(boolean disableCameraTransform) { this.disableCameraTransform = disableCameraTransform; } private boolean disableCameraTransform = false; private boolean disableBezier = false; /** * 获取是否关闭新铅笔工具。 * * @return 是否关闭新铅笔工具: * - `true`: 关闭新铅笔工具。 * - `false`: 开启新铅笔工具。 */ public boolean isDisableNewPencil() { return disableNewPencil; } /** * 关闭/开启新铅笔工具。 * * @since 2.12.2 * * @note * - 在 2.12.2 版本中,`setDisableNewPencil` 的默认值为 `false`,自 2.12.3 版本起,`setDisableNewPencil` 的默认值改为 `true`。 * - 为正常显示笔迹,在开启新铅笔工具前,请确保该房间内的所有用户使用如下 SDK: * - Android SDK 2.12.3 版或之后 * - iOS SDK 2.12.3 版或之后 * - Web SDK 2.12.5 版或之后 * * @param disableNewPencil 是否关闭新铅笔工具: * - `true`: (默认)关闭新铅笔工具。关闭后,SDK 对铅笔工具(`pencil`)应用旧版笔迹平滑算法。 * - `false`: 开启新铅笔工具。开启后,SDK 对铅笔工具应用新版笔迹平滑算法,使书写笔迹更加流畅自然,并带有笔锋效果。 */ public void setDisableNewPencil(boolean disableNewPencil) { this.disableNewPencil = disableNewPencil; } private boolean disableNewPencil = true; /** * 获取视角边界。 * * @return 视角边界。 */ public CameraBound getCameraBound() { return cameraBound; } /** * 设置本地用户的视角边界。 * * @since 2.5.0 * * @param cameraBound 视角边界,详见 {@link com.herewhite.sdk.domain.CameraBound CameraBound}。 */ public void setCameraBound(CameraBound cameraBound) { this.cameraBound = cameraBound; } /** * 获取自 <SUF>*/ public Object getUserPayload() { return userPayload; } /** * 自定义用户信息。 * * @since 2.0.0 * * 你可以在 `userPayload` 中传入自定义的用户信息,例如用户ID,昵称和头像,然后调用此方法将信息发送给应用程序。 * * @note * 为确保传入的 `userPayload` 格式正确,必须为 {@link com.herewhite.sdk.domain.WhiteObject WhiteObject} 的子类。 * * @param userPayload 自定义的用户信息,必须为 key-value 结构,例如,`"avatar", "https://example.com/user.png")`。 */ public void setUserPayload(Object userPayload) { this.userPayload = userPayload; } private Object userPayload; /** * 初始化房间配置参数。 * * @param uuid 房间 UUID, 即房间唯一标识符。传入的房间 UUID 必须和生成 Room Token 时填入的房间 UUID 一致。 * @param roomToken 用于鉴权的 Room Token。 * @param uid 自从 v2.15.0。用户唯一标识符,字符串格式,长度不能超过 1024 字节。如果你使用 2.15.0 及之后版本的 SDK,必须传入该参数。 * 请确保同一房间内每个用户 `uid` 的唯一性。 */ public RoomParams(String uuid, String roomToken, String uid) { this(uuid, roomToken, uid, (Object) null); } /** * 初始化房间配置参数并传入用户信息。 * * @deprecated 该方法已经废弃。请使用 {@link RoomParams(String uuid, String roomToken, String uid, Object userPayload) RoomParams}[3/3]。 * * @param uuid 房间 UUID, 即房间唯一标识符。传入的房间 UUID 必须和生成 Room Token 时填入的房间 UUID 一致。 * @param roomToken 用于鉴权的 Room Token。 * @param uid 自从 v2.15.0。用户唯一标识符,字符串格式,长度不能超过 1024 字节。如果你使用 2.15.0 及之后版本的 SDK,必须传入该参数。 * 请确保同一房间内每个用户 `uid` 的唯一性。 * @param memberInfo 自定义用户信息,详见 {@link com.herewhite.sdk.domain.MemberInformation MemberInformation}。 * */ @Deprecated public RoomParams(String uuid, String roomToken, String uid, MemberInformation memberInfo) { this(uuid, roomToken, uid, (Object) memberInfo); } /** * 初始化房间配置参数并传入自定义的用户信息。 * * @since 2.0.0 * * @param uuid 房间 UUID, 即房间唯一标识符。传入的房间 UUID 必须和生成 Room Token 时填入的房间 UUID 一致。 * @param roomToken 用于鉴权的 Room Token。 * @param uid 自从 v2.15.0。用户唯一标识符,字符串格式,长度不能超过 1024 字节。如果你使用 2.15.0 及之后版本的 SDK,必须传入该参数。 * 请确保同一房间内每个用户 `uid` 的唯一性。 * @param userPayload 自定义用户信息,必须为 {@link com.herewhite.sdk.domain.WhiteObject WhiteObject} 子类。 */ public RoomParams(String uuid, String roomToken, String uid, Object userPayload) { this.uuid = uuid; this.roomToken = roomToken; this.uid = uid; this.userPayload = userPayload; } /** * 获取自定义的用户信息。 * * @deprecated 该方法已废弃。请使用 {@link #getUserPayload() getUserPayload}。 * * @return 自定义用户信息,详见 {@link com.herewhite.sdk.domain.MemberInformation MemberInformation}。 */ @Deprecated public MemberInformation getMemberInfo() { if (userPayload instanceof MemberInformation) { return (MemberInformation) userPayload; } return null; } /** * 自定义用户信息。 * * @deprecated 该方法已废弃。请使用 {@link #getUserPayload() getUserPayload}。 * * @param memberInfo 用户信息,详见 {@link com.herewhite.sdk.domain.MemberInformation MemberInformation}。 */ @Deprecated public void setMemberInfo(MemberInformation memberInfo) { this.userPayload = memberInfo; } /** * 获取房间 UUID。 * * @return 房间 UUID,即房间的唯一标识符。 */ public String getUuid() { return uuid; } /** * 设置房间 UUID。 * * @param uuid 房间 UUID,即房间的唯一标识符。 */ public void setUuid(String uuid) { this.uuid = uuid; } /** * 获取 Room Token。 * * @return Room Token。 */ public String getRoomToken() { return roomToken; } /** * 设置 Room Token。 * * @param roomToken 用于鉴权的 Room Token。生成该 Room Token 的房间 UUID 必须和上面传入的房间 UUID 一致。 */ public void setRoomToken(String roomToken) { this.roomToken = roomToken; } /** * 开启全链路加速功能。 * * Agora 互动白板服务集成了 [Agora 全链路加速(FPA)服务](https://docs.agora.io/cn/global-accelerator/agora_ga_overview?platform=All%20Platforms)。 * 集成 Agora Whiteboard SDK 后,你只需调用 `setUseNativeWebSocket(true)`,即可在互动白板应用中开启全链路加速服务,提升传输质量。 * * @param nativeWebSocket 是否开启全链路加速: * - `true`:开启全链路加速。 * - `false`:(默认)关闭全链路加速。 */ public void setUseNativeWebSocket(boolean nativeWebSocket) { this.nativeWebSocket = nativeWebSocket; } /** * 获取是否开启全链路加速功能。 * * @return 是否开启全链路加速功能: * - `true`:开启。 * - `false`:关闭。 */ public boolean isUseNativeWebSocket() { return nativeWebSocket; } /** * 获取浮动条功能是否已开启。 * * @return 浮动条功能是否已开启: * - `true`:开启。 * - `false`:关闭。 */ public boolean isUsingFloatBar() { return floatBar; } /** * 设置是否开启开启浮动条功能。 * * @param floatBar 是否开启浮动条: * - `true`:开启浮动条功能。 * - `false`:(默认)关闭浮动条功能。 */ public void setUsingFloatBar(boolean floatBar) { this.floatBar = floatBar; } private boolean floatBar = false; /** * 获取白板请求 modules 数据的地址。 * @return 方法调用成功时返回 modules 地址。 */ public String getModulesOrigin() { return modulesOrigin; } /** * 设置白板请求 modules 数据的地址。 * 配置后不会请求白板默认地址。 * @param modulesOrigin modules 地址。示例 https://modules.example.com。 */ public void setModulesOrigin(String modulesOrigin) { this.modulesOrigin = modulesOrigin; private String modulesOrigin; } }
true
46784_26
package chapter08; //为什么需要继承 //两个类的属性和方法有很多是相同的 代码复用性很差 //继承可以解决代码复用 当多个类存在相同的属性和方法时 可以从这些类中抽象出父类 并在父类中定义这些属性和方法 //然后子类只需要通过extends关键字声明就可以获得父类的属性和方法 子类还可以拥有自己的特有属性和方法 也可以再有子类 //使用继承除了提高复用性还能提高扩展性 //语法 //class 子类名 extends 父类名{ // } //关于继承的细节 //1父类的私有属性和方法在子类中不能直接访问 可以通过父类间接访问(属性用方法return 方法用父类调用) //子类与父类在同一个包下,子类可以访问父类默认修饰符修饰的属性 //子类与父类不在同一个包下,子类不可以访问父类默认修饰符修饰的属性,但可以访问受保护的 //2只要是类都需要通过构造器初始化,子类构造器一般只管自己的属性初始化 那么在内存当中,父类那一块的属性并没有初始化 //所以子类必须调用父类的构造器以完成父类属性的初始化 //先别急接着看3当创建子类对象时不管使用子类的哪个构造器都会默认调用父类的无参构造器 //即子类构造器代码中有一行隐藏的super(); //如果父类没有无参构造器 则必须在子类构造器中用super来指定父类使用哪个有参构造器完成父类的初始化 否则编译不通过 //总结来说就是要完成初始化工作 //这是弹幕写的 //子类如果想初始化对象,就得先让父类初始化对象 //如果父类没有,或者只有无参构造器,子类不管调用无参/有参构造器,都得先调用父类的无参构造器 //如果父类有一个有参构造器,并且把无参构造器覆盖。而子类想初始化对象,就得在构造器里面写super.(父类的有参构造器) //4关于super 只能放在子类构造器的第一行(言外之意super访问父类构造器时只能在子类构造器中使用(和this差不多)) //而this访问构造器时也是只能放在构造器的第一行 所以this和super不能存在一个构造器 //5java所有的类都是Object类的子类(都继承Object) //所以调构造器时一直往上追溯到object自上而下初始化 //6不能滥用继承 子类和父类必须有逻辑上的关系比如cat类继承animal类 pupil类继承student类 //import jdk.nashorn.internal.ir.CallNode; //继承的内存布局 //先来写几个类 class GrandPa { String name = "爷爷"; String hobby = "旅游"; } class Father extends GrandPa { String name = "爸爸"; int age = 33; } class Son extends Father { String name = "儿子"; private int age = 12; } //这里儿子类继承爸爸类再继承爷爷类 class Test { public static void main(String[] args) { Son son = new Son(); //这一条执行时 会先向上找到Object类 自上而下加载类信息在方法区 //再GrandPa初始化name和hobby 再Father初始化name和age 再Son初始化name和age 在堆空间 //提醒一下 字符串在常量池都 //这里故意继承的类都写name new对象时不会有影响 都会在堆空间完成初始化 //然后我们来看调用 System.out.println(son.name);//如果不是私有的话.name会从子类开始往上找 //System.out.println(son.age); 当遇到private会阻塞 即使父类还有.age System.out.println(son.hobby); //至于son怎么访问爹和爷爷的name 我也不知道 反正就是只能访到一层 } } //练习题 //1看图说话 class A { public A() {//4来到了这里输出 System.out.println("我是A类"); } } class B extends A { public B() { System.out.println("我是B类的无参构造器"); } public B(String name)//3 {//这里没写出来还有个默认super()去调a的无参构造器 System.out.println("我是B类的有参构造器");//5 } } class C extends B { public C()//程序从这里开始 { this("hello");//1这里调用了c的有参构造器 而且因为第一行是this所以没了super System.out.println("我是C类的无参构造器");//7 } public C(String name) { super("haha");//2我们说子类初始化必须先调父类构造器 这里有手动的super找b的有参构造器 System.out.println("我是C类的有参构造器");//6 } } //然后main方法中new了一个C对象 问输出什么 //C c=new C(); 调用无参构造器 class Test1 { public static void main(String[] args) { C c = new C(); } } //super关键字 代表父类的引用 用于访问父类的属性 方法 构造器 //和this差不多 只不过this是本类 super是在子类访问父类 //访问父类属性和方法 但不能访问private属性和方法 //访问父类构造器 只能放在子类构造器第一句且只能有一句super //(遵守访问修饰符规则) //这时候我们回过头来看刚才写的三个类 class GrandPa1 { String name = "爷爷"; String hobby = "旅游"; public void hello() { System.out.println("d"); } } class Father1 extends GrandPa1 { String name = "爸爸"; int age = 33; public void hello()//在这里建一个方法 { System.out.println("我是father的hello"); } } class Son1 extends Father1 { String name = "儿子"; private int age = 12; public void hello() { System.out.println("我是son的hello"); } //要在子类访问父类hello方法的话 public void hello1() { hello(); this.hello();//这两个是等价的 从本类开始找 没有找到就往上继续 直到找到 被private阻塞或者没找到就报错 //和上面说的差不多 只不过上面是new了对象的 super.hello();//这个是从父类开始找 //这样也能解决上面提出的问题怎么访问爹和爷爷的name //用super 但如果多级同名就只能就近访问 } //属性也差不多这样访问规则 //这里提炼出一点规则 就是当子类父类有重名属性或者方法时为了在子类访问父类的属性和方法必须通过super //但是没重名的话用super this 直接访 都是一样的 (因为会自动往上找) } //this和super的比较 //当访问属性和方法时 super比this高一类 都会往上继续查找 //当访问构造器时 this必须放在本类构造器首行来访问本类的构造器 super放在子类构造器首行来访问父类构造器 //当new了对象 this表示当前类的对象 super表示父类的对象 //方法重写override //构成重写的条件 //首先两个方法要分别在父类和子类 //子类中方法的名称 形参列表 返回类型 和父类的方法的完全一样或者 //名称和形参列表一样 但是子类的方法的返回类型是父类方法的返回类型子类 比如子类string 父类object //然后就是修饰符 子类的方法不能缩小父类的方法的访问范围 //与方法重载比较 重载只要求名一样 参数列表不一样 // 发生范围 方法名 形参列表 返回类型 修饰符 //重载 本类 相同 不一致 无关 无关 //重写 父子类 相同 一致 可以不一样 不缩小 //例题 //Person类包括属性 name age 和构造器 方法say来返回自我介绍的字符串 //Student类继承Person类 增加属性id score及构造器 say方法重写来返回自我介绍的字符串 //在main中分别创建两个类的对象 并调用say方法 class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String say() { return "我叫 " + name + " 年龄 " + age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Student extends Person { private int id; private int score; public Student(String name, int age, int id, int score) { super(name, age); this.id = id; this.score = score; } public String say() { return super.say() + " id " + id + " 成绩 " + score; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } class Test2 { public static void main(String[] args) { Person 东雪莲 = new Person("东雪莲", 40); System.out.println(东雪莲.say()); Student 丁真 = new Student("丁真", 21, 15, 100); System.out.println(丁真.say()); } }//两个say构成了方法重写
Nethtra/JAVA
chapter0708/src/chapter08/c继承.java
2,505
//继承的内存布局
line_comment
zh-cn
package chapter08; //为什么需要继承 //两个类的属性和方法有很多是相同的 代码复用性很差 //继承可以解决代码复用 当多个类存在相同的属性和方法时 可以从这些类中抽象出父类 并在父类中定义这些属性和方法 //然后子类只需要通过extends关键字声明就可以获得父类的属性和方法 子类还可以拥有自己的特有属性和方法 也可以再有子类 //使用继承除了提高复用性还能提高扩展性 //语法 //class 子类名 extends 父类名{ // } //关于继承的细节 //1父类的私有属性和方法在子类中不能直接访问 可以通过父类间接访问(属性用方法return 方法用父类调用) //子类与父类在同一个包下,子类可以访问父类默认修饰符修饰的属性 //子类与父类不在同一个包下,子类不可以访问父类默认修饰符修饰的属性,但可以访问受保护的 //2只要是类都需要通过构造器初始化,子类构造器一般只管自己的属性初始化 那么在内存当中,父类那一块的属性并没有初始化 //所以子类必须调用父类的构造器以完成父类属性的初始化 //先别急接着看3当创建子类对象时不管使用子类的哪个构造器都会默认调用父类的无参构造器 //即子类构造器代码中有一行隐藏的super(); //如果父类没有无参构造器 则必须在子类构造器中用super来指定父类使用哪个有参构造器完成父类的初始化 否则编译不通过 //总结来说就是要完成初始化工作 //这是弹幕写的 //子类如果想初始化对象,就得先让父类初始化对象 //如果父类没有,或者只有无参构造器,子类不管调用无参/有参构造器,都得先调用父类的无参构造器 //如果父类有一个有参构造器,并且把无参构造器覆盖。而子类想初始化对象,就得在构造器里面写super.(父类的有参构造器) //4关于super 只能放在子类构造器的第一行(言外之意super访问父类构造器时只能在子类构造器中使用(和this差不多)) //而this访问构造器时也是只能放在构造器的第一行 所以this和super不能存在一个构造器 //5java所有的类都是Object类的子类(都继承Object) //所以调构造器时一直往上追溯到object自上而下初始化 //6不能滥用继承 子类和父类必须有逻辑上的关系比如cat类继承animal类 pupil类继承student类 //import jdk.nashorn.internal.ir.CallNode; //继承 <SUF> //先来写几个类 class GrandPa { String name = "爷爷"; String hobby = "旅游"; } class Father extends GrandPa { String name = "爸爸"; int age = 33; } class Son extends Father { String name = "儿子"; private int age = 12; } //这里儿子类继承爸爸类再继承爷爷类 class Test { public static void main(String[] args) { Son son = new Son(); //这一条执行时 会先向上找到Object类 自上而下加载类信息在方法区 //再GrandPa初始化name和hobby 再Father初始化name和age 再Son初始化name和age 在堆空间 //提醒一下 字符串在常量池都 //这里故意继承的类都写name new对象时不会有影响 都会在堆空间完成初始化 //然后我们来看调用 System.out.println(son.name);//如果不是私有的话.name会从子类开始往上找 //System.out.println(son.age); 当遇到private会阻塞 即使父类还有.age System.out.println(son.hobby); //至于son怎么访问爹和爷爷的name 我也不知道 反正就是只能访到一层 } } //练习题 //1看图说话 class A { public A() {//4来到了这里输出 System.out.println("我是A类"); } } class B extends A { public B() { System.out.println("我是B类的无参构造器"); } public B(String name)//3 {//这里没写出来还有个默认super()去调a的无参构造器 System.out.println("我是B类的有参构造器");//5 } } class C extends B { public C()//程序从这里开始 { this("hello");//1这里调用了c的有参构造器 而且因为第一行是this所以没了super System.out.println("我是C类的无参构造器");//7 } public C(String name) { super("haha");//2我们说子类初始化必须先调父类构造器 这里有手动的super找b的有参构造器 System.out.println("我是C类的有参构造器");//6 } } //然后main方法中new了一个C对象 问输出什么 //C c=new C(); 调用无参构造器 class Test1 { public static void main(String[] args) { C c = new C(); } } //super关键字 代表父类的引用 用于访问父类的属性 方法 构造器 //和this差不多 只不过this是本类 super是在子类访问父类 //访问父类属性和方法 但不能访问private属性和方法 //访问父类构造器 只能放在子类构造器第一句且只能有一句super //(遵守访问修饰符规则) //这时候我们回过头来看刚才写的三个类 class GrandPa1 { String name = "爷爷"; String hobby = "旅游"; public void hello() { System.out.println("d"); } } class Father1 extends GrandPa1 { String name = "爸爸"; int age = 33; public void hello()//在这里建一个方法 { System.out.println("我是father的hello"); } } class Son1 extends Father1 { String name = "儿子"; private int age = 12; public void hello() { System.out.println("我是son的hello"); } //要在子类访问父类hello方法的话 public void hello1() { hello(); this.hello();//这两个是等价的 从本类开始找 没有找到就往上继续 直到找到 被private阻塞或者没找到就报错 //和上面说的差不多 只不过上面是new了对象的 super.hello();//这个是从父类开始找 //这样也能解决上面提出的问题怎么访问爹和爷爷的name //用super 但如果多级同名就只能就近访问 } //属性也差不多这样访问规则 //这里提炼出一点规则 就是当子类父类有重名属性或者方法时为了在子类访问父类的属性和方法必须通过super //但是没重名的话用super this 直接访 都是一样的 (因为会自动往上找) } //this和super的比较 //当访问属性和方法时 super比this高一类 都会往上继续查找 //当访问构造器时 this必须放在本类构造器首行来访问本类的构造器 super放在子类构造器首行来访问父类构造器 //当new了对象 this表示当前类的对象 super表示父类的对象 //方法重写override //构成重写的条件 //首先两个方法要分别在父类和子类 //子类中方法的名称 形参列表 返回类型 和父类的方法的完全一样或者 //名称和形参列表一样 但是子类的方法的返回类型是父类方法的返回类型子类 比如子类string 父类object //然后就是修饰符 子类的方法不能缩小父类的方法的访问范围 //与方法重载比较 重载只要求名一样 参数列表不一样 // 发生范围 方法名 形参列表 返回类型 修饰符 //重载 本类 相同 不一致 无关 无关 //重写 父子类 相同 一致 可以不一样 不缩小 //例题 //Person类包括属性 name age 和构造器 方法say来返回自我介绍的字符串 //Student类继承Person类 增加属性id score及构造器 say方法重写来返回自我介绍的字符串 //在main中分别创建两个类的对象 并调用say方法 class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String say() { return "我叫 " + name + " 年龄 " + age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Student extends Person { private int id; private int score; public Student(String name, int age, int id, int score) { super(name, age); this.id = id; this.score = score; } public String say() { return super.say() + " id " + id + " 成绩 " + score; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } } class Test2 { public static void main(String[] args) { Person 东雪莲 = new Person("东雪莲", 40); System.out.println(东雪莲.say()); Student 丁真 = new Student("丁真", 21, 15, 100); System.out.println(丁真.say()); } }//两个say构成了方法重写
true
65509_4
package thu.infosecurity.simulate.model; //import javafx.util.Pair; import com.sun.tools.javac.util.Pair; import java.awt.*; import java.util.Set; /** * * Created by forest on 2017/5/15. * Revised by forest on 2017/6/12 */ public class Soldier { /*基本信息*/ private int ID; //ID private String name; //姓名 private Point position; //坐标 /*用于区分敌人的对称秘钥*/ private String DESKey; //用于区分敌我士兵的对称秘钥 /*公私钥信息*/ private String puKey; //公钥 private String prKey; //私钥 /*秘钥共享信息*/ //private String shareKey; //格式为:1,45 因此需要手动按照,讲两个数据提取出来 private Pair<Integer, Integer> shareKey; /*访问控制*/ private String secretLevel; //采用BLP模型,分文秘密'S',机密'C',绝密'T'三个等级 private Set<String> range; //海军'S',陆军'G',空军'A' public static void main(String[] args){ System.out.println("helloworld"); } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Point getPosition() { return position; } public void setPosition(Point position) { this.position = position; } public String getPuKey() { return puKey; } public void setPuKey(String puKey) { this.puKey = puKey; } public String getPrKey() { return prKey; } public void setPrKey(String prKey) { this.prKey = prKey; } public Pair<Integer, Integer> getShareKey() { return shareKey; } public void setShareKey(Pair<Integer, Integer> shareKey) { this.shareKey = shareKey; } public String getSecretLevel() { return secretLevel; } public void setSecretLevel(String secretLevel) { this.secretLevel = secretLevel; } public Set<String> getRange() { return range; } public void setRange(Set<String> range) { this.range = range; } /*201706.12添加:获得军衔*/ public String getTitle(){ if (secretLevel.equals("S")) { return "三级士兵"; } if (secretLevel.equals("C")) { return "二级士兵"; } if (secretLevel.equals("T")) { return "一级士兵"; } return "列兵"; } public void setDESKey(String DESKey) { this.DESKey = DESKey; } public String getDESKey() { return DESKey; } @Override public String toString() { return "Soldier{" + "ID=" + ID + ", name='" + name + '\'' + ", position=" + position + ", DESKey='" + DESKey + '\'' + ", puKey='" + puKey + '\'' + ", prKey='" + prKey + '\'' + ", shareKey=" + shareKey + ", secretLevel='" + secretLevel + '\'' + ", range=" + range + '}'; } }
NetworkInfoSecurity/MilitarySimulateSystem
src/thu/infosecurity/simulate/model/Soldier.java
863
//用于区分敌我士兵的对称秘钥
line_comment
zh-cn
package thu.infosecurity.simulate.model; //import javafx.util.Pair; import com.sun.tools.javac.util.Pair; import java.awt.*; import java.util.Set; /** * * Created by forest on 2017/5/15. * Revised by forest on 2017/6/12 */ public class Soldier { /*基本信息*/ private int ID; //ID private String name; //姓名 private Point position; //坐标 /*用于区分敌人的对称秘钥*/ private String DESKey; //用于 <SUF> /*公私钥信息*/ private String puKey; //公钥 private String prKey; //私钥 /*秘钥共享信息*/ //private String shareKey; //格式为:1,45 因此需要手动按照,讲两个数据提取出来 private Pair<Integer, Integer> shareKey; /*访问控制*/ private String secretLevel; //采用BLP模型,分文秘密'S',机密'C',绝密'T'三个等级 private Set<String> range; //海军'S',陆军'G',空军'A' public static void main(String[] args){ System.out.println("helloworld"); } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Point getPosition() { return position; } public void setPosition(Point position) { this.position = position; } public String getPuKey() { return puKey; } public void setPuKey(String puKey) { this.puKey = puKey; } public String getPrKey() { return prKey; } public void setPrKey(String prKey) { this.prKey = prKey; } public Pair<Integer, Integer> getShareKey() { return shareKey; } public void setShareKey(Pair<Integer, Integer> shareKey) { this.shareKey = shareKey; } public String getSecretLevel() { return secretLevel; } public void setSecretLevel(String secretLevel) { this.secretLevel = secretLevel; } public Set<String> getRange() { return range; } public void setRange(Set<String> range) { this.range = range; } /*201706.12添加:获得军衔*/ public String getTitle(){ if (secretLevel.equals("S")) { return "三级士兵"; } if (secretLevel.equals("C")) { return "二级士兵"; } if (secretLevel.equals("T")) { return "一级士兵"; } return "列兵"; } public void setDESKey(String DESKey) { this.DESKey = DESKey; } public String getDESKey() { return DESKey; } @Override public String toString() { return "Soldier{" + "ID=" + ID + ", name='" + name + '\'' + ", position=" + position + ", DESKey='" + DESKey + '\'' + ", puKey='" + puKey + '\'' + ", prKey='" + prKey + '\'' + ", shareKey=" + shareKey + ", secretLevel='" + secretLevel + '\'' + ", range=" + range + '}'; } }
true
41411_24
package com.tencent.matrix.trace; import com.tencent.matrix.javalib.util.Log; import com.tencent.matrix.trace.item.TraceMethod; import com.tencent.matrix.trace.retrace.MappingCollector; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.MethodNode; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class MethodCollector { private static final String TAG = "MethodCollector"; private final ExecutorService executor; private final MappingCollector mappingCollector; //存储 类->父类 的map(用于查找Activity的子类) private final ConcurrentHashMap<String, String> collectedClassExtendMap = new ConcurrentHashMap<>(); //存储 被忽略方法名 -> 该方法TraceMethod 的映射关系 private final ConcurrentHashMap<String, TraceMethod> collectedIgnoreMethodMap = new ConcurrentHashMap<>(); //存储 需要插桩方法名 -> 该方法TraceMethod 的映射关系 private final ConcurrentHashMap<String, TraceMethod> collectedMethodMap; private final Configuration configuration; private final AtomicInteger methodId; // 被忽略方法计数器 private final AtomicInteger ignoreCount = new AtomicInteger(); //需要插桩方法 计数器 private final AtomicInteger incrementCount = new AtomicInteger(); public MethodCollector(ExecutorService executor, MappingCollector mappingCollector, AtomicInteger methodId, Configuration configuration, ConcurrentHashMap<String, TraceMethod> collectedMethodMap) { this.executor = executor; this.mappingCollector = mappingCollector; this.configuration = configuration; this.methodId = methodId; this.collectedMethodMap = collectedMethodMap; } public ConcurrentHashMap<String, String> getCollectedClassExtendMap() { return collectedClassExtendMap; } public ConcurrentHashMap<String, TraceMethod> getCollectedMethodMap() { return collectedMethodMap; } /** * * @param srcFolderList 原始文件集合 * @param dependencyJarList 原始 jar 集合 * @throws ExecutionException * @throws InterruptedException */ public void collect(Set<File> srcFolderList, Set<File> dependencyJarList) throws ExecutionException, InterruptedException { List<Future> futures = new LinkedList<>(); for (File srcFile : srcFolderList) { //将所有源文件添加到 classFileList 中 ArrayList<File> classFileList = new ArrayList<>(); if (srcFile.isDirectory()) { listClassFiles(classFileList, srcFile); } else { classFileList.add(srcFile); } //这里应该是个bug,这个for 应该防止撒谎给你吗那个for 的外面 for (File classFile : classFileList) { // 每个源文件执行 CollectSrcTask futures.add(executor.submit(new CollectSrcTask(classFile))); } } for (File jarFile : dependencyJarList) { // 每个jar 源文件执行 CollectJarTask futures.add(executor.submit(new CollectJarTask(jarFile))); } for (Future future : futures) { future.get(); } futures.clear(); futures.add(executor.submit(new Runnable() { @Override public void run() { //存储不需要插桩的方法信息到文件(包括黑名单中的方法) saveIgnoreCollectedMethod(mappingCollector); } })); futures.add(executor.submit(new Runnable() { @Override public void run() { //存储待插桩的方法信息到文件 saveCollectedMethod(mappingCollector); } })); for (Future future : futures) { future.get(); } futures.clear(); } class CollectSrcTask implements Runnable { File classFile; CollectSrcTask(File classFile) { this.classFile = classFile; } @Override public void run() { InputStream is = null; try { is = new FileInputStream(classFile); ClassReader classReader = new ClassReader(is); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); //收集Method信息 ClassVisitor visitor = new TraceClassAdapter(Opcodes.ASM5, classWriter); classReader.accept(visitor, 0); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e) { } } } } class CollectJarTask implements Runnable { File fromJar; CollectJarTask(File jarFile) { this.fromJar = jarFile; } @Override public void run() { ZipFile zipFile = null; try { zipFile = new ZipFile(fromJar); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); String zipEntryName = zipEntry.getName(); if (isNeedTraceFile(zipEntryName)) {//是需要被插桩的文件 InputStream inputStream = zipFile.getInputStream(zipEntry); ClassReader classReader = new ClassReader(inputStream); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); //进行扫描 ClassVisitor visitor = new TraceClassAdapter(Opcodes.ASM5, classWriter); classReader.accept(visitor, 0); } } } catch (Exception e) { e.printStackTrace(); } finally { try { zipFile.close(); } catch (Exception e) { Log.e(TAG, "close stream err! fromJar:%s", fromJar.getAbsolutePath()); } } } } /** * 将被忽略的 方法名 存入 ignoreMethodMapping.txt 中 * @param mappingCollector */ private void saveIgnoreCollectedMethod(MappingCollector mappingCollector) { //创建 ignoreMethodMapping.txt 文件对象 File methodMapFile = new File(configuration.ignoreMethodMapFilePath); //如果他爸不存在就创建 if (!methodMapFile.getParentFile().exists()) { methodMapFile.getParentFile().mkdirs(); } List<TraceMethod> ignoreMethodList = new ArrayList<>(); ignoreMethodList.addAll(collectedIgnoreMethodMap.values()); Log.i(TAG, "[saveIgnoreCollectedMethod] size:%s path:%s", collectedIgnoreMethodMap.size(), methodMapFile.getAbsolutePath()); //通过class名字进行排序 Collections.sort(ignoreMethodList, new Comparator<TraceMethod>() { @Override public int compare(TraceMethod o1, TraceMethod o2) { return o1.className.compareTo(o2.className); } }); PrintWriter pw = null; try { FileOutputStream fileOutputStream = new FileOutputStream(methodMapFile, false); Writer w = new OutputStreamWriter(fileOutputStream, "UTF-8"); pw = new PrintWriter(w); pw.println("ignore methods:"); for (TraceMethod traceMethod : ignoreMethodList) { //将 混淆过的数据 转换为 原始数据 traceMethod.revert(mappingCollector); //输出忽略信息到 文件中 pw.println(traceMethod.toIgnoreString()); } } catch (Exception e) { Log.e(TAG, "write method map Exception:%s", e.getMessage()); e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } /** * 将被插桩的 方法名 存入 methodMapping.txt 中 * @param mappingCollector */ private void saveCollectedMethod(MappingCollector mappingCollector) { File methodMapFile = new File(configuration.methodMapFilePath); if (!methodMapFile.getParentFile().exists()) { methodMapFile.getParentFile().mkdirs(); } List<TraceMethod> methodList = new ArrayList<>(); //因为Android包下的 都不会被插装,但是我们需要 dispatchMessage 方法的执行时间 //所以将这个例外 加进去 TraceMethod extra = TraceMethod.create(TraceBuildConstants.METHOD_ID_DISPATCH, Opcodes.ACC_PUBLIC, "android.os.Handler", "dispatchMessage", "(Landroid.os.Message;)V"); collectedMethodMap.put(extra.getMethodName(), extra); methodList.addAll(collectedMethodMap.values()); Log.i(TAG, "[saveCollectedMethod] size:%s incrementCount:%s path:%s", collectedMethodMap.size(), incrementCount.get(), methodMapFile.getAbsolutePath()); //通过ID 进行排序 Collections.sort(methodList, new Comparator<TraceMethod>() { @Override public int compare(TraceMethod o1, TraceMethod o2) { return o1.id - o2.id; } }); PrintWriter pw = null; try { FileOutputStream fileOutputStream = new FileOutputStream(methodMapFile, false); Writer w = new OutputStreamWriter(fileOutputStream, "UTF-8"); pw = new PrintWriter(w); for (TraceMethod traceMethod : methodList) { traceMethod.revert(mappingCollector); pw.println(traceMethod.toString()); } } catch (Exception e) { Log.e(TAG, "write method map Exception:%s", e.getMessage()); e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } private class TraceClassAdapter extends ClassVisitor { private String className; private boolean isABSClass = false; private boolean hasWindowFocusMethod = false; TraceClassAdapter(int i, ClassVisitor classVisitor) { super(i, classVisitor); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); this.className = name; //如果是虚拟类或者接口 isABSClass =true if ((access & Opcodes.ACC_ABSTRACT) > 0 || (access & Opcodes.ACC_INTERFACE) > 0) { this.isABSClass = true; } //存到 collectedClassExtendMap 中 collectedClassExtendMap.put(className, superName); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (isABSClass) {//如果是虚拟类或者接口 就不管 return super.visitMethod(access, name, desc, signature, exceptions); } else { if (!hasWindowFocusMethod) { //该方法是否与onWindowFocusChange方法的签名一致 // (该类中是否复写了onWindowFocusChange方法,Activity不用考虑Class混淆) hasWindowFocusMethod = isWindowFocusChangeMethod(name, desc); } //CollectMethodNode中执行method收集操作 return new CollectMethodNode(className, access, name, desc, signature, exceptions); } } } private class CollectMethodNode extends MethodNode { private String className; private boolean isConstructor; CollectMethodNode(String className, int access, String name, String desc, String signature, String[] exceptions) { super(Opcodes.ASM5, access, name, desc, signature, exceptions); this.className = className; } @Override public void visitEnd() { super.visitEnd(); //创建TraceMethod TraceMethod traceMethod = TraceMethod.create(0, access, className, name, desc); //如果是构造方法 if ("<init>".equals(name)) { isConstructor = true; } //判断类是否 被配置在了 黑名单中 boolean isNeedTrace = isNeedTrace(configuration, traceMethod.className, mappingCollector); //忽略空方法、get/set方法、没有局部变量的简单方法 if ((isEmptyMethod() || isGetSetMethod() || isSingleMethod()) && isNeedTrace) { //忽略方法递增 ignoreCount.incrementAndGet(); //加入到被忽略方法 map collectedIgnoreMethodMap.put(traceMethod.getMethodName(), traceMethod); return; } //不在黑名单中而且没在在methodMapping中配置过的方法加入待插桩的集合; if (isNeedTrace && !collectedMethodMap.containsKey(traceMethod.getMethodName())) { traceMethod.id = methodId.incrementAndGet(); collectedMethodMap.put(traceMethod.getMethodName(), traceMethod); incrementCount.incrementAndGet(); } else if (!isNeedTrace && !collectedIgnoreMethodMap.containsKey(traceMethod.className)) {//在黑名单中而且没在在methodMapping中配置过的方法加入ignore插桩的集合 ignoreCount.incrementAndGet(); collectedIgnoreMethodMap.put(traceMethod.getMethodName(), traceMethod); } } /** * 判断是否是 get方法 * @return */ private boolean isGetSetMethod() { int ignoreCount = 0; ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); int opcode = insnNode.getOpcode(); if (-1 == opcode) { continue; } if (opcode != Opcodes.GETFIELD && opcode != Opcodes.GETSTATIC && opcode != Opcodes.H_GETFIELD && opcode != Opcodes.H_GETSTATIC && opcode != Opcodes.RETURN && opcode != Opcodes.ARETURN && opcode != Opcodes.DRETURN && opcode != Opcodes.FRETURN && opcode != Opcodes.LRETURN && opcode != Opcodes.IRETURN && opcode != Opcodes.PUTFIELD && opcode != Opcodes.PUTSTATIC && opcode != Opcodes.H_PUTFIELD && opcode != Opcodes.H_PUTSTATIC && opcode > Opcodes.SALOAD) { if (isConstructor && opcode == Opcodes.INVOKESPECIAL) { ignoreCount++; if (ignoreCount > 1) { return false; } continue; } return false; } } return true; } private boolean isSingleMethod() { ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); int opcode = insnNode.getOpcode(); if (-1 == opcode) { continue; } else if (Opcodes.INVOKEVIRTUAL <= opcode && opcode <= Opcodes.INVOKEDYNAMIC) { return false; } } return true; } private boolean isEmptyMethod() { ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); int opcode = insnNode.getOpcode(); if (-1 == opcode) { continue; } else { return false; } } return true; } } public static boolean isWindowFocusChangeMethod(String name, String desc) { return null != name && null != desc && name.equals(TraceBuildConstants.MATRIX_TRACE_ON_WINDOW_FOCUS_METHOD) && desc.equals(TraceBuildConstants.MATRIX_TRACE_ON_WINDOW_FOCUS_METHOD_ARGS); } /** * 是否需要 被插桩代码 * @param configuration * @param clsName * @param mappingCollector * @return */ public static boolean isNeedTrace(Configuration configuration, String clsName, MappingCollector mappingCollector) { boolean isNeed = true; //该类是否在黑名单中 if (configuration.blackSet.contains(clsName)) { isNeed = false; } else { if (null != mappingCollector) { //通过混淆过的 类型 获取原始类名 clsName = mappingCollector.originalClassName(clsName, clsName); } clsName = clsName.replaceAll("/", "."); for (String packageName : configuration.blackSet) { //是否属于黑名单中的配置 if (clsName.startsWith(packageName.replaceAll("/", "."))) { isNeed = false; break; } } } return isNeed; } private void listClassFiles(ArrayList<File> classFiles, File folder) { File[] files = folder.listFiles(); if (null == files) { Log.e(TAG, "[listClassFiles] files is null! %s", folder.getAbsolutePath()); return; } for (File file : files) { if (file == null) { continue; } if (file.isDirectory()) { listClassFiles(classFiles, file); } else if (isNeedTraceFile(file.getName())) { classFiles.add(file); } } } /** * 判断是否是需要被插桩的文件 * @param fileName * @return */ public static boolean isNeedTraceFile(String fileName) { if (fileName.endsWith(".class")) { for (String unTraceCls : TraceBuildConstants.UN_TRACE_CLASS) { if (fileName.contains(unTraceCls)) { return false; } } } else { return false; } return true; } }
NiLuogege/MatrixDebug
matrix-master/matrix/matrix-android/matrix-gradle-plugin/src/main/java/com/tencent/matrix/trace/MethodCollector.java
4,123
//通过ID 进行排序
line_comment
zh-cn
package com.tencent.matrix.trace; import com.tencent.matrix.javalib.util.Log; import com.tencent.matrix.trace.item.TraceMethod; import com.tencent.matrix.trace.retrace.MappingCollector; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.MethodNode; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class MethodCollector { private static final String TAG = "MethodCollector"; private final ExecutorService executor; private final MappingCollector mappingCollector; //存储 类->父类 的map(用于查找Activity的子类) private final ConcurrentHashMap<String, String> collectedClassExtendMap = new ConcurrentHashMap<>(); //存储 被忽略方法名 -> 该方法TraceMethod 的映射关系 private final ConcurrentHashMap<String, TraceMethod> collectedIgnoreMethodMap = new ConcurrentHashMap<>(); //存储 需要插桩方法名 -> 该方法TraceMethod 的映射关系 private final ConcurrentHashMap<String, TraceMethod> collectedMethodMap; private final Configuration configuration; private final AtomicInteger methodId; // 被忽略方法计数器 private final AtomicInteger ignoreCount = new AtomicInteger(); //需要插桩方法 计数器 private final AtomicInteger incrementCount = new AtomicInteger(); public MethodCollector(ExecutorService executor, MappingCollector mappingCollector, AtomicInteger methodId, Configuration configuration, ConcurrentHashMap<String, TraceMethod> collectedMethodMap) { this.executor = executor; this.mappingCollector = mappingCollector; this.configuration = configuration; this.methodId = methodId; this.collectedMethodMap = collectedMethodMap; } public ConcurrentHashMap<String, String> getCollectedClassExtendMap() { return collectedClassExtendMap; } public ConcurrentHashMap<String, TraceMethod> getCollectedMethodMap() { return collectedMethodMap; } /** * * @param srcFolderList 原始文件集合 * @param dependencyJarList 原始 jar 集合 * @throws ExecutionException * @throws InterruptedException */ public void collect(Set<File> srcFolderList, Set<File> dependencyJarList) throws ExecutionException, InterruptedException { List<Future> futures = new LinkedList<>(); for (File srcFile : srcFolderList) { //将所有源文件添加到 classFileList 中 ArrayList<File> classFileList = new ArrayList<>(); if (srcFile.isDirectory()) { listClassFiles(classFileList, srcFile); } else { classFileList.add(srcFile); } //这里应该是个bug,这个for 应该防止撒谎给你吗那个for 的外面 for (File classFile : classFileList) { // 每个源文件执行 CollectSrcTask futures.add(executor.submit(new CollectSrcTask(classFile))); } } for (File jarFile : dependencyJarList) { // 每个jar 源文件执行 CollectJarTask futures.add(executor.submit(new CollectJarTask(jarFile))); } for (Future future : futures) { future.get(); } futures.clear(); futures.add(executor.submit(new Runnable() { @Override public void run() { //存储不需要插桩的方法信息到文件(包括黑名单中的方法) saveIgnoreCollectedMethod(mappingCollector); } })); futures.add(executor.submit(new Runnable() { @Override public void run() { //存储待插桩的方法信息到文件 saveCollectedMethod(mappingCollector); } })); for (Future future : futures) { future.get(); } futures.clear(); } class CollectSrcTask implements Runnable { File classFile; CollectSrcTask(File classFile) { this.classFile = classFile; } @Override public void run() { InputStream is = null; try { is = new FileInputStream(classFile); ClassReader classReader = new ClassReader(is); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); //收集Method信息 ClassVisitor visitor = new TraceClassAdapter(Opcodes.ASM5, classWriter); classReader.accept(visitor, 0); } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); } catch (Exception e) { } } } } class CollectJarTask implements Runnable { File fromJar; CollectJarTask(File jarFile) { this.fromJar = jarFile; } @Override public void run() { ZipFile zipFile = null; try { zipFile = new ZipFile(fromJar); Enumeration<? extends ZipEntry> enumeration = zipFile.entries(); while (enumeration.hasMoreElements()) { ZipEntry zipEntry = enumeration.nextElement(); String zipEntryName = zipEntry.getName(); if (isNeedTraceFile(zipEntryName)) {//是需要被插桩的文件 InputStream inputStream = zipFile.getInputStream(zipEntry); ClassReader classReader = new ClassReader(inputStream); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS); //进行扫描 ClassVisitor visitor = new TraceClassAdapter(Opcodes.ASM5, classWriter); classReader.accept(visitor, 0); } } } catch (Exception e) { e.printStackTrace(); } finally { try { zipFile.close(); } catch (Exception e) { Log.e(TAG, "close stream err! fromJar:%s", fromJar.getAbsolutePath()); } } } } /** * 将被忽略的 方法名 存入 ignoreMethodMapping.txt 中 * @param mappingCollector */ private void saveIgnoreCollectedMethod(MappingCollector mappingCollector) { //创建 ignoreMethodMapping.txt 文件对象 File methodMapFile = new File(configuration.ignoreMethodMapFilePath); //如果他爸不存在就创建 if (!methodMapFile.getParentFile().exists()) { methodMapFile.getParentFile().mkdirs(); } List<TraceMethod> ignoreMethodList = new ArrayList<>(); ignoreMethodList.addAll(collectedIgnoreMethodMap.values()); Log.i(TAG, "[saveIgnoreCollectedMethod] size:%s path:%s", collectedIgnoreMethodMap.size(), methodMapFile.getAbsolutePath()); //通过class名字进行排序 Collections.sort(ignoreMethodList, new Comparator<TraceMethod>() { @Override public int compare(TraceMethod o1, TraceMethod o2) { return o1.className.compareTo(o2.className); } }); PrintWriter pw = null; try { FileOutputStream fileOutputStream = new FileOutputStream(methodMapFile, false); Writer w = new OutputStreamWriter(fileOutputStream, "UTF-8"); pw = new PrintWriter(w); pw.println("ignore methods:"); for (TraceMethod traceMethod : ignoreMethodList) { //将 混淆过的数据 转换为 原始数据 traceMethod.revert(mappingCollector); //输出忽略信息到 文件中 pw.println(traceMethod.toIgnoreString()); } } catch (Exception e) { Log.e(TAG, "write method map Exception:%s", e.getMessage()); e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } /** * 将被插桩的 方法名 存入 methodMapping.txt 中 * @param mappingCollector */ private void saveCollectedMethod(MappingCollector mappingCollector) { File methodMapFile = new File(configuration.methodMapFilePath); if (!methodMapFile.getParentFile().exists()) { methodMapFile.getParentFile().mkdirs(); } List<TraceMethod> methodList = new ArrayList<>(); //因为Android包下的 都不会被插装,但是我们需要 dispatchMessage 方法的执行时间 //所以将这个例外 加进去 TraceMethod extra = TraceMethod.create(TraceBuildConstants.METHOD_ID_DISPATCH, Opcodes.ACC_PUBLIC, "android.os.Handler", "dispatchMessage", "(Landroid.os.Message;)V"); collectedMethodMap.put(extra.getMethodName(), extra); methodList.addAll(collectedMethodMap.values()); Log.i(TAG, "[saveCollectedMethod] size:%s incrementCount:%s path:%s", collectedMethodMap.size(), incrementCount.get(), methodMapFile.getAbsolutePath()); //通过 <SUF> Collections.sort(methodList, new Comparator<TraceMethod>() { @Override public int compare(TraceMethod o1, TraceMethod o2) { return o1.id - o2.id; } }); PrintWriter pw = null; try { FileOutputStream fileOutputStream = new FileOutputStream(methodMapFile, false); Writer w = new OutputStreamWriter(fileOutputStream, "UTF-8"); pw = new PrintWriter(w); for (TraceMethod traceMethod : methodList) { traceMethod.revert(mappingCollector); pw.println(traceMethod.toString()); } } catch (Exception e) { Log.e(TAG, "write method map Exception:%s", e.getMessage()); e.printStackTrace(); } finally { if (pw != null) { pw.flush(); pw.close(); } } } private class TraceClassAdapter extends ClassVisitor { private String className; private boolean isABSClass = false; private boolean hasWindowFocusMethod = false; TraceClassAdapter(int i, ClassVisitor classVisitor) { super(i, classVisitor); } @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, name, signature, superName, interfaces); this.className = name; //如果是虚拟类或者接口 isABSClass =true if ((access & Opcodes.ACC_ABSTRACT) > 0 || (access & Opcodes.ACC_INTERFACE) > 0) { this.isABSClass = true; } //存到 collectedClassExtendMap 中 collectedClassExtendMap.put(className, superName); } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (isABSClass) {//如果是虚拟类或者接口 就不管 return super.visitMethod(access, name, desc, signature, exceptions); } else { if (!hasWindowFocusMethod) { //该方法是否与onWindowFocusChange方法的签名一致 // (该类中是否复写了onWindowFocusChange方法,Activity不用考虑Class混淆) hasWindowFocusMethod = isWindowFocusChangeMethod(name, desc); } //CollectMethodNode中执行method收集操作 return new CollectMethodNode(className, access, name, desc, signature, exceptions); } } } private class CollectMethodNode extends MethodNode { private String className; private boolean isConstructor; CollectMethodNode(String className, int access, String name, String desc, String signature, String[] exceptions) { super(Opcodes.ASM5, access, name, desc, signature, exceptions); this.className = className; } @Override public void visitEnd() { super.visitEnd(); //创建TraceMethod TraceMethod traceMethod = TraceMethod.create(0, access, className, name, desc); //如果是构造方法 if ("<init>".equals(name)) { isConstructor = true; } //判断类是否 被配置在了 黑名单中 boolean isNeedTrace = isNeedTrace(configuration, traceMethod.className, mappingCollector); //忽略空方法、get/set方法、没有局部变量的简单方法 if ((isEmptyMethod() || isGetSetMethod() || isSingleMethod()) && isNeedTrace) { //忽略方法递增 ignoreCount.incrementAndGet(); //加入到被忽略方法 map collectedIgnoreMethodMap.put(traceMethod.getMethodName(), traceMethod); return; } //不在黑名单中而且没在在methodMapping中配置过的方法加入待插桩的集合; if (isNeedTrace && !collectedMethodMap.containsKey(traceMethod.getMethodName())) { traceMethod.id = methodId.incrementAndGet(); collectedMethodMap.put(traceMethod.getMethodName(), traceMethod); incrementCount.incrementAndGet(); } else if (!isNeedTrace && !collectedIgnoreMethodMap.containsKey(traceMethod.className)) {//在黑名单中而且没在在methodMapping中配置过的方法加入ignore插桩的集合 ignoreCount.incrementAndGet(); collectedIgnoreMethodMap.put(traceMethod.getMethodName(), traceMethod); } } /** * 判断是否是 get方法 * @return */ private boolean isGetSetMethod() { int ignoreCount = 0; ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); int opcode = insnNode.getOpcode(); if (-1 == opcode) { continue; } if (opcode != Opcodes.GETFIELD && opcode != Opcodes.GETSTATIC && opcode != Opcodes.H_GETFIELD && opcode != Opcodes.H_GETSTATIC && opcode != Opcodes.RETURN && opcode != Opcodes.ARETURN && opcode != Opcodes.DRETURN && opcode != Opcodes.FRETURN && opcode != Opcodes.LRETURN && opcode != Opcodes.IRETURN && opcode != Opcodes.PUTFIELD && opcode != Opcodes.PUTSTATIC && opcode != Opcodes.H_PUTFIELD && opcode != Opcodes.H_PUTSTATIC && opcode > Opcodes.SALOAD) { if (isConstructor && opcode == Opcodes.INVOKESPECIAL) { ignoreCount++; if (ignoreCount > 1) { return false; } continue; } return false; } } return true; } private boolean isSingleMethod() { ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); int opcode = insnNode.getOpcode(); if (-1 == opcode) { continue; } else if (Opcodes.INVOKEVIRTUAL <= opcode && opcode <= Opcodes.INVOKEDYNAMIC) { return false; } } return true; } private boolean isEmptyMethod() { ListIterator<AbstractInsnNode> iterator = instructions.iterator(); while (iterator.hasNext()) { AbstractInsnNode insnNode = iterator.next(); int opcode = insnNode.getOpcode(); if (-1 == opcode) { continue; } else { return false; } } return true; } } public static boolean isWindowFocusChangeMethod(String name, String desc) { return null != name && null != desc && name.equals(TraceBuildConstants.MATRIX_TRACE_ON_WINDOW_FOCUS_METHOD) && desc.equals(TraceBuildConstants.MATRIX_TRACE_ON_WINDOW_FOCUS_METHOD_ARGS); } /** * 是否需要 被插桩代码 * @param configuration * @param clsName * @param mappingCollector * @return */ public static boolean isNeedTrace(Configuration configuration, String clsName, MappingCollector mappingCollector) { boolean isNeed = true; //该类是否在黑名单中 if (configuration.blackSet.contains(clsName)) { isNeed = false; } else { if (null != mappingCollector) { //通过混淆过的 类型 获取原始类名 clsName = mappingCollector.originalClassName(clsName, clsName); } clsName = clsName.replaceAll("/", "."); for (String packageName : configuration.blackSet) { //是否属于黑名单中的配置 if (clsName.startsWith(packageName.replaceAll("/", "."))) { isNeed = false; break; } } } return isNeed; } private void listClassFiles(ArrayList<File> classFiles, File folder) { File[] files = folder.listFiles(); if (null == files) { Log.e(TAG, "[listClassFiles] files is null! %s", folder.getAbsolutePath()); return; } for (File file : files) { if (file == null) { continue; } if (file.isDirectory()) { listClassFiles(classFiles, file); } else if (isNeedTraceFile(file.getName())) { classFiles.add(file); } } } /** * 判断是否是需要被插桩的文件 * @param fileName * @return */ public static boolean isNeedTraceFile(String fileName) { if (fileName.endsWith(".class")) { for (String unTraceCls : TraceBuildConstants.UN_TRACE_CLASS) { if (fileName.contains(unTraceCls)) { return false; } } } else { return false; } return true; } }
true
58696_0
package com.qingcheng.controller.goods; import com.alibaba.dubbo.config.annotation.Reference; import com.qingcheng.service.goods.StockBackService; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class SkuTask { @Reference private StockBackService stockBackService; /** * 间隔一小时执行库存回滚 */ @Scheduled(cron = "0 * * * * ?") public void skuStockBack(){ System.out.println("库存回滚开始"); stockBackService.doBack(); System.out.println("库存回滚结束"); } }
NiLuogege/myqingchengcode
qingcheng_web_manager/src/main/java/com/qingcheng/controller/goods/SkuTask.java
167
/** * 间隔一小时执行库存回滚 */
block_comment
zh-cn
package com.qingcheng.controller.goods; import com.alibaba.dubbo.config.annotation.Reference; import com.qingcheng.service.goods.StockBackService; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class SkuTask { @Reference private StockBackService stockBackService; /** * 间隔一 <SUF>*/ @Scheduled(cron = "0 * * * * ?") public void skuStockBack(){ System.out.println("库存回滚开始"); stockBackService.doBack(); System.out.println("库存回滚结束"); } }
true
20610_2
package com.alibaba.it.asset.web.workflow.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author keray * @date 2018/08/30 下午1:54 * 性能计时工具 */ public class TimingUtil { private final static Logger log = LoggerFactory.getLogger(TimingUtil.class); private static final ThreadLocal<Map<String,Long>> THREAD_LOCAL = new ThreadLocal<>(); /** * 基本计时器 只能单流程执行 start -> stop * */ public static void start() { start("simple"); } /** * 单流程 <b>停止</b> 于上面的start配合使用 * */ public static void stop(String sign) { stop("simple",sign,true); } /** * 可暂停计时,提供一个计时签名 * */ public static void start(String sign) { try { Map<String, Long> map = THREAD_LOCAL.get(); if (map == null) { map = new HashMap<>(4); map.put(sign + "_time",0L); THREAD_LOCAL.set(map); } else if (!map.containsKey(sign + "_time")) { map.put(sign + "_time",0L); } map.put(sign,System.currentTimeMillis()); }catch (Exception ignored) {} } /** * 重入计时停止 于上面的start配合使用 * @param stop * stop 为false时 计时不会停止 只是 <b>暂停</b>!!! * stop 为true时 计时<b>停止</b> 进行日志输出 * */ public static void stop(String sign,boolean stop) { stop(sign, sign,stop); } private static void stop(String sign,String desc,boolean stop) { try { Map<String, Long> map = THREAD_LOCAL.get(); if (stop) { log.info("{} 耗时 : {}",desc,(map.get(sign + "_time") + (System.currentTimeMillis() - map.get(sign)))); } else { map.put(sign + "_time",map.get(sign + "_time") + (System.currentTimeMillis() - map.get(sign))); } }catch (Exception ignored) {} } public static void stop() { THREAD_LOCAL.remove(); } }
NiX-Team/NiX-Joy
java/util/TimingUtil.java
588
/** * 单流程 <b>停止</b> 于上面的start配合使用 * */
block_comment
zh-cn
package com.alibaba.it.asset.web.workflow.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; /** * @author keray * @date 2018/08/30 下午1:54 * 性能计时工具 */ public class TimingUtil { private final static Logger log = LoggerFactory.getLogger(TimingUtil.class); private static final ThreadLocal<Map<String,Long>> THREAD_LOCAL = new ThreadLocal<>(); /** * 基本计时器 只能单流程执行 start -> stop * */ public static void start() { start("simple"); } /** * 单流程 <SUF>*/ public static void stop(String sign) { stop("simple",sign,true); } /** * 可暂停计时,提供一个计时签名 * */ public static void start(String sign) { try { Map<String, Long> map = THREAD_LOCAL.get(); if (map == null) { map = new HashMap<>(4); map.put(sign + "_time",0L); THREAD_LOCAL.set(map); } else if (!map.containsKey(sign + "_time")) { map.put(sign + "_time",0L); } map.put(sign,System.currentTimeMillis()); }catch (Exception ignored) {} } /** * 重入计时停止 于上面的start配合使用 * @param stop * stop 为false时 计时不会停止 只是 <b>暂停</b>!!! * stop 为true时 计时<b>停止</b> 进行日志输出 * */ public static void stop(String sign,boolean stop) { stop(sign, sign,stop); } private static void stop(String sign,String desc,boolean stop) { try { Map<String, Long> map = THREAD_LOCAL.get(); if (stop) { log.info("{} 耗时 : {}",desc,(map.get(sign + "_time") + (System.currentTimeMillis() - map.get(sign)))); } else { map.put(sign + "_time",map.get(sign + "_time") + (System.currentTimeMillis() - map.get(sign))); } }catch (Exception ignored) {} } public static void stop() { THREAD_LOCAL.remove(); } }
true
59051_0
package io.niceseason.gulimall.cart.vo; import java.math.BigDecimal; import java.util.List; public class CartVo { /** * 购物车子项信息 */ List<CartItemVo> items; /** * 商品数量 */ private Integer countNum; /** * 商品类型数量 */ private Integer countType; /** * 商品总价 */ private BigDecimal totalAmount; /** * 减免价格 */ private BigDecimal reduce = new BigDecimal("0.00"); public List<CartItemVo> getItems() { return items; } public void setItems(List<CartItemVo> items) { this.items = items; } public Integer getCountNum() { int count=0; if (items != null && items.size() > 0) { for (CartItemVo item : items) { count += item.getCount(); } } return count; } public void setCountNum(Integer countNum) { this.countNum = countNum; } public Integer getCountType() { int count=0; if (items != null && items.size() > 0) { for (CartItemVo item : items) { count += 1; } } return count; } public void setCountType(Integer countType) { this.countType = countType; } public BigDecimal getTotalAmount() { BigDecimal total = new BigDecimal(0); if (items != null && items.size() > 0) { for (CartItemVo item : items) { total.add(item.getTotalPrice()); } } total.subtract(reduce); return total; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } public BigDecimal getReduce() { return reduce; } public void setReduce(BigDecimal reduce) { this.reduce = reduce; } }
NiceSeason/gulimall-learning
gulimall-cart/src/main/java/io/niceseason/gulimall/cart/vo/CartVo.java
462
/** * 购物车子项信息 */
block_comment
zh-cn
package io.niceseason.gulimall.cart.vo; import java.math.BigDecimal; import java.util.List; public class CartVo { /** * 购物车 <SUF>*/ List<CartItemVo> items; /** * 商品数量 */ private Integer countNum; /** * 商品类型数量 */ private Integer countType; /** * 商品总价 */ private BigDecimal totalAmount; /** * 减免价格 */ private BigDecimal reduce = new BigDecimal("0.00"); public List<CartItemVo> getItems() { return items; } public void setItems(List<CartItemVo> items) { this.items = items; } public Integer getCountNum() { int count=0; if (items != null && items.size() > 0) { for (CartItemVo item : items) { count += item.getCount(); } } return count; } public void setCountNum(Integer countNum) { this.countNum = countNum; } public Integer getCountType() { int count=0; if (items != null && items.size() > 0) { for (CartItemVo item : items) { count += 1; } } return count; } public void setCountType(Integer countType) { this.countType = countType; } public BigDecimal getTotalAmount() { BigDecimal total = new BigDecimal(0); if (items != null && items.size() > 0) { for (CartItemVo item : items) { total.add(item.getTotalPrice()); } } total.subtract(reduce); return total; } public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; } public BigDecimal getReduce() { return reduce; } public void setReduce(BigDecimal reduce) { this.reduce = reduce; } }
true
19507_3
package cc.xiaoquer.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Nicholas on 2018/3/16. */ public class JSONParsingUtil { public static void main(String[] args) throws IOException { // String rawJson = "{\"expand\":\"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations\",\"id\":\"24976\",\"self\":\"http://99.48.46.160:8080/rest/agile/1.0/issue/24976\",\"key\":\"BAOSHENG-112\",\"fields\":{\"issuetype\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issuetype/10006\",\"id\":\"10006\",\"description\":\"问题的子任务\",\"iconUrl\":\"http://99.48.46.160:8080/secure/viewavatar?size=xsmall&avatarId=10316&avatarType=issuetype\",\"name\":\"子任务\",\"subtask\":true,\"avatarId\":10316},\"parent\":{\"id\":\"24975\",\"key\":\"BAOSHENG-111\",\"self\":\"http://99.48.46.160:8080/rest/api/2/issue/24975\",\"fields\":{\"summary\":\"【技术准备事宜】运维技术准备工作\",\"status\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/status/10701\",\"description\":\"\",\"iconUrl\":\"http://99.48.46.160:8080/\",\"name\":\"进行中\",\"id\":\"10701\",\"statusCategory\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/statuscategory/4\",\"id\":4,\"key\":\"indeterminate\",\"colorName\":\"yellow\",\"name\":\"进行中\"}},\"priority\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/priority/3\",\"iconUrl\":\"http://99.48.46.160:8080/images/icons/priorities/medium.svg\",\"name\":\"Medium\",\"id\":\"3\"},\"issuetype\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issuetype/10001\",\"id\":\"10001\",\"description\":\"gh.issue.story.desc\",\"iconUrl\":\"http://99.48.46.160:8080/images/icons/issuetypes/story.svg\",\"name\":\"Story\",\"subtask\":false}}},\"timespent\":null,\"sprint\":{\"id\":234,\"self\":\"http://99.48.46.160:8080/rest/agile/1.0/sprint/234\",\"state\":\"active\",\"name\":\"BAOSHENG Sprint 0410\",\"startDate\":\"2018-03-07T18:23:57.152+08:00\",\"endDate\":\"2018-03-21T06:23:00.000+08:00\",\"originBoardId\":154},\"project\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/project/11501\",\"id\":\"11501\",\"key\":\"BAOSHENG\",\"name\":\"宝生项目\",\"avatarUrls\":{\"48x48\":\"http://99.48.46.160:8080/secure/projectavatar?avatarId=10324\",\"24x24\":\"http://99.48.46.160:8080/secure/projectavatar?size=small&avatarId=10324\",\"16x16\":\"http://99.48.46.160:8080/secure/projectavatar?size=xsmall&avatarId=10324\",\"32x32\":\"http://99.48.46.160:8080/secure/projectavatar?size=medium&avatarId=10324\"}},\"fixVersions\":[],\"customfield_11001\":34567.0,\"aggregatetimespent\":null,\"resolution\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/resolution/10301\",\"id\":\"10301\",\"description\":\"GreenHopper Managed Resolution\",\"name\":\"完成\"},\"customfield_10104\":null,\"customfield_10105\":null,\"customfield_10106\":null,\"customfield_10107\":null,\"customfield_10900\":null,\"resolutiondate\":\"2018-03-10T11:25:05.000+0800\",\"workratio\":0,\"lastViewed\":\"2018-03-16T17:34:54.427+0800\",\"watches\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issue/BAOSHENG-112/watchers\",\"watchCount\":1,\"isWatching\":false},\"created\":\"2018-03-09T10:20:10.000+0800\",\"priority\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/priority/3\",\"iconUrl\":\"http://99.48.46.160:8080/images/icons/priorities/medium.svg\",\"name\":\"Medium\",\"id\":\"3\"},\"customfield_10100\":null,\"customfield_10101\":null,\"customfield_10102\":null,\"labels\":[],\"timeestimate\":18000,\"aggregatetimeoriginalestimate\":18000,\"versions\":[],\"issuelinks\":[],\"assignee\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/user?username=debao.fan\",\"name\":\"debao.fan\",\"key\":\"debao.fan\",\"emailAddress\":\"[email protected]\",\"avatarUrls\":{\"48x48\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=48\",\"24x24\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=24\",\"16x16\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=16\",\"32x32\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=32\"},\"displayName\":\"樊得宝\",\"active\":true,\"timeZone\":\"Asia/Shanghai\"},\"updated\":\"2018-03-16T17:34:54.000+0800\",\"status\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/status/10001\",\"description\":\"\",\"iconUrl\":\"http://99.48.46.160:8080/\",\"name\":\"完成\",\"id\":\"10001\",\"statusCategory\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/statuscategory/3\",\"id\":3,\"key\":\"done\",\"colorName\":\"green\",\"name\":\"Done\"}},\"components\":[],\"timeoriginalestimate\":18000,\"description\":null,\"timetracking\":{\"originalEstimate\":\"5h\",\"remainingEstimate\":\"5h\",\"originalEstimateSeconds\":18000,\"remainingEstimateSeconds\":18000},\"attachment\":[],\"aggregatetimeestimate\":18000,\"flagged\":false,\"summary\":\"完成私服\",\"creator\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/user?username=huiqi.hu\",\"name\":\"huiqi.hu\",\"key\":\"huiqi.hu\",\"emailAddress\":\"[email protected]\",\"avatarUrls\":{\"48x48\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=48\",\"24x24\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=24\",\"16x16\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=16\",\"32x32\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=32\"},\"displayName\":\"胡晖祺\",\"active\":true,\"timeZone\":\"Asia/Shanghai\"},\"subtasks\":[],\"reporter\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/user?username=huiqi.hu\",\"name\":\"huiqi.hu\",\"key\":\"huiqi.hu\",\"emailAddress\":\"[email protected]\",\"avatarUrls\":{\"48x48\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=48\",\"24x24\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=24\",\"16x16\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=16\",\"32x32\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=32\"},\"displayName\":\"胡晖祺\",\"active\":true,\"timeZone\":\"Asia/Shanghai\"},\"customfield_10000\":\"0|i01zfz:\",\"aggregateprogress\":{\"progress\":0,\"total\":18000,\"percent\":0},\"customfield_10001\":[\"com.atlassian.greenhopper.service.sprint.Sprint@542e3b8c[id=234,rapidViewId=154,state=ACTIVE,name=BAOSHENG Sprint 0410,startDate=2018-03-07T18:23:57.152+08:00,endDate=2018-03-21T06:23:00.000+08:00,completeDate=<null>,sequence=234]\"],\"customfield_10002\":null,\"customfield_10200\":null,\"environment\":null,\"duedate\":null,\"progress\":{\"progress\":0,\"total\":18000,\"percent\":0},\"comment\":{\"comments\":[],\"maxResults\":0,\"total\":0,\"startAt\":0},\"votes\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issue/BAOSHENG-112/votes\",\"votes\":0,\"hasVoted\":false},\"worklog\":{\"startAt\":0,\"maxResults\":20,\"total\":0,\"worklogs\":[]}}}"; String rawJson = "{\n" + " \"name\": \"三班\",\n" + " \"students\": [\n" + " {\n" + " \"age\": 25,\n" + " \"gender\": \"female\",\n" + " \"grades\": \"三班\",\n" + " \"name\": \"露西\",\n" + " \"score\": {\n" + " \"网络协议\": 98,\n" + " \"JavaEE\": 92,\n" + " \"计算机基础\": 93\n" + " },\n" + " \"weight\": 51.3\n" + " },\n" + " {\n" + " \"age\": 26,\n" + " \"gender\": \"male\",\n" + " \"grades\": \"三班\",\n" + " \"name\": \"杰克\",\n" + " \"score\": {\n" + " \"网络安全\": 75,\n" + " \"Linux操作系统\": 81,\n" + " \"计算机基础\": 92\n" + " },\n" + " \"weight\": 66.5\n" + " },\n" + " {\n" + " \"age\": 25,\n" + " \"gender\": \"female\",\n" + " \"grades\": \"三班\",\n" + " \"name\": \"莉莉\",\n" + " \"score\": {\n" + " \"网络安全\": 95,\n" + " \"Linux操作系统\": 98,\n" + " \"SQL数据库\": 88,\n" + " \"数据结构\": 89\n" + " },\n" + " \"weight\": 55\n" + " }\n" + " ]\n" + "}"; Map<String, String> allMappings = new LinkedHashMap<String, String>(); getAllMappings(null, rawJson, allMappings); for (String key : allMappings.keySet()) { System.out.println(key + " ============= " + allMappings.get(key)); } System.out.println("key:" + getValueByExp(allMappings, "students>0>score>JavaEE")); System.out.println("correct exp:" +getValueByExp(allMappings, "students>.*>name")); System.out.println("wrong exp:" + getValueByExp(allMappings, "&*(&()!@$students>.*>name")); } public static Map<String, String> getAllMapping(String json) { Map<String, String> allMappings = new LinkedHashMap<String, String>(); getAllMappings(null, json, allMappings); return allMappings; } /**根据表达式,将匹配的Key的值组装展示 1. 若key精确匹配只有一个,如fields>customfile_10000 --> nicholas.qu, 则直接返回 nicholas.qu 2. 若key无法精确匹配,只能模糊匹配,如Map中的条目有: "fields>customfield_121001>0>self" -> "http://jira.immd.cn/rest/api/2/customFieldOption/12506" "fields>customfield_12101>0>id" -> "12506" "fields>customfield_12101>0>value" -> "activity(活动dubbo服务)" "fields>customfield_12101>1>self" -> "http://jira.immd.cn/rest/api/2/customFieldOption/12508" "fields>customfield_12101>1>id" -> "12508" "fields>customfield_12101>1>value" -> "activity-management(活动平台配置管理)" 若需要展示的是value的合集,则配置的expression表达式应该是 fields>customfield_12101>.*>value **/ public static String COMMA = ", "; public static String getValueByExp(Map<String, String> jsonMapping, String exp) { String value = jsonMapping.get(exp); if (StringUtils.isNotBlank(value)) { return value; } try { Pattern pattern = Pattern.compile(exp); StringBuffer sb = new StringBuffer(); for (String key : jsonMapping.keySet()) { Matcher m = pattern.matcher(key); if (m.matches()) { sb.append(jsonMapping.get(key)).append(COMMA); } } return StringUtils.stripEnd(sb.toString(), COMMA); } catch (Exception e) { return ""; } } private static void getAllMappings(String key, String valueJsonStr, Map<String, String> allMappings) { if (valueJsonStr == null && key == null) { return; } int type = checkType(valueJsonStr); //已是基本字符串,无法继续递归! if (type == 0) { allMappings.put(key, valueJsonStr); return; } else if (type == 1) { JSONObject json = JSON.parseObject(valueJsonStr); for (String k1 : json.keySet()) { String v = json.getString(k1); String k = (key == null ? k1 : key + ">" + k1); getAllMappings(k, v, allMappings); } } else if (type == 2) { JSONArray arr = JSON.parseArray(valueJsonStr); for (int i = 0; i < arr.size(); i++) { String obj = arr.getString(i); String k = (key == null ? String.valueOf(i) : key + ">" + i); getAllMappings(k, obj, allMappings); } } } /** * 0 - String * 1 - JsonObject * 2 - Array */ public static int checkType(String jsonStr){ if (jsonStr == null || jsonStr.trim().length() == 0) return 0; try { JSON.parseArray(jsonStr); return 2; } catch (Exception e) { } try { JSON.parseObject(jsonStr); return 1; } catch (Exception e) { } return 0; } public static boolean isString(int type) { return 0 == type; } public static boolean isJsonObject(int type) { return 1 == type; } public static boolean isArray(int type) { return 2 == type; } }
NicholasQu/JiraScrumCardsPrinter
src/main/java/cc/xiaoquer/utils/JSONParsingUtil.java
4,719
//已是基本字符串,无法继续递归!
line_comment
zh-cn
package cc.xiaoquer.utils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Nicholas on 2018/3/16. */ public class JSONParsingUtil { public static void main(String[] args) throws IOException { // String rawJson = "{\"expand\":\"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations\",\"id\":\"24976\",\"self\":\"http://99.48.46.160:8080/rest/agile/1.0/issue/24976\",\"key\":\"BAOSHENG-112\",\"fields\":{\"issuetype\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issuetype/10006\",\"id\":\"10006\",\"description\":\"问题的子任务\",\"iconUrl\":\"http://99.48.46.160:8080/secure/viewavatar?size=xsmall&avatarId=10316&avatarType=issuetype\",\"name\":\"子任务\",\"subtask\":true,\"avatarId\":10316},\"parent\":{\"id\":\"24975\",\"key\":\"BAOSHENG-111\",\"self\":\"http://99.48.46.160:8080/rest/api/2/issue/24975\",\"fields\":{\"summary\":\"【技术准备事宜】运维技术准备工作\",\"status\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/status/10701\",\"description\":\"\",\"iconUrl\":\"http://99.48.46.160:8080/\",\"name\":\"进行中\",\"id\":\"10701\",\"statusCategory\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/statuscategory/4\",\"id\":4,\"key\":\"indeterminate\",\"colorName\":\"yellow\",\"name\":\"进行中\"}},\"priority\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/priority/3\",\"iconUrl\":\"http://99.48.46.160:8080/images/icons/priorities/medium.svg\",\"name\":\"Medium\",\"id\":\"3\"},\"issuetype\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issuetype/10001\",\"id\":\"10001\",\"description\":\"gh.issue.story.desc\",\"iconUrl\":\"http://99.48.46.160:8080/images/icons/issuetypes/story.svg\",\"name\":\"Story\",\"subtask\":false}}},\"timespent\":null,\"sprint\":{\"id\":234,\"self\":\"http://99.48.46.160:8080/rest/agile/1.0/sprint/234\",\"state\":\"active\",\"name\":\"BAOSHENG Sprint 0410\",\"startDate\":\"2018-03-07T18:23:57.152+08:00\",\"endDate\":\"2018-03-21T06:23:00.000+08:00\",\"originBoardId\":154},\"project\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/project/11501\",\"id\":\"11501\",\"key\":\"BAOSHENG\",\"name\":\"宝生项目\",\"avatarUrls\":{\"48x48\":\"http://99.48.46.160:8080/secure/projectavatar?avatarId=10324\",\"24x24\":\"http://99.48.46.160:8080/secure/projectavatar?size=small&avatarId=10324\",\"16x16\":\"http://99.48.46.160:8080/secure/projectavatar?size=xsmall&avatarId=10324\",\"32x32\":\"http://99.48.46.160:8080/secure/projectavatar?size=medium&avatarId=10324\"}},\"fixVersions\":[],\"customfield_11001\":34567.0,\"aggregatetimespent\":null,\"resolution\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/resolution/10301\",\"id\":\"10301\",\"description\":\"GreenHopper Managed Resolution\",\"name\":\"完成\"},\"customfield_10104\":null,\"customfield_10105\":null,\"customfield_10106\":null,\"customfield_10107\":null,\"customfield_10900\":null,\"resolutiondate\":\"2018-03-10T11:25:05.000+0800\",\"workratio\":0,\"lastViewed\":\"2018-03-16T17:34:54.427+0800\",\"watches\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issue/BAOSHENG-112/watchers\",\"watchCount\":1,\"isWatching\":false},\"created\":\"2018-03-09T10:20:10.000+0800\",\"priority\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/priority/3\",\"iconUrl\":\"http://99.48.46.160:8080/images/icons/priorities/medium.svg\",\"name\":\"Medium\",\"id\":\"3\"},\"customfield_10100\":null,\"customfield_10101\":null,\"customfield_10102\":null,\"labels\":[],\"timeestimate\":18000,\"aggregatetimeoriginalestimate\":18000,\"versions\":[],\"issuelinks\":[],\"assignee\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/user?username=debao.fan\",\"name\":\"debao.fan\",\"key\":\"debao.fan\",\"emailAddress\":\"[email protected]\",\"avatarUrls\":{\"48x48\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=48\",\"24x24\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=24\",\"16x16\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=16\",\"32x32\":\"http://www.gravatar.com/avatar/b85137662d8823723131d5e9e98e6680?d=mm&s=32\"},\"displayName\":\"樊得宝\",\"active\":true,\"timeZone\":\"Asia/Shanghai\"},\"updated\":\"2018-03-16T17:34:54.000+0800\",\"status\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/status/10001\",\"description\":\"\",\"iconUrl\":\"http://99.48.46.160:8080/\",\"name\":\"完成\",\"id\":\"10001\",\"statusCategory\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/statuscategory/3\",\"id\":3,\"key\":\"done\",\"colorName\":\"green\",\"name\":\"Done\"}},\"components\":[],\"timeoriginalestimate\":18000,\"description\":null,\"timetracking\":{\"originalEstimate\":\"5h\",\"remainingEstimate\":\"5h\",\"originalEstimateSeconds\":18000,\"remainingEstimateSeconds\":18000},\"attachment\":[],\"aggregatetimeestimate\":18000,\"flagged\":false,\"summary\":\"完成私服\",\"creator\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/user?username=huiqi.hu\",\"name\":\"huiqi.hu\",\"key\":\"huiqi.hu\",\"emailAddress\":\"[email protected]\",\"avatarUrls\":{\"48x48\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=48\",\"24x24\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=24\",\"16x16\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=16\",\"32x32\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=32\"},\"displayName\":\"胡晖祺\",\"active\":true,\"timeZone\":\"Asia/Shanghai\"},\"subtasks\":[],\"reporter\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/user?username=huiqi.hu\",\"name\":\"huiqi.hu\",\"key\":\"huiqi.hu\",\"emailAddress\":\"[email protected]\",\"avatarUrls\":{\"48x48\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=48\",\"24x24\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=24\",\"16x16\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=16\",\"32x32\":\"http://www.gravatar.com/avatar/9ea755d452f01e7d5c95e63e2ae1c49e?d=mm&s=32\"},\"displayName\":\"胡晖祺\",\"active\":true,\"timeZone\":\"Asia/Shanghai\"},\"customfield_10000\":\"0|i01zfz:\",\"aggregateprogress\":{\"progress\":0,\"total\":18000,\"percent\":0},\"customfield_10001\":[\"com.atlassian.greenhopper.service.sprint.Sprint@542e3b8c[id=234,rapidViewId=154,state=ACTIVE,name=BAOSHENG Sprint 0410,startDate=2018-03-07T18:23:57.152+08:00,endDate=2018-03-21T06:23:00.000+08:00,completeDate=<null>,sequence=234]\"],\"customfield_10002\":null,\"customfield_10200\":null,\"environment\":null,\"duedate\":null,\"progress\":{\"progress\":0,\"total\":18000,\"percent\":0},\"comment\":{\"comments\":[],\"maxResults\":0,\"total\":0,\"startAt\":0},\"votes\":{\"self\":\"http://99.48.46.160:8080/rest/api/2/issue/BAOSHENG-112/votes\",\"votes\":0,\"hasVoted\":false},\"worklog\":{\"startAt\":0,\"maxResults\":20,\"total\":0,\"worklogs\":[]}}}"; String rawJson = "{\n" + " \"name\": \"三班\",\n" + " \"students\": [\n" + " {\n" + " \"age\": 25,\n" + " \"gender\": \"female\",\n" + " \"grades\": \"三班\",\n" + " \"name\": \"露西\",\n" + " \"score\": {\n" + " \"网络协议\": 98,\n" + " \"JavaEE\": 92,\n" + " \"计算机基础\": 93\n" + " },\n" + " \"weight\": 51.3\n" + " },\n" + " {\n" + " \"age\": 26,\n" + " \"gender\": \"male\",\n" + " \"grades\": \"三班\",\n" + " \"name\": \"杰克\",\n" + " \"score\": {\n" + " \"网络安全\": 75,\n" + " \"Linux操作系统\": 81,\n" + " \"计算机基础\": 92\n" + " },\n" + " \"weight\": 66.5\n" + " },\n" + " {\n" + " \"age\": 25,\n" + " \"gender\": \"female\",\n" + " \"grades\": \"三班\",\n" + " \"name\": \"莉莉\",\n" + " \"score\": {\n" + " \"网络安全\": 95,\n" + " \"Linux操作系统\": 98,\n" + " \"SQL数据库\": 88,\n" + " \"数据结构\": 89\n" + " },\n" + " \"weight\": 55\n" + " }\n" + " ]\n" + "}"; Map<String, String> allMappings = new LinkedHashMap<String, String>(); getAllMappings(null, rawJson, allMappings); for (String key : allMappings.keySet()) { System.out.println(key + " ============= " + allMappings.get(key)); } System.out.println("key:" + getValueByExp(allMappings, "students>0>score>JavaEE")); System.out.println("correct exp:" +getValueByExp(allMappings, "students>.*>name")); System.out.println("wrong exp:" + getValueByExp(allMappings, "&*(&()!@$students>.*>name")); } public static Map<String, String> getAllMapping(String json) { Map<String, String> allMappings = new LinkedHashMap<String, String>(); getAllMappings(null, json, allMappings); return allMappings; } /**根据表达式,将匹配的Key的值组装展示 1. 若key精确匹配只有一个,如fields>customfile_10000 --> nicholas.qu, 则直接返回 nicholas.qu 2. 若key无法精确匹配,只能模糊匹配,如Map中的条目有: "fields>customfield_121001>0>self" -> "http://jira.immd.cn/rest/api/2/customFieldOption/12506" "fields>customfield_12101>0>id" -> "12506" "fields>customfield_12101>0>value" -> "activity(活动dubbo服务)" "fields>customfield_12101>1>self" -> "http://jira.immd.cn/rest/api/2/customFieldOption/12508" "fields>customfield_12101>1>id" -> "12508" "fields>customfield_12101>1>value" -> "activity-management(活动平台配置管理)" 若需要展示的是value的合集,则配置的expression表达式应该是 fields>customfield_12101>.*>value **/ public static String COMMA = ", "; public static String getValueByExp(Map<String, String> jsonMapping, String exp) { String value = jsonMapping.get(exp); if (StringUtils.isNotBlank(value)) { return value; } try { Pattern pattern = Pattern.compile(exp); StringBuffer sb = new StringBuffer(); for (String key : jsonMapping.keySet()) { Matcher m = pattern.matcher(key); if (m.matches()) { sb.append(jsonMapping.get(key)).append(COMMA); } } return StringUtils.stripEnd(sb.toString(), COMMA); } catch (Exception e) { return ""; } } private static void getAllMappings(String key, String valueJsonStr, Map<String, String> allMappings) { if (valueJsonStr == null && key == null) { return; } int type = checkType(valueJsonStr); //已是 <SUF> if (type == 0) { allMappings.put(key, valueJsonStr); return; } else if (type == 1) { JSONObject json = JSON.parseObject(valueJsonStr); for (String k1 : json.keySet()) { String v = json.getString(k1); String k = (key == null ? k1 : key + ">" + k1); getAllMappings(k, v, allMappings); } } else if (type == 2) { JSONArray arr = JSON.parseArray(valueJsonStr); for (int i = 0; i < arr.size(); i++) { String obj = arr.getString(i); String k = (key == null ? String.valueOf(i) : key + ">" + i); getAllMappings(k, obj, allMappings); } } } /** * 0 - String * 1 - JsonObject * 2 - Array */ public static int checkType(String jsonStr){ if (jsonStr == null || jsonStr.trim().length() == 0) return 0; try { JSON.parseArray(jsonStr); return 2; } catch (Exception e) { } try { JSON.parseObject(jsonStr); return 1; } catch (Exception e) { } return 0; } public static boolean isString(int type) { return 0 == type; } public static boolean isJsonObject(int type) { return 1 == type; } public static boolean isArray(int type) { return 2 == type; } }
true
61832_10
import java.util.Scanner; /* * 哈希表数据结构: * 1,哈希表实际是由链表组成的数组。 * 2,增删改查元素的时候根据散列函数算法确定把元素加到哪个下标下的链表里。 * 3,JDK集合中的Hashtable.java就是一个哈希表,只是设计的功能更复杂,但底层是一样的。 */ public class HashTableTest { public static void main(String[] args){ //单链表测试 //SingleLinkedList list = new SingleLinkedList(); //listDo(list); //哈希表 HashTableDemo hashTable = new HashTableDemo(10); tableDo(hashTable); } //哈希表测试,增删改查完成,改是在增的功能里,遇到相同id的直接覆盖旧节点。 public static void tableDo(HashTableDemo hashTable){ while(true){ Scanner scan = new Scanner(System.in); System.out.println("添加:add"); System.out.println("展示:list"); System.out.println("查找:find"); System.out.println("删除:delete"); System.out.println("退出:exit"); String order = scan.next(); switch (order){ case "add": System.out.print("请输入id:"); int id = scan.nextInt(); System.out.print("请输入name:"); String name = scan.next(); //hashTable.add(new UserNode(id,name)); //新节点添加到链表最后 hashTable.addByOrder(new UserNode(id,name)); //有序添加 break; case "list": hashTable.showTable(); break; case "find": System.out.print("请输入要查找的id:"); id = scan.nextInt(); UserNode user = hashTable.findById(id); System.out.println("查找结果==>" + user); break; case "delete": System.out.print("请输入要删除的id:"); id = scan.nextInt(); hashTable.deleteById(id); break; case "exit": scan.close(); //io流一定要关闭 System.exit(0); break; default: System.out.println("请输入正确的代号!!"); break; } } } //单链表测试 public static void listDo(SingleLinkedList list){ while(true){ Scanner scan = new Scanner(System.in); System.out.println("添加:add"); System.out.println("展示:list"); System.out.println("退出:exit"); String order = scan.next(); switch (order){ case "add": System.out.print("请输入id:"); int id = scan.nextInt(); System.out.print("请输入name:"); String name = scan.next(); list.addByOrder(new UserNode(id,name)); break; case "list": list.show(); break; case "exit": scan.close(); //io流一定要关闭 System.exit(0); default: break; } } } }
NicholasRabbit/Data-Structure-and-Algorithm
8_HashTable/HashTableTest.java
808
//io流一定要关闭
line_comment
zh-cn
import java.util.Scanner; /* * 哈希表数据结构: * 1,哈希表实际是由链表组成的数组。 * 2,增删改查元素的时候根据散列函数算法确定把元素加到哪个下标下的链表里。 * 3,JDK集合中的Hashtable.java就是一个哈希表,只是设计的功能更复杂,但底层是一样的。 */ public class HashTableTest { public static void main(String[] args){ //单链表测试 //SingleLinkedList list = new SingleLinkedList(); //listDo(list); //哈希表 HashTableDemo hashTable = new HashTableDemo(10); tableDo(hashTable); } //哈希表测试,增删改查完成,改是在增的功能里,遇到相同id的直接覆盖旧节点。 public static void tableDo(HashTableDemo hashTable){ while(true){ Scanner scan = new Scanner(System.in); System.out.println("添加:add"); System.out.println("展示:list"); System.out.println("查找:find"); System.out.println("删除:delete"); System.out.println("退出:exit"); String order = scan.next(); switch (order){ case "add": System.out.print("请输入id:"); int id = scan.nextInt(); System.out.print("请输入name:"); String name = scan.next(); //hashTable.add(new UserNode(id,name)); //新节点添加到链表最后 hashTable.addByOrder(new UserNode(id,name)); //有序添加 break; case "list": hashTable.showTable(); break; case "find": System.out.print("请输入要查找的id:"); id = scan.nextInt(); UserNode user = hashTable.findById(id); System.out.println("查找结果==>" + user); break; case "delete": System.out.print("请输入要删除的id:"); id = scan.nextInt(); hashTable.deleteById(id); break; case "exit": scan.close(); //io流一定要关闭 System.exit(0); break; default: System.out.println("请输入正确的代号!!"); break; } } } //单链表测试 public static void listDo(SingleLinkedList list){ while(true){ Scanner scan = new Scanner(System.in); System.out.println("添加:add"); System.out.println("展示:list"); System.out.println("退出:exit"); String order = scan.next(); switch (order){ case "add": System.out.print("请输入id:"); int id = scan.nextInt(); System.out.print("请输入name:"); String name = scan.next(); list.addByOrder(new UserNode(id,name)); break; case "list": list.show(); break; case "exit": scan.close(); //io <SUF> System.exit(0); default: break; } } } }
true
53935_2
import javax.imageio.*; import java.awt.image.*; import java.io.*; public class FuzzyDetection { int mWidth, mHeight; public static void main(String[] args) { if(args == null) { return ; } FuzzyDetection fuzzyDetection = new FuzzyDetection(); String path = args[0]; File[] files = fuzzyDetection.getFiles(path); if (files == null) { System.out.println("没有提供图片文件夹路径"); return ; } File reulstFile = null; double maxScore = 0; for (File file : files) { try { BufferedImage bufferedImage = ImageIO.read(file); fuzzyDetection.mWidth = bufferedImage.getWidth(); fuzzyDetection.mHeight = bufferedImage.getHeight(); int []gray = fuzzyDetection.grayImage(bufferedImage); int []pixes = fuzzyDetection.convolution(gray); double nowResult = fuzzyDetection.calcVariance(pixes); System.out.print("这个图片名字 >> " + file.getName()); System.out.println(" 清晰度是 >> " + nowResult); if (nowResult >= maxScore) { maxScore = nowResult; reulstFile = file; } } catch(Exception e) { e.printStackTrace(); } } System.out.println("这组图片中最优的是 >> " + reulstFile.getName()); System.out.println("此图片的清晰度是 >> " + maxScore); } /** * 获取指定路径下的所有png图片 */ private File[] getFiles(String paths) { if (paths == null) { return null; } File file = new File(paths); if (file.exists() && file.isDirectory()) { File[] files = file.listFiles(); if (files.length != 0) { return files; } } return null; } /** * 将颜色转换成rgb */ private int colorToRGB(int alpha, int red, int green, int blue) { int newPixel = 0; newPixel += alpha; newPixel = newPixel << 8; newPixel += red; newPixel = newPixel << 8; newPixel += green; newPixel = newPixel << 8; newPixel += blue; return newPixel; } /** * 将图片转换成灰度图数组 */ private int[] grayImage(BufferedImage image) { int width = mWidth; int height = mHeight; int [] grey = new int[width * height]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { final int color = image.getRGB(i, j); long otColor = color; final int r = (color >> 16) & 0xff; final int g = (color >> 8) & 0xff; final int b = color & 0xff; //将颜色值 使用权值方式 生成灰度值 更加准确 int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b); int newPixel = colorToRGB(255, gray, gray, gray); grey[i + j * width] = newPixel; } } return grey; } /** * 通过灰度数组与拉卡拉斯算子计算卷积值 */ private int[] convolution(int[] gray) { int[] lapras = new int[] { 0, -1, 0, -1, 4, -1, 0, -1, 0 }; int total = mWidth * mHeight; int[] output = new int[total]; int offset = 0; int k0 = 0, k1 = 0, k2 = 0; int k3 = 0, k4 = 0, k5 = 0; int k6 = 0, k7 = 0, k8 = 0; k0 = lapras[0]; k1 = lapras[1]; k2 = lapras[2]; k3 = lapras[3]; k4 = lapras[4]; k5 = lapras[5]; k6 = lapras[6]; k7 = lapras[7]; k8 = lapras[8]; int sr = 0; int r = 0; for (int row = 1; row < mHeight - 1; row++) { offset = row * mWidth; for (int col = 1; col < mWidth - 1; col++) { // red sr = k0 * ((gray[offset - mWidth + col - 1] >> 16) & 0xff) + k1 * (gray[offset - mWidth + col] & 0xff) + k2 * (gray[offset - mWidth + col + 1] & 0xff) + k3 * (gray[offset + col - 1] & 0xff) + k4 * (gray[offset + col] & 0xff) + k5 * (gray[offset + col + 1] & 0xff) + k6 * (gray[offset + mWidth + col - 1] & 0xff) + k7 * (gray[offset + mWidth + col] & 0xff) + k8 * (gray[offset + mWidth + col + 1] & 0xff); r = sr; r = r > 255 ? 255 :( (r < 0) ? 0: r); output[offset+col]= r; // for next pixel sr = 0; } } return output; } /** * 计算方差 */ private double calcVariance(int [] values) { double variance = 0;//方差 double average = 0;//平均数 int i,len = values.length; double sum=0, sum2=0; for(i = 0; i< len; i ++){ sum += values[i]; } average = sum/ len; for(i = 0; i < len; i++){ sum2 += ((double)values[i]-average)*((double)values[i]-average); } variance = sum2/ len; return variance; } }
Nichooool/FuzzyDetection
FuzzyDetection.java
1,501
/** * 将图片转换成灰度图数组 */
block_comment
zh-cn
import javax.imageio.*; import java.awt.image.*; import java.io.*; public class FuzzyDetection { int mWidth, mHeight; public static void main(String[] args) { if(args == null) { return ; } FuzzyDetection fuzzyDetection = new FuzzyDetection(); String path = args[0]; File[] files = fuzzyDetection.getFiles(path); if (files == null) { System.out.println("没有提供图片文件夹路径"); return ; } File reulstFile = null; double maxScore = 0; for (File file : files) { try { BufferedImage bufferedImage = ImageIO.read(file); fuzzyDetection.mWidth = bufferedImage.getWidth(); fuzzyDetection.mHeight = bufferedImage.getHeight(); int []gray = fuzzyDetection.grayImage(bufferedImage); int []pixes = fuzzyDetection.convolution(gray); double nowResult = fuzzyDetection.calcVariance(pixes); System.out.print("这个图片名字 >> " + file.getName()); System.out.println(" 清晰度是 >> " + nowResult); if (nowResult >= maxScore) { maxScore = nowResult; reulstFile = file; } } catch(Exception e) { e.printStackTrace(); } } System.out.println("这组图片中最优的是 >> " + reulstFile.getName()); System.out.println("此图片的清晰度是 >> " + maxScore); } /** * 获取指定路径下的所有png图片 */ private File[] getFiles(String paths) { if (paths == null) { return null; } File file = new File(paths); if (file.exists() && file.isDirectory()) { File[] files = file.listFiles(); if (files.length != 0) { return files; } } return null; } /** * 将颜色转换成rgb */ private int colorToRGB(int alpha, int red, int green, int blue) { int newPixel = 0; newPixel += alpha; newPixel = newPixel << 8; newPixel += red; newPixel = newPixel << 8; newPixel += green; newPixel = newPixel << 8; newPixel += blue; return newPixel; } /** * 将图片 <SUF>*/ private int[] grayImage(BufferedImage image) { int width = mWidth; int height = mHeight; int [] grey = new int[width * height]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { final int color = image.getRGB(i, j); long otColor = color; final int r = (color >> 16) & 0xff; final int g = (color >> 8) & 0xff; final int b = color & 0xff; //将颜色值 使用权值方式 生成灰度值 更加准确 int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b); int newPixel = colorToRGB(255, gray, gray, gray); grey[i + j * width] = newPixel; } } return grey; } /** * 通过灰度数组与拉卡拉斯算子计算卷积值 */ private int[] convolution(int[] gray) { int[] lapras = new int[] { 0, -1, 0, -1, 4, -1, 0, -1, 0 }; int total = mWidth * mHeight; int[] output = new int[total]; int offset = 0; int k0 = 0, k1 = 0, k2 = 0; int k3 = 0, k4 = 0, k5 = 0; int k6 = 0, k7 = 0, k8 = 0; k0 = lapras[0]; k1 = lapras[1]; k2 = lapras[2]; k3 = lapras[3]; k4 = lapras[4]; k5 = lapras[5]; k6 = lapras[6]; k7 = lapras[7]; k8 = lapras[8]; int sr = 0; int r = 0; for (int row = 1; row < mHeight - 1; row++) { offset = row * mWidth; for (int col = 1; col < mWidth - 1; col++) { // red sr = k0 * ((gray[offset - mWidth + col - 1] >> 16) & 0xff) + k1 * (gray[offset - mWidth + col] & 0xff) + k2 * (gray[offset - mWidth + col + 1] & 0xff) + k3 * (gray[offset + col - 1] & 0xff) + k4 * (gray[offset + col] & 0xff) + k5 * (gray[offset + col + 1] & 0xff) + k6 * (gray[offset + mWidth + col - 1] & 0xff) + k7 * (gray[offset + mWidth + col] & 0xff) + k8 * (gray[offset + mWidth + col + 1] & 0xff); r = sr; r = r > 255 ? 255 :( (r < 0) ? 0: r); output[offset+col]= r; // for next pixel sr = 0; } } return output; } /** * 计算方差 */ private double calcVariance(int [] values) { double variance = 0;//方差 double average = 0;//平均数 int i,len = values.length; double sum=0, sum2=0; for(i = 0; i< len; i ++){ sum += values[i]; } average = sum/ len; for(i = 0; i < len; i++){ sum2 += ((double)values[i]-average)*((double)values[i]-average); } variance = sum2/ len; return variance; } }
true
37480_2
public class Solution885 { public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { int size = rows * cols; int x = rStart, y = cStart; // 返回的二维矩阵 int[][] matrix = new int[size][2]; // 传入的参数就是入口第一个 matrix[0][0] = rStart; matrix[0][1] = cStart; // 作为数量 int z = 1; // 步进,1,1,2,2,3,3,4 ... 螺旋矩阵的增长 int a = 1; // 方向 1 表示右,2 表示下,3 表示左,4 表示上 int dir = 1; while (z < size) { for (int i = 0; i < 2; i++) { for (int j = 0; j < a; j++) { // 处理方向 if (dir % 4 == 1) { y++; } else if (dir % 4 == 2) { x++; } else if (dir % 4 == 3) { y--; } else { x--; } // 如果在实际矩阵内 if (x < rows && y < cols && x >= 0 && y >= 0) { matrix[z][0] = x; matrix[z][1] = y; z++; } } // 转变方向 dir++; } // 步进++ a++; } return matrix; } }
Nicksxs/Nicksxs.github.io
code/Solution885.java
367
// 作为数量
line_comment
zh-cn
public class Solution885 { public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { int size = rows * cols; int x = rStart, y = cStart; // 返回的二维矩阵 int[][] matrix = new int[size][2]; // 传入的参数就是入口第一个 matrix[0][0] = rStart; matrix[0][1] = cStart; // 作为 <SUF> int z = 1; // 步进,1,1,2,2,3,3,4 ... 螺旋矩阵的增长 int a = 1; // 方向 1 表示右,2 表示下,3 表示左,4 表示上 int dir = 1; while (z < size) { for (int i = 0; i < 2; i++) { for (int j = 0; j < a; j++) { // 处理方向 if (dir % 4 == 1) { y++; } else if (dir % 4 == 2) { x++; } else if (dir % 4 == 3) { y--; } else { x--; } // 如果在实际矩阵内 if (x < rows && y < cols && x >= 0 && y >= 0) { matrix[z][0] = x; matrix[z][1] = y; z++; } } // 转变方向 dir++; } // 步进++ a++; } return matrix; } }
false
38356_0
/* * 分支结构1: if-else条件判断结构 * * 1.格式 * if(条件表达式){ * 语句块; * } * * 2.格式2 * if(条件表达式){ * 语句块1; * }else { * 语句块2; * } * * 3. 格式3 * if(条件表达式1){ * 语句块1; * }else if(条件表达式2){ * 语句块2; * } else { * 语句块n+1; * } * * TODO: * 1.如果多个条件表达式之间没有交集(理解是互斥关系),则哪个条件表达式声明在上面,哪个条件表达式在下面都可以 * 2.如果多个条件表达式之间是包含关系,则需要将范围小的条件表达式声明在范围大的条件表达式上面。否则范围小的条件表达式不会被执行 * 3.从开发经验来说,没有写过超过三层的if-else结构 * 4. 如果if-else中的执行语句块中只有一行执行语句,则此执行语句所在的一对{}可以省略,但是不建议省略 * * * */ public class c1 { } class IfElseTest{ public static void main(String[] args){ int heartBeats = 89; if (60 >= heartBeats && heartBeats > 100){ System.out.println("More check "); } System.out.println("Finish"); } } class NumberTest{ public static void main(String[] args){ int num = 11; if (num%2==0){ System.out.println("Yes"); }else { System.out.println("No"); } } } class IfElseIfTest{ public static void main(String[] args){ int grade = 80; if(grade==100){ System.out.println("race car"); } else if (grade>80 && grade<=99) { System.out.println("bike"); } else if (grade>=60 && grade <=80) { System.out.println("playground"); } else { System.out.println("nothing"); } } }
Niki9001/Java-Study-charpter2
src/c1.java
551
/* * 分支结构1: if-else条件判断结构 * * 1.格式 * if(条件表达式){ * 语句块; * } * * 2.格式2 * if(条件表达式){ * 语句块1; * }else { * 语句块2; * } * * 3. 格式3 * if(条件表达式1){ * 语句块1; * }else if(条件表达式2){ * 语句块2; * } else { * 语句块n+1; * } * * TODO: * 1.如果多个条件表达式之间没有交集(理解是互斥关系),则哪个条件表达式声明在上面,哪个条件表达式在下面都可以 * 2.如果多个条件表达式之间是包含关系,则需要将范围小的条件表达式声明在范围大的条件表达式上面。否则范围小的条件表达式不会被执行 * 3.从开发经验来说,没有写过超过三层的if-else结构 * 4. 如果if-else中的执行语句块中只有一行执行语句,则此执行语句所在的一对{}可以省略,但是不建议省略 * * * */
block_comment
zh-cn
/* * 分支结 <SUF>*/ public class c1 { } class IfElseTest{ public static void main(String[] args){ int heartBeats = 89; if (60 >= heartBeats && heartBeats > 100){ System.out.println("More check "); } System.out.println("Finish"); } } class NumberTest{ public static void main(String[] args){ int num = 11; if (num%2==0){ System.out.println("Yes"); }else { System.out.println("No"); } } } class IfElseIfTest{ public static void main(String[] args){ int grade = 80; if(grade==100){ System.out.println("race car"); } else if (grade>80 && grade<=99) { System.out.println("bike"); } else if (grade>=60 && grade <=80) { System.out.println("playground"); } else { System.out.println("nothing"); } } }
false
15900_0
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //对于多个测试用例写个while循环 while (scanner.hasNext()) { //预算 int N = scanner.nextInt()/10; //商品数 int m = scanner.nextInt(); //价格数组 int[] price = new int[m]; //重要度*价格 int[] value = new int[m]; //主件还是附件 附件的isMain记录的是主件号 int[] isMain = new int[m]; for(int i=0; i<m; i++) { price[i] = scanner.nextInt()/10; value[i] = scanner.nextInt() * price[i]; isMain[i] = scanner.nextInt(); } int[][] dp = new int[m+1][N+1]; //dp[i][j]表示用j钱购买i件物品的总价值 背包中总价值 for(int i=1;i<=m;i++) { for(int j=1;j<=N;j++) { if(isMain[i-1]==0) { //表示为主件 if(j >= price[i-1]) { //买-->dp[i][j]=dp[i-1][j-price[i-1]]+value[i-1] //不买-->dp[i][j]=dp[i-1][j] dp[i][j]=Math.max(dp[i-1][j],dp[i-1][j-price[i-1]]+value[i-1]); //分别表示不买第i件和买第i件物品之后的最大价值 }else { dp[i][j]=dp[i-1][j]; } } else { //表示为附件,附件需要购买主件 if(j >= price[i-1]+price[isMain[i-1]-1]) { dp[i][j]=Math.max(dp[i-1][j] ,dp[i-1][j-price[i-1]-price[isMain[i-1]-1]]+value[i-1]+value[isMain[i-1]-1]); } else{ dp[i][j]=dp[i-1][j]; } } } } System.out.println(dp[m][N] * 10); } scanner.close(); } }
NjustJiaweihan/NowCoder_HuaWei
16.java
605
//对于多个测试用例写个while循环
line_comment
zh-cn
import java.util.*; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); //对于 <SUF> while (scanner.hasNext()) { //预算 int N = scanner.nextInt()/10; //商品数 int m = scanner.nextInt(); //价格数组 int[] price = new int[m]; //重要度*价格 int[] value = new int[m]; //主件还是附件 附件的isMain记录的是主件号 int[] isMain = new int[m]; for(int i=0; i<m; i++) { price[i] = scanner.nextInt()/10; value[i] = scanner.nextInt() * price[i]; isMain[i] = scanner.nextInt(); } int[][] dp = new int[m+1][N+1]; //dp[i][j]表示用j钱购买i件物品的总价值 背包中总价值 for(int i=1;i<=m;i++) { for(int j=1;j<=N;j++) { if(isMain[i-1]==0) { //表示为主件 if(j >= price[i-1]) { //买-->dp[i][j]=dp[i-1][j-price[i-1]]+value[i-1] //不买-->dp[i][j]=dp[i-1][j] dp[i][j]=Math.max(dp[i-1][j],dp[i-1][j-price[i-1]]+value[i-1]); //分别表示不买第i件和买第i件物品之后的最大价值 }else { dp[i][j]=dp[i-1][j]; } } else { //表示为附件,附件需要购买主件 if(j >= price[i-1]+price[isMain[i-1]-1]) { dp[i][j]=Math.max(dp[i-1][j] ,dp[i-1][j-price[i-1]-price[isMain[i-1]-1]]+value[i-1]+value[isMain[i-1]-1]); } else{ dp[i][j]=dp[i-1][j]; } } } } System.out.println(dp[m][N] * 10); } scanner.close(); } }
true
37943_11
package pass.ir; import ir.MyModule; import ir.Use; import ir.values.Constants.ConstantInt; import ir.values.Function; import ir.values.GlobalVariable; import ir.values.Value; import ir.values.instructions.Instruction; import ir.values.instructions.MemInst.GEPInst; import ir.values.instructions.MemInst.StoreInst; import ir.values.instructions.TerminatorInst.BrInst; import ir.values.instructions.TerminatorInst.CallInst; import ir.values.instructions.TerminatorInst.RetInst; import java.util.ArrayList; import java.util.HashSet; import pass.Pass.IRPass; import util.IList.INode; public class InterProceduralDCE implements IRPass { @Override public String getName() { return "interproceduraldce"; } /* * todo * 这个pass需要在mem2reg之前调用 * 1.跨过程的数据流好麻啊,失败了失败了失败了失败了失败了 * 2.如果一个函数的返回值实际上没被使用过,那么标记这个函数,并且把其所有返回值更换为CONST0 * :假设:使用了与输出的BUILTIN函数相关的函数的与被BUILTIN函数使用的所有值都是不可删除的 * :跑这个之前跑一次inter procedural ana与bb pred succ * :如果一个函数的所有返回值在所有地方都没有用到(递归函数的情况要进行特判),就把这个函数的所有返回值替换为Const0并且接触Ret的关系 * :对每个gv判断其在每个函数里面是否有用(指通过use关系和输出函数相连接),如果在所有函数里面都没用,就把这个gv删除 * 根据去年median的尿性,我猜测会 * 1.出个一个函数有两个出口,一个是对自己的尾调用,一个是返回一个p用没有但是算了一堆的东西 * 2.出个没有用但是在很多函数间计算了好多次的全局变量 * * */ MyModule m; HashSet<Function> funcs = new HashSet<>();//输出函数 HashSet<Function> needtokeep = new HashSet<>(); HashSet<Value> cd = new HashSet<>();//can't be deleted private boolean changed = false; HashSet<Function> optedFunc = new HashSet<>(); @Override public void run(MyModule m) { this.m = m; for (INode<Function, MyModule> node : m.__functions) { var name = node.getVal().getName(); if (name.equals("putch") || name.equals("putarray") || name.equals("putint")) { funcs.add(node.getVal()); cd.add(node.getVal()); } } do { changed = false; removeUseLessRet(); removeUselessGV(); } while (changed); } //我们认为只有通过use关系向下搜索能够搜索到putch,putarray,putint,br,ret,call的全局变量是"有用"的全局变量 //对于ret,跟进分析返回值与传入参数的使用情况(麻) //对于"没用"的全局变量,保留他们的getint getch getarray(虽然应该没有出题人犯病输入一堆没用的数据,但只要有,那就赚了) private void removeUselessGV() { for (GlobalVariable __globalVariable : m.__globalVariables) { analyseGv(__globalVariable); if (happy) { relatedValues.forEach(value -> { if (value instanceof Instruction) { ((Instruction) value).CORemoveAllOperand(); ((Instruction) value).node.removeSelf(); } }); } } } private void funcArgsPreAnalyse() { } private ArrayList<Function> isUsefulInFunc = new ArrayList<>(); HashSet<Value> relatedValues = new HashSet<>(); ArrayList<RetInst> relatedRet = new ArrayList<>(); ArrayList<CallInst> relatedCall = new ArrayList<>(); ArrayList<BrInst> relatedBr = new ArrayList<>(); HashSet<Function> relatedFunc = new HashSet<>(); boolean happy = true; private void analyseGv(GlobalVariable gv) {// happy = true; relatedValues.clear(); relatedRet.clear(); relatedCall.clear(); relatedBr.clear(); findRelatedUsers(gv); for (Function f : funcs) { if (relatedFunc.contains(f)) { happy = false; return; } } if (!relatedBr.isEmpty()) { happy = false; return; } if (!relatedFunc.isEmpty()) { happy = false; return; } if (!relatedCall.isEmpty()) { happy = false; return; } if (!relatedRet.isEmpty()) { happy = false; return; } } private void findRelatedUsers(Value value) { if (relatedValues.contains(value)) { return; } if (value instanceof StoreInst) {//store要把user的两个operand都放进去 /* * store @a pointer * a和pointer有关联 * */ if (((StoreInst) value).getPointer() instanceof GEPInst) { findRelatedUsers(((GEPInst) ((StoreInst) value).getPointer()).getAimTo()); findRelatedUsers(((StoreInst) value).getVal()); } } if (value instanceof RetInst) { relatedRet.add((RetInst) value); } if (value instanceof CallInst) { relatedFunc.add(((CallInst) value).getFunc()); relatedCall.add((CallInst) value); } if (value instanceof BrInst) { relatedBr.add((BrInst) value); } relatedValues.add(value); value.getUsesList().forEach(use -> { findRelatedUsers(use.getUser()); }); } /* x没用但是函数内的dce消不掉 int t=2; * int foo(int j){ * int x =100; * t=t+1; * for(x<100 x=x+1); * if(j==0){ * return x; * } * return foo(j-1); * } * int main(){ * foo(114514); * return t; * } * */ //找到返回值没用的函数,把所有返回值改成ret0 //remove use less ret 和inter procedural gv dce 组合起来后 //实际上能够起到跨过程的局部变量的dce的作用,因为一个局部变量,能够和调用者交流的方式只有gv或者是ret private void removeUseLessRet() { for (INode<Function, MyModule> fnd : m.__functions) { var fun = fnd.getVal(); if (!fun.isBuiltin_() && fun.getType().getRetType().isIntegerTy()) { if (!fun.getName().equals("main")){ processOneFunc(fun); } } } } private void processOneFunc(Function fun) { var isUseful = false; var recursion = false; ArrayList<CallInst> innerCall = new ArrayList<>(); if (optedFunc.contains(fun)) { return; } //analyse all call for (Use use : fun.getUsesList()) { var inst = use.getUser(); if (inst instanceof CallInst) { if (((CallInst) inst).getBB().getParent().equals(fun)) { recursion = true; innerCall.add(((CallInst) inst)); } else { if (!inst.getUsesList().isEmpty()) { isUseful = true; } } } } if (isUseful) { return; } if (recursion) { for (CallInst call : innerCall) { if (call.getUsesList().size() > 1) { return; } else { if (!call.getUsesList().isEmpty()) { if (!(call.getUsesList().get(0).getUser() instanceof RetInst)) { return; } } } } //ok 是我们想要的形式 changed = true; optedFunc.add(fun); fun.getList_().forEach( bb -> { bb.getVal().getList().forEach(instnd -> { var val = instnd.getVal(); if (val instanceof RetInst) { val.CORemoveAllOperand(); val.COaddOperand(ConstantInt.CONST0()); } }); } ); } else { for (CallInst call : innerCall) { if (call.getUsesList().size() > 1) { return; } else { if (!call.getUsesList().isEmpty()) { if (!(call.getUsesList().get(0).getUser() instanceof RetInst)) { return; } } } } fun.getList_().forEach( bb -> { bb.getVal().getList().forEach(instnd -> { var val = instnd.getVal(); if (val instanceof RetInst) { val.CORemoveAllOperand(); val.COaddOperand(ConstantInt.CONST0()); } }); } ); } } }
No-SF-Work/ayame
src/pass/ir/InterProceduralDCE.java
2,154
//实际上能够起到跨过程的局部变量的dce的作用,因为一个局部变量,能够和调用者交流的方式只有gv或者是ret
line_comment
zh-cn
package pass.ir; import ir.MyModule; import ir.Use; import ir.values.Constants.ConstantInt; import ir.values.Function; import ir.values.GlobalVariable; import ir.values.Value; import ir.values.instructions.Instruction; import ir.values.instructions.MemInst.GEPInst; import ir.values.instructions.MemInst.StoreInst; import ir.values.instructions.TerminatorInst.BrInst; import ir.values.instructions.TerminatorInst.CallInst; import ir.values.instructions.TerminatorInst.RetInst; import java.util.ArrayList; import java.util.HashSet; import pass.Pass.IRPass; import util.IList.INode; public class InterProceduralDCE implements IRPass { @Override public String getName() { return "interproceduraldce"; } /* * todo * 这个pass需要在mem2reg之前调用 * 1.跨过程的数据流好麻啊,失败了失败了失败了失败了失败了 * 2.如果一个函数的返回值实际上没被使用过,那么标记这个函数,并且把其所有返回值更换为CONST0 * :假设:使用了与输出的BUILTIN函数相关的函数的与被BUILTIN函数使用的所有值都是不可删除的 * :跑这个之前跑一次inter procedural ana与bb pred succ * :如果一个函数的所有返回值在所有地方都没有用到(递归函数的情况要进行特判),就把这个函数的所有返回值替换为Const0并且接触Ret的关系 * :对每个gv判断其在每个函数里面是否有用(指通过use关系和输出函数相连接),如果在所有函数里面都没用,就把这个gv删除 * 根据去年median的尿性,我猜测会 * 1.出个一个函数有两个出口,一个是对自己的尾调用,一个是返回一个p用没有但是算了一堆的东西 * 2.出个没有用但是在很多函数间计算了好多次的全局变量 * * */ MyModule m; HashSet<Function> funcs = new HashSet<>();//输出函数 HashSet<Function> needtokeep = new HashSet<>(); HashSet<Value> cd = new HashSet<>();//can't be deleted private boolean changed = false; HashSet<Function> optedFunc = new HashSet<>(); @Override public void run(MyModule m) { this.m = m; for (INode<Function, MyModule> node : m.__functions) { var name = node.getVal().getName(); if (name.equals("putch") || name.equals("putarray") || name.equals("putint")) { funcs.add(node.getVal()); cd.add(node.getVal()); } } do { changed = false; removeUseLessRet(); removeUselessGV(); } while (changed); } //我们认为只有通过use关系向下搜索能够搜索到putch,putarray,putint,br,ret,call的全局变量是"有用"的全局变量 //对于ret,跟进分析返回值与传入参数的使用情况(麻) //对于"没用"的全局变量,保留他们的getint getch getarray(虽然应该没有出题人犯病输入一堆没用的数据,但只要有,那就赚了) private void removeUselessGV() { for (GlobalVariable __globalVariable : m.__globalVariables) { analyseGv(__globalVariable); if (happy) { relatedValues.forEach(value -> { if (value instanceof Instruction) { ((Instruction) value).CORemoveAllOperand(); ((Instruction) value).node.removeSelf(); } }); } } } private void funcArgsPreAnalyse() { } private ArrayList<Function> isUsefulInFunc = new ArrayList<>(); HashSet<Value> relatedValues = new HashSet<>(); ArrayList<RetInst> relatedRet = new ArrayList<>(); ArrayList<CallInst> relatedCall = new ArrayList<>(); ArrayList<BrInst> relatedBr = new ArrayList<>(); HashSet<Function> relatedFunc = new HashSet<>(); boolean happy = true; private void analyseGv(GlobalVariable gv) {// happy = true; relatedValues.clear(); relatedRet.clear(); relatedCall.clear(); relatedBr.clear(); findRelatedUsers(gv); for (Function f : funcs) { if (relatedFunc.contains(f)) { happy = false; return; } } if (!relatedBr.isEmpty()) { happy = false; return; } if (!relatedFunc.isEmpty()) { happy = false; return; } if (!relatedCall.isEmpty()) { happy = false; return; } if (!relatedRet.isEmpty()) { happy = false; return; } } private void findRelatedUsers(Value value) { if (relatedValues.contains(value)) { return; } if (value instanceof StoreInst) {//store要把user的两个operand都放进去 /* * store @a pointer * a和pointer有关联 * */ if (((StoreInst) value).getPointer() instanceof GEPInst) { findRelatedUsers(((GEPInst) ((StoreInst) value).getPointer()).getAimTo()); findRelatedUsers(((StoreInst) value).getVal()); } } if (value instanceof RetInst) { relatedRet.add((RetInst) value); } if (value instanceof CallInst) { relatedFunc.add(((CallInst) value).getFunc()); relatedCall.add((CallInst) value); } if (value instanceof BrInst) { relatedBr.add((BrInst) value); } relatedValues.add(value); value.getUsesList().forEach(use -> { findRelatedUsers(use.getUser()); }); } /* x没用但是函数内的dce消不掉 int t=2; * int foo(int j){ * int x =100; * t=t+1; * for(x<100 x=x+1); * if(j==0){ * return x; * } * return foo(j-1); * } * int main(){ * foo(114514); * return t; * } * */ //找到返回值没用的函数,把所有返回值改成ret0 //remove use less ret 和inter procedural gv dce 组合起来后 //实际 <SUF> private void removeUseLessRet() { for (INode<Function, MyModule> fnd : m.__functions) { var fun = fnd.getVal(); if (!fun.isBuiltin_() && fun.getType().getRetType().isIntegerTy()) { if (!fun.getName().equals("main")){ processOneFunc(fun); } } } } private void processOneFunc(Function fun) { var isUseful = false; var recursion = false; ArrayList<CallInst> innerCall = new ArrayList<>(); if (optedFunc.contains(fun)) { return; } //analyse all call for (Use use : fun.getUsesList()) { var inst = use.getUser(); if (inst instanceof CallInst) { if (((CallInst) inst).getBB().getParent().equals(fun)) { recursion = true; innerCall.add(((CallInst) inst)); } else { if (!inst.getUsesList().isEmpty()) { isUseful = true; } } } } if (isUseful) { return; } if (recursion) { for (CallInst call : innerCall) { if (call.getUsesList().size() > 1) { return; } else { if (!call.getUsesList().isEmpty()) { if (!(call.getUsesList().get(0).getUser() instanceof RetInst)) { return; } } } } //ok 是我们想要的形式 changed = true; optedFunc.add(fun); fun.getList_().forEach( bb -> { bb.getVal().getList().forEach(instnd -> { var val = instnd.getVal(); if (val instanceof RetInst) { val.CORemoveAllOperand(); val.COaddOperand(ConstantInt.CONST0()); } }); } ); } else { for (CallInst call : innerCall) { if (call.getUsesList().size() > 1) { return; } else { if (!call.getUsesList().isEmpty()) { if (!(call.getUsesList().get(0).getUser() instanceof RetInst)) { return; } } } } fun.getList_().forEach( bb -> { bb.getVal().getList().forEach(instnd -> { var val = instnd.getVal(); if (val instanceof RetInst) { val.CORemoveAllOperand(); val.COaddOperand(ConstantInt.CONST0()); } }); } ); } } }
true
65229_8
package com.mp4player.utils; import java.util.Stack; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Process; import android.util.Log; import android.widget.ListView; /** * see {@link android.os.AsyncTask} * <p><b>在系统基础上</b> * <ul> * <li>1. 增强并发能力,根据处理器个数设置线程开销</li> * <li>2. 大量线程并发状况下优化线程并发控制及调度策略</li> * <li>3. 支持子线程建立并执行{@link AsyncTask},{@link #onPostExecute(Object)}方法一定会在主线程执行</li> * </ul> * @author MaTianyu * 2014-1-30下午3:10:43 */ public abstract class AsyncTask<Params, Progress, Result> { private static final String TAG = "AsyncTask"; private static int CPU_COUNT = Runtime.getRuntime().availableProcessors(); static { Log.i(TAG, "CPU : " + CPU_COUNT); } /*********************************** 基本线程池(无容量限制) *******************************/ /** * 有N处理器,便长期保持N个活跃线程。 */ private static final int CORE_POOL_SIZE = CPU_COUNT; private static final int MAXIMUM_POOL_SIZE = Integer.MAX_VALUE; private static final int KEEP_ALIVE = 10; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new SynchronousQueue<Runnable>(); /** * An {@link Executor} that can be used to execute tasks in parallel. * 核心线程数为{@link #CORE_POOL_SIZE},不限制并发总线程数! * 这就使得任务总能得到执行,且高效执行少量(<={@link #CORE_POOL_SIZE})异步任务。 * 线程完成任务后保持{@link #KEEP_ALIVE}秒销毁,这段时间内可重用以应付短时间内较大量并发,提升性能。 * 它实际控制并执行线程任务。 */ public static final ThreadPoolExecutor mCachedSerialExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /*********************************** 线程并发控制器 *******************************/ /** * 并发量控制: 根据cpu能力控制一段时间内并发数量,并发过量大时采用Lru方式移除旧的异步任务,默认采用LIFO策略调度线程运作,开发者可选调度策略有LIFO、FIFO。 */ public static final Executor mLruSerialExecutor = new SmartSerialExecutor(); /** * 它大大改善Android自带异步任务框架的处理能力和速度。 * 默认地,它使用LIFO(后进先出)策略来调度线程,可将最新的任务快速执行,当然你自己可以换为FIFO调度策略。 * 这有助于用户当前任务优先完成(比如加载图片时,很容易做到当前屏幕上的图片优先加载)。 * * @author MaTianyu * 2014-2-3上午12:46:53 */ private static class SmartSerialExecutor implements Executor { /** * 这里使用{@link ArrayDequeCompat}当栈比{@link Stack}性能高 */ private ArrayDequeCompat<Runnable> mQueue = new ArrayDequeCompat<Runnable>(serialMaxCount); private ScheduleStrategy mStrategy = ScheduleStrategy.LIFO; private enum ScheduleStrategy { /** * 队列中最后加入的任务最先执行 */ LIFO, /** * 队列中最先加入的任务最先执行 */ FIFO; } /** * 一次同时并发的数量,根据处理器数量调节 * * <p>cpu count : 1 2 3 4 8 16 32 * <p>once(base*2): 1 2 3 4 8 16 32 * * <p>一个时间段内最多并发线程个数: * 双核手机:2 * 四核手机:4 * ... * 计算公式如下: */ private static int serialOneTime; /** * 并发最大数量,当投入的任务过多大于此值时,根据Lru规则,将最老的任务移除(将得不到执行) * <p>cpu count : 1 2 3 4 8 16 32 * <p>base(cpu+3) : 4 5 6 7 11 19 35 * <p>max(base*16): 64 80 96 112 176 304 560 */ private static int serialMaxCount; private int cpuCount = CPU_COUNT; private void reSettings(int cpuCount) { this.cpuCount = cpuCount; serialOneTime = cpuCount; serialMaxCount = (cpuCount + 3) * 16; // serialMaxCount = 30; } public SmartSerialExecutor() { reSettings(CPU_COUNT); } @Override public synchronized void execute(final Runnable command) { Runnable r = new Runnable() { @Override public void run() { command.run(); next(); } }; if (mCachedSerialExecutor.getActiveCount() < serialOneTime) { // 小于单次并发量直接运行 mCachedSerialExecutor.execute(r); } else { // 如果大于并发上限,那么移除最老的任务 if (mQueue.size() >= serialMaxCount) { mQueue.pollFirst(); } // 新任务放在队尾 mQueue.offerLast(r); } } public synchronized void next() { Runnable mActive; switch (mStrategy) { case LIFO : mActive = mQueue.pollLast(); break; case FIFO : mActive = mQueue.pollFirst(); break; default : mActive = mQueue.pollLast(); break; } if (mActive != null) mCachedSerialExecutor.execute(mActive); } } /*********************************** 其他 *******************************/ private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; protected static final InternalHandler sHandler; static { if (Looper.myLooper() != Looper.getMainLooper()) { sHandler = new InternalHandler(Looper.getMainLooper()); } else { sHandler = new InternalHandler(); } } private static volatile Executor sDefaultExecutor = mCachedSerialExecutor; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); private FinishedListener finishedListener; /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } /** @hide Used to force static handler to be created. */ public static void init() { sHandler.getLooper(); } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { Log.w(TAG, e.getMessage()); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ protected void onPreExecute() {} /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * * <p>This method won't be invoked if the task was cancelled.</p> * * @param result The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ protected void onPostExecute(Result result) {} /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ protected void onProgressUpdate(Progress... values) {} /** * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * <p>The default implementation simply invokes {@link #onCancelled()} and * ignores the result. If you write your own implementation, do not call * <code>super.onCancelled(result)</code>.</p> * * @param result The result, if any, computed in * {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled(Result result) { onCancelled(); } /** * <p>Applications should preferably override {@link #onCancelled(Object)}. * This method is invoked by the default implementation of * {@link #onCancelled(Object)}.</p> * * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled() {} /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from * {@link #doInBackground(Object[])} to end the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p>Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task.</p> * * <p>Calling this method will result in {@link #onCancelled(Object)} being * invoked on the UI thread after {@link #doInBackground(Object[])} * returns. Calling this method guarantees that {@link #onPostExecute(Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])} to finish the task as early as * possible.</p> * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p> Execute a task immediately. * * <p> This method must be invoked on the UI thread. * * <p> 用于重要、紧急、单独的异步任务,该Task立即得到执行。 * <p> 加载类似瀑布流时产生的大量并发(一定程度允许任务被剔除队列)时请用{@link AsyncTask#executeAllowingLoss(Object...)} * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. * * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTask<Params, Progress, Result> execute(final Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * <p> 用于瞬间大量并发的场景,比如,假设用户拖动{@link ListView}时如果需要加载大量图片,而拖动过去时间很久的用户已经看不到,允许任务丢失。 * <p> This method execute task wisely when a large number of task will be submitted. * @param params * @return */ public final AsyncTask<Params, Progress, Result> executeAllowingLoss(Params... params) { return executeOnExecutor(mLruSerialExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>This method is typically used with {@link #mCachedSerialExecutor} to * allow multiple tasks to run in parallel on a pool of threads managed by * AsyncTask, however you can also use your own {@link Executor} for custom * behavior. * * <p>This method must be invoked on the UI thread. * * @param exec The executor to use. {@link #mCachedSerialExecutor} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. * * @see #execute(Object[]) */ public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING : throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED : throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); default: break; } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * <p> 用于重要、紧急、单独的异步任务,该Runnable立即得到执行。 * <p> 加载类似瀑布流时产生的大量并发(任务数超出限制允许任务被剔除队列)时请用{@link AsyncTask#executeAllowingLoss(Runnable)} * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * <p> 用于瞬间大量并发的场景,比如,假设用户拖动{@link ListView}时如果需要启动大量异步线程,而拖动过去时间很久的用户已经看不到,允许任务丢失。 * <p> This method execute runnable wisely when a large number of task will be submitted. * <p> 任务数限制情况见{@link SmartSerialExecutor} * immediate execution for important or urgent task. * @param runnable */ public static void executeAllowingLoss(Runnable runnable) { mLruSerialExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate} on the UI thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. * * @param values The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); if (finishedListener != null) finishedListener.onCancelled(); } else { onPostExecute(result); if (finishedListener != null) finishedListener.onPostExecute(); } mStatus = Status.FINISHED; } protected FinishedListener getFinishedListener() { return finishedListener; } protected void setFinishedListener(FinishedListener finishedListener) { this.finishedListener = finishedListener; } private static class InternalHandler extends Handler { public InternalHandler() { super(); } public InternalHandler(Looper looper) { super(looper); } @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT : // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS : result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } public static interface FinishedListener { void onCancelled(); void onPostExecute(); } }
NoSuchBoyException/Android-MP4Player
src/com/mp4player/utils/AsyncTask.java
5,711
/** * 队列中最后加入的任务最先执行 */
block_comment
zh-cn
package com.mp4player.utils; import java.util.Stack; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.Process; import android.util.Log; import android.widget.ListView; /** * see {@link android.os.AsyncTask} * <p><b>在系统基础上</b> * <ul> * <li>1. 增强并发能力,根据处理器个数设置线程开销</li> * <li>2. 大量线程并发状况下优化线程并发控制及调度策略</li> * <li>3. 支持子线程建立并执行{@link AsyncTask},{@link #onPostExecute(Object)}方法一定会在主线程执行</li> * </ul> * @author MaTianyu * 2014-1-30下午3:10:43 */ public abstract class AsyncTask<Params, Progress, Result> { private static final String TAG = "AsyncTask"; private static int CPU_COUNT = Runtime.getRuntime().availableProcessors(); static { Log.i(TAG, "CPU : " + CPU_COUNT); } /*********************************** 基本线程池(无容量限制) *******************************/ /** * 有N处理器,便长期保持N个活跃线程。 */ private static final int CORE_POOL_SIZE = CPU_COUNT; private static final int MAXIMUM_POOL_SIZE = Integer.MAX_VALUE; private static final int KEEP_ALIVE = 10; private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final BlockingQueue<Runnable> sPoolWorkQueue = new SynchronousQueue<Runnable>(); /** * An {@link Executor} that can be used to execute tasks in parallel. * 核心线程数为{@link #CORE_POOL_SIZE},不限制并发总线程数! * 这就使得任务总能得到执行,且高效执行少量(<={@link #CORE_POOL_SIZE})异步任务。 * 线程完成任务后保持{@link #KEEP_ALIVE}秒销毁,这段时间内可重用以应付短时间内较大量并发,提升性能。 * 它实际控制并执行线程任务。 */ public static final ThreadPoolExecutor mCachedSerialExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); /*********************************** 线程并发控制器 *******************************/ /** * 并发量控制: 根据cpu能力控制一段时间内并发数量,并发过量大时采用Lru方式移除旧的异步任务,默认采用LIFO策略调度线程运作,开发者可选调度策略有LIFO、FIFO。 */ public static final Executor mLruSerialExecutor = new SmartSerialExecutor(); /** * 它大大改善Android自带异步任务框架的处理能力和速度。 * 默认地,它使用LIFO(后进先出)策略来调度线程,可将最新的任务快速执行,当然你自己可以换为FIFO调度策略。 * 这有助于用户当前任务优先完成(比如加载图片时,很容易做到当前屏幕上的图片优先加载)。 * * @author MaTianyu * 2014-2-3上午12:46:53 */ private static class SmartSerialExecutor implements Executor { /** * 这里使用{@link ArrayDequeCompat}当栈比{@link Stack}性能高 */ private ArrayDequeCompat<Runnable> mQueue = new ArrayDequeCompat<Runnable>(serialMaxCount); private ScheduleStrategy mStrategy = ScheduleStrategy.LIFO; private enum ScheduleStrategy { /** * 队列中 <SUF>*/ LIFO, /** * 队列中最先加入的任务最先执行 */ FIFO; } /** * 一次同时并发的数量,根据处理器数量调节 * * <p>cpu count : 1 2 3 4 8 16 32 * <p>once(base*2): 1 2 3 4 8 16 32 * * <p>一个时间段内最多并发线程个数: * 双核手机:2 * 四核手机:4 * ... * 计算公式如下: */ private static int serialOneTime; /** * 并发最大数量,当投入的任务过多大于此值时,根据Lru规则,将最老的任务移除(将得不到执行) * <p>cpu count : 1 2 3 4 8 16 32 * <p>base(cpu+3) : 4 5 6 7 11 19 35 * <p>max(base*16): 64 80 96 112 176 304 560 */ private static int serialMaxCount; private int cpuCount = CPU_COUNT; private void reSettings(int cpuCount) { this.cpuCount = cpuCount; serialOneTime = cpuCount; serialMaxCount = (cpuCount + 3) * 16; // serialMaxCount = 30; } public SmartSerialExecutor() { reSettings(CPU_COUNT); } @Override public synchronized void execute(final Runnable command) { Runnable r = new Runnable() { @Override public void run() { command.run(); next(); } }; if (mCachedSerialExecutor.getActiveCount() < serialOneTime) { // 小于单次并发量直接运行 mCachedSerialExecutor.execute(r); } else { // 如果大于并发上限,那么移除最老的任务 if (mQueue.size() >= serialMaxCount) { mQueue.pollFirst(); } // 新任务放在队尾 mQueue.offerLast(r); } } public synchronized void next() { Runnable mActive; switch (mStrategy) { case LIFO : mActive = mQueue.pollLast(); break; case FIFO : mActive = mQueue.pollFirst(); break; default : mActive = mQueue.pollLast(); break; } if (mActive != null) mCachedSerialExecutor.execute(mActive); } } /*********************************** 其他 *******************************/ private static final int MESSAGE_POST_RESULT = 0x1; private static final int MESSAGE_POST_PROGRESS = 0x2; protected static final InternalHandler sHandler; static { if (Looper.myLooper() != Looper.getMainLooper()) { sHandler = new InternalHandler(Looper.getMainLooper()); } else { sHandler = new InternalHandler(); } } private static volatile Executor sDefaultExecutor = mCachedSerialExecutor; private final WorkerRunnable<Params, Result> mWorker; private final FutureTask<Result> mFuture; private volatile Status mStatus = Status.PENDING; private final AtomicBoolean mCancelled = new AtomicBoolean(); private final AtomicBoolean mTaskInvoked = new AtomicBoolean(); private FinishedListener finishedListener; /** * Indicates the current status of the task. Each status will be set only once * during the lifetime of a task. */ public enum Status { /** * Indicates that the task has not been executed yet. */ PENDING, /** * Indicates that the task is running. */ RUNNING, /** * Indicates that {@link AsyncTask#onPostExecute} has finished. */ FINISHED, } /** @hide Used to force static handler to be created. */ public static void init() { sHandler.getLooper(); } /** @hide */ public static void setDefaultExecutor(Executor exec) { sDefaultExecutor = exec; } /** * Creates a new asynchronous task. This constructor must be invoked on the UI thread. */ public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return postResult(doInBackground(mParams)); } }; mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { Log.w(TAG, e.getMessage()); } catch (ExecutionException e) { throw new RuntimeException("An error occured while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } } private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } /** * Returns the current status of this task. * * @return The current status. */ public final Status getStatus() { return mStatus; } /** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task. * * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * * @return A result, defined by the subclass of this task. * * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ protected abstract Result doInBackground(Params... params); /** * Runs on the UI thread before {@link #doInBackground}. * * @see #onPostExecute * @see #doInBackground */ protected void onPreExecute() {} /** * <p>Runs on the UI thread after {@link #doInBackground}. The * specified result is the value returned by {@link #doInBackground}.</p> * * <p>This method won't be invoked if the task was cancelled.</p> * * @param result The result of the operation computed by {@link #doInBackground}. * * @see #onPreExecute * @see #doInBackground * @see #onCancelled(Object) */ protected void onPostExecute(Result result) {} /** * Runs on the UI thread after {@link #publishProgress} is invoked. * The specified values are the values passed to {@link #publishProgress}. * * @param values The values indicating progress. * * @see #publishProgress * @see #doInBackground */ protected void onProgressUpdate(Progress... values) {} /** * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * <p>The default implementation simply invokes {@link #onCancelled()} and * ignores the result. If you write your own implementation, do not call * <code>super.onCancelled(result)</code>.</p> * * @param result The result, if any, computed in * {@link #doInBackground(Object[])}, can be null * * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled(Result result) { onCancelled(); } /** * <p>Applications should preferably override {@link #onCancelled(Object)}. * This method is invoked by the default implementation of * {@link #onCancelled(Object)}.</p> * * <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and * {@link #doInBackground(Object[])} has finished.</p> * * @see #onCancelled(Object) * @see #cancel(boolean) * @see #isCancelled() */ protected void onCancelled() {} /** * Returns <tt>true</tt> if this task was cancelled before it completed * normally. If you are calling {@link #cancel(boolean)} on the task, * the value returned by this method should be checked periodically from * {@link #doInBackground(Object[])} to end the task as soon as possible. * * @return <tt>true</tt> if task was cancelled before it completed * * @see #cancel(boolean) */ public final boolean isCancelled() { return mCancelled.get(); } /** * <p>Attempts to cancel execution of this task. This attempt will * fail if the task has already completed, already been cancelled, * or could not be cancelled for some other reason. If successful, * and this task has not started when <tt>cancel</tt> is called, * this task should never run. If the task has already started, * then the <tt>mayInterruptIfRunning</tt> parameter determines * whether the thread executing this task should be interrupted in * an attempt to stop the task.</p> * * <p>Calling this method will result in {@link #onCancelled(Object)} being * invoked on the UI thread after {@link #doInBackground(Object[])} * returns. Calling this method guarantees that {@link #onPostExecute(Object)} * is never invoked. After invoking this method, you should check the * value returned by {@link #isCancelled()} periodically from * {@link #doInBackground(Object[])} to finish the task as early as * possible.</p> * * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this * task should be interrupted; otherwise, in-progress tasks are allowed * to complete. * * @return <tt>false</tt> if the task could not be cancelled, * typically because it has already completed normally; * <tt>true</tt> otherwise * * @see #isCancelled() * @see #onCancelled(Object) */ public final boolean cancel(boolean mayInterruptIfRunning) { mCancelled.set(true); return mFuture.cancel(mayInterruptIfRunning); } /** * Waits if necessary for the computation to complete, and then * retrieves its result. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. */ public final Result get() throws InterruptedException, ExecutionException { return mFuture.get(); } /** * Waits if necessary for at most the given time for the computation * to complete, and then retrieves its result. * * @param timeout Time to wait before cancelling the operation. * @param unit The time unit for the timeout. * * @return The computed result. * * @throws CancellationException If the computation was cancelled. * @throws ExecutionException If the computation threw an exception. * @throws InterruptedException If the current thread was interrupted * while waiting. * @throws TimeoutException If the wait timed out. */ public final Result get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return mFuture.get(timeout, unit); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p> Execute a task immediately. * * <p> This method must be invoked on the UI thread. * * <p> 用于重要、紧急、单独的异步任务,该Task立即得到执行。 * <p> 加载类似瀑布流时产生的大量并发(一定程度允许任务被剔除队列)时请用{@link AsyncTask#executeAllowingLoss(Object...)} * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. * * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) * @see #execute(Runnable) */ public final AsyncTask<Params, Progress, Result> execute(final Params... params) { return executeOnExecutor(sDefaultExecutor, params); } /** * <p> 用于瞬间大量并发的场景,比如,假设用户拖动{@link ListView}时如果需要加载大量图片,而拖动过去时间很久的用户已经看不到,允许任务丢失。 * <p> This method execute task wisely when a large number of task will be submitted. * @param params * @return */ public final AsyncTask<Params, Progress, Result> executeAllowingLoss(Params... params) { return executeOnExecutor(mLruSerialExecutor, params); } /** * Executes the task with the specified parameters. The task returns * itself (this) so that the caller can keep a reference to it. * * <p>This method is typically used with {@link #mCachedSerialExecutor} to * allow multiple tasks to run in parallel on a pool of threads managed by * AsyncTask, however you can also use your own {@link Executor} for custom * behavior. * * <p>This method must be invoked on the UI thread. * * @param exec The executor to use. {@link #mCachedSerialExecutor} is available as a * convenient process-wide thread pool for tasks that are loosely coupled. * @param params The parameters of the task. * * @return This instance of AsyncTask. * * @throws IllegalStateException If {@link #getStatus()} returns either * {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}. * * @see #execute(Object[]) */ public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING : throw new IllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED : throw new IllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); default: break; } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; exec.execute(mFuture); return this; } /** * Convenience version of {@link #execute(Object...)} for use with * a simple Runnable object. See {@link #execute(Object[])} for more * information on the order of execution. * <p> 用于重要、紧急、单独的异步任务,该Runnable立即得到执行。 * <p> 加载类似瀑布流时产生的大量并发(任务数超出限制允许任务被剔除队列)时请用{@link AsyncTask#executeAllowingLoss(Runnable)} * @see #execute(Object[]) * @see #executeOnExecutor(java.util.concurrent.Executor, Object[]) */ public static void execute(Runnable runnable) { sDefaultExecutor.execute(runnable); } /** * <p> 用于瞬间大量并发的场景,比如,假设用户拖动{@link ListView}时如果需要启动大量异步线程,而拖动过去时间很久的用户已经看不到,允许任务丢失。 * <p> This method execute runnable wisely when a large number of task will be submitted. * <p> 任务数限制情况见{@link SmartSerialExecutor} * immediate execution for important or urgent task. * @param runnable */ public static void executeAllowingLoss(Runnable runnable) { mLruSerialExecutor.execute(runnable); } /** * This method can be invoked from {@link #doInBackground} to * publish updates on the UI thread while the background computation is * still running. Each call to this method will trigger the execution of * {@link #onProgressUpdate} on the UI thread. * * {@link #onProgressUpdate} will note be called if the task has been * canceled. * * @param values The progress values to update the UI with. * * @see #onProgressUpdate * @see #doInBackground */ protected final void publishProgress(Progress... values) { if (!isCancelled()) { sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget(); } } private void finish(Result result) { if (isCancelled()) { onCancelled(result); if (finishedListener != null) finishedListener.onCancelled(); } else { onPostExecute(result); if (finishedListener != null) finishedListener.onPostExecute(); } mStatus = Status.FINISHED; } protected FinishedListener getFinishedListener() { return finishedListener; } protected void setFinishedListener(FinishedListener finishedListener) { this.finishedListener = finishedListener; } private static class InternalHandler extends Handler { public InternalHandler() { super(); } public InternalHandler(Looper looper) { super(looper); } @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"}) @Override public void handleMessage(Message msg) { AsyncTaskResult result = (AsyncTaskResult) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT : // There is only one result result.mTask.finish(result.mData[0]); break; case MESSAGE_POST_PROGRESS : result.mTask.onProgressUpdate(result.mData); break; } } } private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; } @SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } } public static interface FinishedListener { void onCancelled(); void onPostExecute(); } }
true
35688_29
//在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 // // 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 // // 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。 // // 说明: // // // 如果题目有解,该答案即为唯一答案。 // 输入数组均为非空数组,且长度相同。 // 输入数组中的元素均为非负数。 // // // 示例 1: // // 输入: //gas = [1,2,3,4,5] //cost = [3,4,5,1,2] // //输出: 3 // //解释: //从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油 //开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油 //开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油 //开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油 //开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油 //开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。 //因此,3 可为起始索引。 // // 示例 2: // // 输入: //gas = [2,3,4] //cost = [3,4,3] // //输出: -1 // //解释: //你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。 //我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油 //开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油 //开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油 //你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。 //因此,无论怎样,你都不可能绕环路行驶一周。 // Related Topics 贪心算法 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // 解题思路大概是遍历一遍数组,设定两个变量 // 第一个变量是总油量,如果总油量加起来还不够cost的,就宣布失败,返回-1 // 如果没失败,说明必有一个点是开始点 int total = 0; int cur = 0; int start = 0; for(int i = 0; i < gas.length; i++){ total += gas[i] - cost[i]; cur += gas[i] - cost[i]; if(cur < 0){ // 如果当前邮箱已经坚持不下去了,就从下一个节点处开始 cur = 0; start = i + 1; } } return total >= 0 ? start : -1; } } //leetcode submit region end(Prohibit modification and deletion)
Noahhhhha/leetcode
src/problem/greedy/[134]加油站.java
1,056
//开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
line_comment
zh-cn
//在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 // // 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 // // 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。 // // 说明: // // // 如果题目有解,该答案即为唯一答案。 // 输入数组均为非空数组,且长度相同。 // 输入数组中的元素均为非负数。 // // // 示例 1: // // 输入: //gas = [1,2,3,4,5] //cost = [3,4,5,1,2] // //输出: 3 // //解释: //从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油 //开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油 //开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油 //开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油 //开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油 //开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。 //因此,3 可为起始索引。 // // 示例 2: // // 输入: //gas = [2,3,4] //cost = [3,4,3] // //输出: -1 // //解释: //你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。 //我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油 //开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油 //开往 <SUF> //你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。 //因此,无论怎样,你都不可能绕环路行驶一周。 // Related Topics 贪心算法 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // 解题思路大概是遍历一遍数组,设定两个变量 // 第一个变量是总油量,如果总油量加起来还不够cost的,就宣布失败,返回-1 // 如果没失败,说明必有一个点是开始点 int total = 0; int cur = 0; int start = 0; for(int i = 0; i < gas.length; i++){ total += gas[i] - cost[i]; cur += gas[i] - cost[i]; if(cur < 0){ // 如果当前邮箱已经坚持不下去了,就从下一个节点处开始 cur = 0; start = i + 1; } } return total >= 0 ? start : -1; } } //leetcode submit region end(Prohibit modification and deletion)
false